zanmato1984 commented on code in PR #45001: URL: https://github.com/apache/arrow/pull/45001#discussion_r2224858452
########## docs/source/cpp/compute.rst: ########## @@ -1271,6 +1271,26 @@ Containment tests * \(8) Output is true iff :member:`MatchSubstringOptions::pattern` matches the corresponding input element at any position. + +Hash Functions +~~~~~~~~~~~~~~ + +Not to be confused with the "group by" functions, Hash functions produce an array of hash +values corresponding to the length of the input. Currently, these functions take a single +array as input. + ++---------------+-------+-------------+-------------+---------------+-------+ +| Function name | Arity | Input types | Output type | Options class | Notes | ++===============+=======+=============+=============+===============+=======+ +| hash32 | Unary | Any | UInt32 | | \(1) | ++---------------+-------+-------------+-------------+---------------+-------+ +| hash64 | Unary | Any | UInt64 | | \(1) | ++---------------+-------+-------------+-------------+---------------+-------+ + +* \(1) The implementation doesn't guarantee hash stability across different versions of Review Comment: Shall we also mention that they don't emit `null`s even for `null` values. ########## cpp/src/arrow/compute/api_scalar.h: ########## @@ -1786,5 +1786,42 @@ ARROW_EXPORT Result<Datum> NanosecondsBetween(const Datum& left, const Datum& ri /// \note API not yet finalized ARROW_EXPORT Result<Datum> MapLookup(const Datum& map, MapLookupOptions options, ExecContext* ctx = NULLPTR); + +/// \brief Construct a hash value for each row of the input. +/// +/// The result is an Array of length equal to the length of the input; however, the output +/// shall be a UInt32Array, with each element being a hash constructed from each row of +/// the input. If the input Array is a NestedArray, this means that each "attribute" or +/// "field" of the input NestedArray corresponding to the same "row" will collectively +/// produce a single uint32_t hash. At the moment, this function does not take options, +/// though these may be added in the future. +/// +/// \param[in] input_array input data to hash +/// \param[in] ctx function execution context, optional +/// \return elementwise hash values +/// +/// \since 21.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result<Datum> Hash32(const Datum& input_array, ExecContext* ctx = NULLPTR); + +/// \brief Construct a hash value for each row of the input. +/// +/// The result is an Array of length equal to the length of the input; however, the output +/// shall be a UInt64Array, with each element being a hash constructed from each row of +/// the input. If the input Array is a NestedArray, this means that each "attribute" or +/// "field" of the input NestedArray corresponding to the same "row" will collectively +/// produce a single uint64_t hash. At the moment, this function does not take options, +/// though these may be added in the future. +/// +/// \param[in] input_array input data to hash +/// \param[in] ctx function execution context, optional +/// \return elementwise hash values +/// +/// \since 21.0.0 Review Comment: ```suggestion /// \since 22.0.0 ``` ########## docs/source/cpp/compute.rst: ########## @@ -1271,6 +1271,26 @@ Containment tests * \(8) Output is true iff :member:`MatchSubstringOptions::pattern` matches the corresponding input element at any position. + +Hash Functions +~~~~~~~~~~~~~~ + +Not to be confused with the "group by" functions, Hash functions produce an array of hash +values corresponding to the length of the input. Currently, these functions take a single +array as input. + ++---------------+-------+-------------+-------------+---------------+-------+ +| Function name | Arity | Input types | Output type | Options class | Notes | ++===============+=======+=============+=============+===============+=======+ +| hash32 | Unary | Any | UInt32 | | \(1) | ++---------------+-------+-------------+-------------+---------------+-------+ +| hash64 | Unary | Any | UInt64 | | \(1) | ++---------------+-------+-------------+-------------+---------------+-------+ + +* \(1) The implementation doesn't guarantee hash stability across different versions of + the library. Union-, view- and run end encoded types are not supported yet. Review Comment: ```suggestion the library. Union, view and run end encoded types are not supported yet. ``` ########## cpp/src/arrow/compute/key_hash_benchmark.cc: ########## @@ -0,0 +1,125 @@ +// 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 <algorithm> +#include <cstdint> +#include <limits> +#include <random> +#include <string> +#include <vector> + +#include "benchmark/benchmark.h" + +#include "arrow/testing/gtest_util.h" +#include "arrow/testing/random.h" +#include "arrow/util/hashing.h" + +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/util_internal.h" + +namespace arrow { +namespace internal { + +namespace { +// copied from scalar_string_benchmark +constexpr auto kSeed = 0x94378165; + +static random::RandomArrayGenerator hashing_rng(kSeed); +} // namespace + +static void KeyHashIntegers32(benchmark::State& state) { // NOLINT non-const reference + auto test_vals = hashing_rng.Int32(10000, 0, std::numeric_limits<int32_t>::max()); + + // initialize the stack allocator + util::TempVectorStack stack_memallocator; + ASSERT_OK( + stack_memallocator.Init(compute::default_exec_context()->memory_pool(), + 3 * sizeof(int32_t) * util::MiniBatch::kMiniBatchLength)); + + // prepare the execution context for Hashing32 + compute::LightContext hash_ctx; + hash_ctx.hardware_flags = compute::default_exec_context()->cpu_info()->hardware_flags(); + hash_ctx.stack = &stack_memallocator; + + // allocate memory for results + ASSERT_OK_AND_ASSIGN(std::unique_ptr<Buffer> hash_buffer, + AllocateBuffer(test_vals->length() * sizeof(int32_t))); + + // run the benchmark + while (state.KeepRunning()) { + // Prepare input data structure for propagation to hash function + ASSERT_OK_AND_ASSIGN( + compute::KeyColumnArray input_keycol, + compute::ColumnArrayFromArrayData(test_vals->data(), 0, test_vals->length())); + + compute::Hashing32::HashMultiColumn( + {input_keycol}, &hash_ctx, + reinterpret_cast<uint32_t*>(hash_buffer->mutable_data())); + + // benchmark::DoNotOptimize(hash_buffer); Review Comment: ```suggestion ``` ########## cpp/src/arrow/compute/kernels/scalar_hash.cc: ########## @@ -0,0 +1,240 @@ +// 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 <algorithm> + +#include "arrow/array/array_base.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/light_array_internal.h" +#include "arrow/compute/util.h" +#include "arrow/result.h" + +namespace arrow { +namespace compute { +namespace internal { + +// Define symbols visible within `arrow::compute::internal` in this file; +// these symbols are not visible outside of this file. +namespace { + +// ------------------------------ +// Kernel implementations +// It is expected that HashArrowType is either UInt32Type or UInt64Type (default) + +template <typename ArrowType, typename Hasher> +struct FastHashScalar { + using c_type = typename ArrowType::c_type; + + static Result<KeyColumnArray> ToColumnArray( + const ArraySpan& array, LightContext* ctx, + const uint8_t* list_values_buffer = nullptr) { + KeyColumnMetadata metadata; + const uint8_t* validity_buffer = nullptr; + const uint8_t* fixed_length_buffer = nullptr; + const uint8_t* var_length_buffer = nullptr; + + if (array.GetBuffer(0) != nullptr) { + validity_buffer = array.GetBuffer(0)->data(); + } + if (array.GetBuffer(1) != nullptr) { + fixed_length_buffer = array.GetBuffer(1)->data(); + } + + auto type = array.type; + auto type_id = type->id(); + if (type_id == Type::NA) { + metadata = KeyColumnMetadata(true, 0, true); + } else if (type_id == Type::BOOL) { + metadata = KeyColumnMetadata(true, 0); + } else if (is_fixed_width(type_id)) { + metadata = KeyColumnMetadata(true, type->bit_width() / 8); + } else if (is_binary_like(type_id)) { + metadata = KeyColumnMetadata(false, sizeof(uint32_t)); + var_length_buffer = array.GetBuffer(2)->data(); + } else if (is_large_binary_like(type_id)) { + metadata = KeyColumnMetadata(false, sizeof(uint64_t)); + var_length_buffer = array.GetBuffer(2)->data(); + } else if (type_id == Type::MAP) { + metadata = KeyColumnMetadata(false, sizeof(uint32_t)); + var_length_buffer = list_values_buffer; + } else if (type_id == Type::LIST) { + metadata = KeyColumnMetadata(false, sizeof(uint32_t)); + var_length_buffer = list_values_buffer; + } else if (type_id == Type::LARGE_LIST) { + metadata = KeyColumnMetadata(false, sizeof(uint64_t)); + var_length_buffer = list_values_buffer; + } else if (type_id == Type::FIXED_SIZE_LIST) { + auto list_type = checked_cast<const FixedSizeListType*>(type); + metadata = KeyColumnMetadata(true, list_type->list_size()); + fixed_length_buffer = list_values_buffer; + } else { + return Status::TypeError("Unsupported column data type ", type->name(), + " used with hash32/hash64 compute kernel"); + } + + return KeyColumnArray(metadata, array.length, validity_buffer, fixed_length_buffer, + var_length_buffer); + } + + static Result<std::shared_ptr<ArrayData>> HashChild(const ArraySpan& array, + const ArraySpan& child, + LightContext* hash_ctx, + MemoryPool* memory_pool) { + auto arrow_type = TypeTraits<ArrowType>::type_singleton(); + auto buffer_size = child.length * sizeof(c_type); + ARROW_ASSIGN_OR_RAISE(auto buffer, AllocateBuffer(buffer_size, memory_pool)); + ARROW_RETURN_NOT_OK( + HashArray(child, hash_ctx, memory_pool, buffer->mutable_data_as<c_type>())); + return ArrayData::Make(arrow_type, child.length, + {array.GetBuffer(0), std::move(buffer)}, array.null_count); + } + + static Status HashArray(const ArraySpan& array, LightContext* hash_ctx, + MemoryPool* memory_pool, c_type* out) { + // KeyColumnArray objects are being passed to the hashing utility + KeyColumnArray column; + std::vector<KeyColumnArray> columns(1); + + auto type_id = array.type->id(); + if (type_id == Type::EXTENSION) { + auto extension_type = checked_cast<const ExtensionType*>(array.type); + auto storage_array = array; + storage_array.type = extension_type->storage_type().get(); + return HashArray(storage_array, hash_ctx, memory_pool, out); + } + + if (type_id == Type::STRUCT) { + std::vector<std::shared_ptr<ArrayData>> child_hashes(array.child_data.size()); + columns.resize(array.child_data.size()); + for (size_t i = 0; i < array.child_data.size(); i++) { + auto child = array.child_data[i]; + if (is_nested(child.type->id())) { + ARROW_ASSIGN_OR_RAISE(child_hashes[i], + HashChild(array, child, hash_ctx, memory_pool)); + ARROW_ASSIGN_OR_RAISE(column, ToColumnArray(*child_hashes[i], hash_ctx)); + } else { + ARROW_ASSIGN_OR_RAISE(column, ToColumnArray(child, hash_ctx)); + } + columns[i] = column.Slice(array.offset, array.length); + } + Hasher::HashMultiColumn(columns, hash_ctx, out); + } else if (is_list_like(type_id)) { + auto values = array.child_data[0]; + ARROW_ASSIGN_OR_RAISE(auto value_hashes, + HashChild(array, values, hash_ctx, memory_pool)); + ARROW_ASSIGN_OR_RAISE( + column, ToColumnArray(array, hash_ctx, value_hashes->buffers[1]->data())); Review Comment: Is it possible to make a copy of the `array`, and set `array_copy.buffers[2] = value_hashes->buffers[1]->data()`? This way, function `ToColumnArray` won't need the extra `list_values_buffer` parameter. ########## cpp/src/arrow/compute/key_hash_benchmark.cc: ########## @@ -0,0 +1,125 @@ +// 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 <algorithm> +#include <cstdint> +#include <limits> +#include <random> +#include <string> +#include <vector> + +#include "benchmark/benchmark.h" + +#include "arrow/testing/gtest_util.h" +#include "arrow/testing/random.h" +#include "arrow/util/hashing.h" + +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/util_internal.h" + +namespace arrow { +namespace internal { + +namespace { +// copied from scalar_string_benchmark +constexpr auto kSeed = 0x94378165; + +static random::RandomArrayGenerator hashing_rng(kSeed); +} // namespace + +static void KeyHashIntegers32(benchmark::State& state) { // NOLINT non-const reference + auto test_vals = hashing_rng.Int32(10000, 0, std::numeric_limits<int32_t>::max()); + + // initialize the stack allocator + util::TempVectorStack stack_memallocator; + ASSERT_OK( + stack_memallocator.Init(compute::default_exec_context()->memory_pool(), + 3 * sizeof(int32_t) * util::MiniBatch::kMiniBatchLength)); + + // prepare the execution context for Hashing32 + compute::LightContext hash_ctx; + hash_ctx.hardware_flags = compute::default_exec_context()->cpu_info()->hardware_flags(); + hash_ctx.stack = &stack_memallocator; + + // allocate memory for results + ASSERT_OK_AND_ASSIGN(std::unique_ptr<Buffer> hash_buffer, + AllocateBuffer(test_vals->length() * sizeof(int32_t))); + + // run the benchmark + while (state.KeepRunning()) { + // Prepare input data structure for propagation to hash function + ASSERT_OK_AND_ASSIGN( + compute::KeyColumnArray input_keycol, + compute::ColumnArrayFromArrayData(test_vals->data(), 0, test_vals->length())); + + compute::Hashing32::HashMultiColumn( + {input_keycol}, &hash_ctx, + reinterpret_cast<uint32_t*>(hash_buffer->mutable_data())); + + // benchmark::DoNotOptimize(hash_buffer); Review Comment: Useless? ########## cpp/src/arrow/compute/kernels/scalar_hash.cc: ########## @@ -0,0 +1,240 @@ +// 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 <algorithm> + +#include "arrow/array/array_base.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/light_array_internal.h" +#include "arrow/compute/util.h" +#include "arrow/result.h" + +namespace arrow { +namespace compute { +namespace internal { + +// Define symbols visible within `arrow::compute::internal` in this file; +// these symbols are not visible outside of this file. +namespace { + +// ------------------------------ +// Kernel implementations +// It is expected that HashArrowType is either UInt32Type or UInt64Type (default) + +template <typename ArrowType, typename Hasher> +struct FastHashScalar { + using c_type = typename ArrowType::c_type; + + static Result<KeyColumnArray> ToColumnArray( + const ArraySpan& array, LightContext* ctx, + const uint8_t* list_values_buffer = nullptr) { Review Comment: ```suggestion const ArraySpan& array, const uint8_t* list_values_buffer = nullptr) { ``` ########## cpp/src/arrow/compute/kernels/scalar_hash.cc: ########## @@ -0,0 +1,240 @@ +// 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 <algorithm> + +#include "arrow/array/array_base.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/light_array_internal.h" +#include "arrow/compute/util.h" +#include "arrow/result.h" + +namespace arrow { +namespace compute { +namespace internal { + +// Define symbols visible within `arrow::compute::internal` in this file; +// these symbols are not visible outside of this file. +namespace { + +// ------------------------------ +// Kernel implementations +// It is expected that HashArrowType is either UInt32Type or UInt64Type (default) + +template <typename ArrowType, typename Hasher> +struct FastHashScalar { + using c_type = typename ArrowType::c_type; + + static Result<KeyColumnArray> ToColumnArray( + const ArraySpan& array, LightContext* ctx, + const uint8_t* list_values_buffer = nullptr) { + KeyColumnMetadata metadata; + const uint8_t* validity_buffer = nullptr; + const uint8_t* fixed_length_buffer = nullptr; + const uint8_t* var_length_buffer = nullptr; + + if (array.GetBuffer(0) != nullptr) { + validity_buffer = array.GetBuffer(0)->data(); + } + if (array.GetBuffer(1) != nullptr) { + fixed_length_buffer = array.GetBuffer(1)->data(); + } + + auto type = array.type; + auto type_id = type->id(); + if (type_id == Type::NA) { + metadata = KeyColumnMetadata(true, 0, true); + } else if (type_id == Type::BOOL) { + metadata = KeyColumnMetadata(true, 0); + } else if (is_fixed_width(type_id)) { + metadata = KeyColumnMetadata(true, type->bit_width() / 8); + } else if (is_binary_like(type_id)) { + metadata = KeyColumnMetadata(false, sizeof(uint32_t)); + var_length_buffer = array.GetBuffer(2)->data(); + } else if (is_large_binary_like(type_id)) { + metadata = KeyColumnMetadata(false, sizeof(uint64_t)); + var_length_buffer = array.GetBuffer(2)->data(); + } else if (type_id == Type::MAP) { + metadata = KeyColumnMetadata(false, sizeof(uint32_t)); + var_length_buffer = list_values_buffer; + } else if (type_id == Type::LIST) { + metadata = KeyColumnMetadata(false, sizeof(uint32_t)); + var_length_buffer = list_values_buffer; + } else if (type_id == Type::LARGE_LIST) { + metadata = KeyColumnMetadata(false, sizeof(uint64_t)); + var_length_buffer = list_values_buffer; + } else if (type_id == Type::FIXED_SIZE_LIST) { + auto list_type = checked_cast<const FixedSizeListType*>(type); + metadata = KeyColumnMetadata(true, list_type->list_size()); + fixed_length_buffer = list_values_buffer; + } else { + return Status::TypeError("Unsupported column data type ", type->name(), + " used with hash32/hash64 compute kernel"); + } + + return KeyColumnArray(metadata, array.length, validity_buffer, fixed_length_buffer, + var_length_buffer); + } + + static Result<std::shared_ptr<ArrayData>> HashChild(const ArraySpan& array, + const ArraySpan& child, + LightContext* hash_ctx, + MemoryPool* memory_pool) { + auto arrow_type = TypeTraits<ArrowType>::type_singleton(); + auto buffer_size = child.length * sizeof(c_type); + ARROW_ASSIGN_OR_RAISE(auto buffer, AllocateBuffer(buffer_size, memory_pool)); Review Comment: This is actually allocating memory within a kernel that claims to be `MemAllocation::PREALLOCATE`. I'm not sure if this is problematic given that, IIRC, we may do tricky things for `MemAllocation::PREALLOCATE` kernels evaluation. @pitrou would you help to confirm that? ########## cpp/src/arrow/util/hashing_benchmark.cc: ########## @@ -25,11 +25,21 @@ #include "benchmark/benchmark.h" #include "arrow/testing/gtest_util.h" +#include "arrow/testing/random.h" #include "arrow/util/hashing.h" +#include "arrow/array/builder_primitive.h" Review Comment: Why is this separated? ########## cpp/src/arrow/compute/CMakeLists.txt: ########## @@ -138,6 +138,19 @@ add_arrow_compute_test(row_test add_arrow_benchmark(function_benchmark PREFIX "arrow-compute") +if(ARROW_TEST_LINKAGE STREQUAL "static") + set(ARROW_COMPUTE_BENCHMARK_LINK_LIBS arrow_compute_static) +else() + set(ARROW_COMPUTE_BENCHMARK_LINK_LIBS arrow_compute_shared) +endif() +if(ARROW_COMPUTE) Review Comment: I think these might be unnecessary if you rebase to the latest main branch? ########## cpp/src/arrow/compute/kernels/scalar_hash.cc: ########## @@ -0,0 +1,240 @@ +// 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 <algorithm> + +#include "arrow/array/array_base.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/light_array_internal.h" +#include "arrow/compute/util.h" +#include "arrow/result.h" + +namespace arrow { +namespace compute { +namespace internal { + +// Define symbols visible within `arrow::compute::internal` in this file; +// these symbols are not visible outside of this file. +namespace { + +// ------------------------------ +// Kernel implementations +// It is expected that HashArrowType is either UInt32Type or UInt64Type (default) + +template <typename ArrowType, typename Hasher> +struct FastHashScalar { + using c_type = typename ArrowType::c_type; + + static Result<KeyColumnArray> ToColumnArray( Review Comment: Since this function is not template argument depending, can we move it outside the class to reduce the code generation? ########## cpp/src/arrow/compute/api_scalar.h: ########## @@ -1786,5 +1786,42 @@ ARROW_EXPORT Result<Datum> NanosecondsBetween(const Datum& left, const Datum& ri /// \note API not yet finalized ARROW_EXPORT Result<Datum> MapLookup(const Datum& map, MapLookupOptions options, ExecContext* ctx = NULLPTR); + +/// \brief Construct a hash value for each row of the input. +/// +/// The result is an Array of length equal to the length of the input; however, the output +/// shall be a UInt32Array, with each element being a hash constructed from each row of +/// the input. If the input Array is a NestedArray, this means that each "attribute" or +/// "field" of the input NestedArray corresponding to the same "row" will collectively +/// produce a single uint32_t hash. At the moment, this function does not take options, +/// though these may be added in the future. +/// +/// \param[in] input_array input data to hash +/// \param[in] ctx function execution context, optional +/// \return elementwise hash values +/// +/// \since 21.0.0 +/// \note API not yet finalized +ARROW_EXPORT +Result<Datum> Hash32(const Datum& input_array, ExecContext* ctx = NULLPTR); + +/// \brief Construct a hash value for each row of the input. +/// +/// The result is an Array of length equal to the length of the input; however, the output +/// shall be a UInt64Array, with each element being a hash constructed from each row of +/// the input. If the input Array is a NestedArray, this means that each "attribute" or +/// "field" of the input NestedArray corresponding to the same "row" will collectively +/// produce a single uint64_t hash. At the moment, this function does not take options, +/// though these may be added in the future. +/// +/// \param[in] input_array input data to hash +/// \param[in] ctx function execution context, optional +/// \return elementwise hash values +/// +/// \since 21.0.0 Review Comment: Hopefully it can land in 22.0.0. ########## cpp/src/arrow/compute/api_scalar.h: ########## @@ -1786,5 +1786,42 @@ ARROW_EXPORT Result<Datum> NanosecondsBetween(const Datum& left, const Datum& ri /// \note API not yet finalized ARROW_EXPORT Result<Datum> MapLookup(const Datum& map, MapLookupOptions options, ExecContext* ctx = NULLPTR); + +/// \brief Construct a hash value for each row of the input. +/// +/// The result is an Array of length equal to the length of the input; however, the output +/// shall be a UInt32Array, with each element being a hash constructed from each row of +/// the input. If the input Array is a NestedArray, this means that each "attribute" or +/// "field" of the input NestedArray corresponding to the same "row" will collectively +/// produce a single uint32_t hash. At the moment, this function does not take options, +/// though these may be added in the future. +/// +/// \param[in] input_array input data to hash +/// \param[in] ctx function execution context, optional +/// \return elementwise hash values +/// +/// \since 21.0.0 Review Comment: ```suggestion /// \since 22.0.0 ``` ########## cpp/src/arrow/compute/kernels/scalar_hash.cc: ########## @@ -0,0 +1,240 @@ +// 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 <algorithm> + +#include "arrow/array/array_base.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/light_array_internal.h" +#include "arrow/compute/util.h" +#include "arrow/result.h" + +namespace arrow { +namespace compute { +namespace internal { + +// Define symbols visible within `arrow::compute::internal` in this file; +// these symbols are not visible outside of this file. +namespace { + +// ------------------------------ +// Kernel implementations +// It is expected that HashArrowType is either UInt32Type or UInt64Type (default) + +template <typename ArrowType, typename Hasher> +struct FastHashScalar { + using c_type = typename ArrowType::c_type; + + static Result<KeyColumnArray> ToColumnArray( + const ArraySpan& array, LightContext* ctx, + const uint8_t* list_values_buffer = nullptr) { Review Comment: The `ctx` isn't used within the function. ########## docs/source/cpp/compute.rst: ########## @@ -1271,6 +1271,26 @@ Containment tests * \(8) Output is true iff :member:`MatchSubstringOptions::pattern` matches the corresponding input element at any position. + +Hash Functions +~~~~~~~~~~~~~~ + +Not to be confused with the "group by" functions, Hash functions produce an array of hash +values corresponding to the length of the input. Currently, these functions take a single +array as input. + ++---------------+-------+-------------+-------------+---------------+-------+ +| Function name | Arity | Input types | Output type | Options class | Notes | ++===============+=======+=============+=============+===============+=======+ +| hash32 | Unary | Any | UInt32 | | \(1) | ++---------------+-------+-------------+-------------+---------------+-------+ +| hash64 | Unary | Any | UInt64 | | \(1) | ++---------------+-------+-------------+-------------+---------------+-------+ + +* \(1) The implementation doesn't guarantee hash stability across different versions of + the library. Union-, view- and run end encoded types are not supported yet. Review Comment: We don't really need the dash I guess? ########## cpp/src/arrow/compute/key_hash_benchmark.cc: ########## @@ -0,0 +1,125 @@ +// 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 <algorithm> +#include <cstdint> +#include <limits> +#include <random> +#include <string> +#include <vector> + +#include "benchmark/benchmark.h" + +#include "arrow/testing/gtest_util.h" +#include "arrow/testing/random.h" +#include "arrow/util/hashing.h" + +#include "arrow/array/builder_primitive.h" +#include "arrow/compute/key_hash_internal.h" +#include "arrow/compute/util_internal.h" + +namespace arrow { +namespace internal { + +namespace { +// copied from scalar_string_benchmark +constexpr auto kSeed = 0x94378165; + +static random::RandomArrayGenerator hashing_rng(kSeed); +} // namespace + +static void KeyHashIntegers32(benchmark::State& state) { // NOLINT non-const reference + auto test_vals = hashing_rng.Int32(10000, 0, std::numeric_limits<int32_t>::max()); + + // initialize the stack allocator + util::TempVectorStack stack_memallocator; + ASSERT_OK( + stack_memallocator.Init(compute::default_exec_context()->memory_pool(), + 3 * sizeof(int32_t) * util::MiniBatch::kMiniBatchLength)); + + // prepare the execution context for Hashing32 + compute::LightContext hash_ctx; + hash_ctx.hardware_flags = compute::default_exec_context()->cpu_info()->hardware_flags(); + hash_ctx.stack = &stack_memallocator; + + // allocate memory for results + ASSERT_OK_AND_ASSIGN(std::unique_ptr<Buffer> hash_buffer, + AllocateBuffer(test_vals->length() * sizeof(int32_t))); + + // run the benchmark + while (state.KeepRunning()) { + // Prepare input data structure for propagation to hash function + ASSERT_OK_AND_ASSIGN( + compute::KeyColumnArray input_keycol, + compute::ColumnArrayFromArrayData(test_vals->data(), 0, test_vals->length())); + + compute::Hashing32::HashMultiColumn( + {input_keycol}, &hash_ctx, + reinterpret_cast<uint32_t*>(hash_buffer->mutable_data())); + + // benchmark::DoNotOptimize(hash_buffer); + } + + state.SetBytesProcessed(state.iterations() * test_vals->length() * sizeof(int32_t)); + state.SetItemsProcessed(state.iterations() * test_vals->length()); +} + +static void KeyHashIntegers64(benchmark::State& state) { // NOLINT non-const reference + auto test_vals = hashing_rng.Int64(10000, 0, std::numeric_limits<int64_t>::max()); + + // initialize the stack allocator + util::TempVectorStack stack_memallocator; + ASSERT_OK( + stack_memallocator.Init(compute::default_exec_context()->memory_pool(), + 3 * sizeof(int32_t) * util::MiniBatch::kMiniBatchLength)); + + // prepare the execution context for Hashing32 + compute::LightContext hash_ctx; + hash_ctx.hardware_flags = compute::default_exec_context()->cpu_info()->hardware_flags(); + hash_ctx.stack = &stack_memallocator; + + // allocate memory for results + ASSERT_OK_AND_ASSIGN(std::unique_ptr<Buffer> hash_buffer, + AllocateBuffer(test_vals->length() * sizeof(int64_t))); + + // run the benchmark + while (state.KeepRunning()) { + // Prepare input data structure for propagation to hash function + ASSERT_OK_AND_ASSIGN( + compute::KeyColumnArray input_keycol, + compute::ColumnArrayFromArrayData(test_vals->data(), 0, test_vals->length())); + + compute::Hashing64::HashMultiColumn( + {input_keycol}, &hash_ctx, + reinterpret_cast<uint64_t*>(hash_buffer->mutable_data())); + + // benchmark::DoNotOptimize(hash_buffer); Review Comment: ```suggestion ``` -- 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: github-unsubscr...@arrow.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org