bkietz commented on code in PR #37418: URL: https://github.com/apache/arrow/pull/37418#discussion_r1335994446
########## cpp/src/arrow/compute/kernels/vector_dictionary.cc: ########## @@ -0,0 +1,201 @@ +// 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/array/array_base.h" +#include "arrow/array/array_dict.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/array/dict_internal.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/result.h" + +namespace arrow { + +namespace compute { +namespace internal { + +namespace { + +// Dictionary compaction implementation + +const FunctionDoc dictionary_compact_doc{ + "Compact dictionary array", + ("Return a compacted version of the dictionary array input,\n" + "which removes unused values in dictionary.\n" + "The function assumes every indices has its corresponding value\n" + "in dictionary."), + {"dictionary_array"}}; + +class DictionaryCompactKernel : public KernelState { + public: + virtual Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const = 0; +}; Review Comment: Instead of wrapping the data in the user friendly (but heavier, performance-wise) `Array` and `DictionaryArray` classes, please use `ExecSpan` and `ArraySpan` directly. That will actually simplify this kernel state to ```suggestion class DictionaryCompactKernelState : public KernelState { public: ArrayKernelExec exec; }; ``` ... which can then be used below as ```c++ auto exec = checked_cast<const DictionaryCompactKernel*>(ctx->state())->exec; return exec(ctx, batch, out); ``` ... and will allow rewriting `DictionaryCompactKernelImpl<T>::Exec` as a single template function. ########## cpp/src/arrow/compute/kernels/vector_dictionary.cc: ########## @@ -0,0 +1,201 @@ +// 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/array/array_base.h" +#include "arrow/array/array_dict.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/array/dict_internal.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/result.h" + +namespace arrow { + +namespace compute { +namespace internal { + +namespace { + +// Dictionary compaction implementation + +const FunctionDoc dictionary_compact_doc{ + "Compact dictionary array", + ("Return a compacted version of the dictionary array input,\n" + "which removes unused values in dictionary.\n" + "The function assumes every indices has its corresponding value\n" Review Comment: ```suggestion "The function assumes every index corresponds to a value\n" ``` ########## cpp/src/arrow/compute/kernels/vector_dictionary.cc: ########## @@ -0,0 +1,201 @@ +// 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/array/array_base.h" +#include "arrow/array/array_dict.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/array/dict_internal.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/result.h" + +namespace arrow { + +namespace compute { +namespace internal { + +namespace { + +// Dictionary compaction implementation + +const FunctionDoc dictionary_compact_doc{ + "Compact dictionary array", + ("Return a compacted version of the dictionary array input,\n" + "which removes unused values in dictionary.\n" + "The function assumes every indices has its corresponding value\n" + "in dictionary."), + {"dictionary_array"}}; + +class DictionaryCompactKernel : public KernelState { + public: + virtual Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const = 0; +}; + +template <typename IndiceArrowType> +class DictionaryCompactKernelImpl : public DictionaryCompactKernel { + using BuilderType = NumericBuilder<IndiceArrowType>; + using CType = typename IndiceArrowType::c_type; + + public: + Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const override { + const DictionaryArray& casted_dict_array = + checked_cast<const DictionaryArray&>(*dict_array); + const std::shared_ptr<Array>& dict = casted_dict_array.dictionary(); + if (dict->length() == 0) { + return dict_array; + } + const std::shared_ptr<Array>& indices = casted_dict_array.indices(); + if (indices->length() == 0) { + ARROW_ASSIGN_OR_RAISE(auto empty_dict, + MakeEmptyArray(dict->type(), ctx->memory_pool())); + return DictionaryArray::FromArrays(dict_array->type(), indices, empty_dict); + } + const CType* indices_data = indices->data()->GetValues<CType>(1); + + // check whether the input is compacted + std::vector<bool> dict_used(dict->length(), false); + int64_t dict_used_count = 0; + for (int64_t i = 0; i < indices->length(); i++) { + if (indices->IsNull(i)) { + continue; + } + + CType current_index = indices_data[i]; + if (!dict_used[current_index]) { + dict_used[current_index] = true; + dict_used_count++; + + if (dict_used_count == dict->length()) { // input is already compacted + return dict_array; + } + } + } + + // dictionary compaction + if (dict_used_count == 0) { + ARROW_ASSIGN_OR_RAISE(auto empty_dict, + MakeEmptyArray(dict->type(), ctx->memory_pool())); + return DictionaryArray::FromArrays(dict_array->type(), indices, empty_dict); + } + BuilderType dict_indices_builder(ctx->memory_pool()); + bool need_change_indice = false; + CType len = static_cast<CType>(dict->length()); + for (CType i = 0; i < len; i++) { + if (dict_used[i]) { + ARROW_RETURN_NOT_OK(dict_indices_builder.Append(i)); + } else if (i + 1 < len && dict_used[i + 1]) { + need_change_indice = true; + } + } + ARROW_ASSIGN_OR_RAISE(std::shared_ptr<arrow::Array> compacted_dict_indices, + dict_indices_builder.Finish()); + ARROW_ASSIGN_OR_RAISE( + auto compacted_dict_res, + Take(dict, compacted_dict_indices, TakeOptions::NoBoundsCheck(), ctx)); + std::shared_ptr<arrow::Array> compacted_dict = compacted_dict_res.make_array(); + + // indices changes + if (!need_change_indice) { + return DictionaryArray::FromArrays(dict_array->type(), indices, compacted_dict); + } + std::vector<CType> indice_minus_number(dict->length(), 0); + if (!dict_used[0]) { + indice_minus_number[0] = 1; + } + for (int64_t i = 1; i < dict->length(); i++) { + indice_minus_number[i] = indice_minus_number[i - 1]; + if (!dict_used[i]) { + indice_minus_number[i] = indice_minus_number[i] + 1; + } + } + + BuilderType indices_builder(ctx->memory_pool()); + for (int64_t i = 0; i < indices->length(); i++) { + if (indices->IsNull(i)) { + ARROW_RETURN_NOT_OK(indices_builder.AppendNull()); + } else { + CType current_index = indices_data[i]; + ARROW_RETURN_NOT_OK( + indices_builder.Append(current_index - indice_minus_number[current_index])); + } + } + ARROW_ASSIGN_OR_RAISE(std::shared_ptr<arrow::Array> changed_indice, + indices_builder.Finish()); + + return DictionaryArray::FromArrays(dict_array->type(), changed_indice, + compacted_dict); + } +}; + +Result<std::unique_ptr<KernelState>> DictionaryCompactInit(KernelContext* ctx, + const KernelInitArgs& args) { + const auto& dict_type = + checked_cast<const DictionaryType&>(*(args.inputs[0].owned_type)); + switch (dict_type.index_type()->id()) { + case Type::UINT8: + return std::make_unique<DictionaryCompactKernelImpl<UInt8Type>>(); + case Type::INT8: + return std::make_unique<DictionaryCompactKernelImpl<Int8Type>>(); + case Type::UINT16: + return std::make_unique<DictionaryCompactKernelImpl<UInt16Type>>(); + case Type::INT16: + return std::make_unique<DictionaryCompactKernelImpl<Int16Type>>(); + case Type::UINT32: + return std::make_unique<DictionaryCompactKernelImpl<UInt32Type>>(); + case Type::INT32: + return std::make_unique<DictionaryCompactKernelImpl<Int32Type>>(); + case Type::UINT64: + return std::make_unique<DictionaryCompactKernelImpl<UInt64Type>>(); + case Type::INT64: + return std::make_unique<DictionaryCompactKernelImpl<Int64Type>>(); + default: + ARROW_CHECK(false) << "unreachable"; + return Status::TypeError("Expected an Indice Type of Int or UInt"); + } +} + +Status DictionaryCompactExec(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) { + if (batch[0].is_scalar()) { + return Status::TypeError("Expected an Array or a Chunked Array"); Review Comment: ```suggestion return Status::NotImplemented("DictionaryCompacting Scalars"); ``` Note: this kernel exec function never receives chunked arrays; dispatching the kernel's exec function to each chunk is handled in CallFunction ########## cpp/src/arrow/compute/kernels/vector_dictionary.cc: ########## @@ -0,0 +1,201 @@ +// 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/array/array_base.h" +#include "arrow/array/array_dict.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/array/dict_internal.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/result.h" + +namespace arrow { + +namespace compute { +namespace internal { + +namespace { + +// Dictionary compaction implementation + +const FunctionDoc dictionary_compact_doc{ + "Compact dictionary array", + ("Return a compacted version of the dictionary array input,\n" + "which removes unused values in dictionary.\n" + "The function assumes every indices has its corresponding value\n" + "in dictionary."), + {"dictionary_array"}}; + +class DictionaryCompactKernel : public KernelState { + public: + virtual Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const = 0; +}; + +template <typename IndiceArrowType> +class DictionaryCompactKernelImpl : public DictionaryCompactKernel { + using BuilderType = NumericBuilder<IndiceArrowType>; + using CType = typename IndiceArrowType::c_type; + + public: + Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const override { + const DictionaryArray& casted_dict_array = + checked_cast<const DictionaryArray&>(*dict_array); + const std::shared_ptr<Array>& dict = casted_dict_array.dictionary(); + if (dict->length() == 0) { + return dict_array; + } + const std::shared_ptr<Array>& indices = casted_dict_array.indices(); + if (indices->length() == 0) { + ARROW_ASSIGN_OR_RAISE(auto empty_dict, + MakeEmptyArray(dict->type(), ctx->memory_pool())); + return DictionaryArray::FromArrays(dict_array->type(), indices, empty_dict); + } + const CType* indices_data = indices->data()->GetValues<CType>(1); + + // check whether the input is compacted + std::vector<bool> dict_used(dict->length(), false); + int64_t dict_used_count = 0; + for (int64_t i = 0; i < indices->length(); i++) { + if (indices->IsNull(i)) { + continue; Review Comment: Instead of manually iterating through the array, it's more efficient to use the helpers in `visit_data_inline.h`. For example, you can use `VisitArraySpanInline` as in https://github.com/apache/arrow/blob/87f475a69b212041f124b50b06f3d92404e3492d/cpp/src/arrow/compute/kernels/scalar_temporal_unary.cc#L1307-L1321 ########## cpp/src/arrow/compute/kernels/vector_dictionary.cc: ########## @@ -0,0 +1,201 @@ +// 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/array/array_base.h" +#include "arrow/array/array_dict.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/array/dict_internal.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/result.h" + +namespace arrow { + +namespace compute { +namespace internal { + +namespace { + +// Dictionary compaction implementation + +const FunctionDoc dictionary_compact_doc{ + "Compact dictionary array", + ("Return a compacted version of the dictionary array input,\n" + "which removes unused values in dictionary.\n" + "The function assumes every indices has its corresponding value\n" + "in dictionary."), + {"dictionary_array"}}; + +class DictionaryCompactKernel : public KernelState { + public: + virtual Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const = 0; +}; + +template <typename IndiceArrowType> +class DictionaryCompactKernelImpl : public DictionaryCompactKernel { + using BuilderType = NumericBuilder<IndiceArrowType>; + using CType = typename IndiceArrowType::c_type; + + public: + Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const override { + const DictionaryArray& casted_dict_array = + checked_cast<const DictionaryArray&>(*dict_array); + const std::shared_ptr<Array>& dict = casted_dict_array.dictionary(); + if (dict->length() == 0) { + return dict_array; + } + const std::shared_ptr<Array>& indices = casted_dict_array.indices(); + if (indices->length() == 0) { + ARROW_ASSIGN_OR_RAISE(auto empty_dict, + MakeEmptyArray(dict->type(), ctx->memory_pool())); + return DictionaryArray::FromArrays(dict_array->type(), indices, empty_dict); + } + const CType* indices_data = indices->data()->GetValues<CType>(1); + + // check whether the input is compacted + std::vector<bool> dict_used(dict->length(), false); + int64_t dict_used_count = 0; + for (int64_t i = 0; i < indices->length(); i++) { + if (indices->IsNull(i)) { + continue; + } + + CType current_index = indices_data[i]; + if (!dict_used[current_index]) { + dict_used[current_index] = true; + dict_used_count++; + + if (dict_used_count == dict->length()) { // input is already compacted + return dict_array; + } + } + } + + // dictionary compaction + if (dict_used_count == 0) { + ARROW_ASSIGN_OR_RAISE(auto empty_dict, + MakeEmptyArray(dict->type(), ctx->memory_pool())); + return DictionaryArray::FromArrays(dict_array->type(), indices, empty_dict); + } + BuilderType dict_indices_builder(ctx->memory_pool()); + bool need_change_indice = false; + CType len = static_cast<CType>(dict->length()); + for (CType i = 0; i < len; i++) { + if (dict_used[i]) { + ARROW_RETURN_NOT_OK(dict_indices_builder.Append(i)); + } else if (i + 1 < len && dict_used[i + 1]) { + need_change_indice = true; + } + } + ARROW_ASSIGN_OR_RAISE(std::shared_ptr<arrow::Array> compacted_dict_indices, + dict_indices_builder.Finish()); + ARROW_ASSIGN_OR_RAISE( + auto compacted_dict_res, + Take(dict, compacted_dict_indices, TakeOptions::NoBoundsCheck(), ctx)); + std::shared_ptr<arrow::Array> compacted_dict = compacted_dict_res.make_array(); + + // indices changes + if (!need_change_indice) { + return DictionaryArray::FromArrays(dict_array->type(), indices, compacted_dict); + } + std::vector<CType> indice_minus_number(dict->length(), 0); Review Comment: I think you can accomplish this more simply with another call to `Take`: just build an array mapping `compacted_dict_indices[i] -> i` ########## cpp/src/arrow/compute/kernels/vector_dictionary.cc: ########## @@ -0,0 +1,201 @@ +// 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/array/array_base.h" +#include "arrow/array/array_dict.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/array/dict_internal.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/result.h" + +namespace arrow { + +namespace compute { +namespace internal { + +namespace { + +// Dictionary compaction implementation + +const FunctionDoc dictionary_compact_doc{ + "Compact dictionary array", + ("Return a compacted version of the dictionary array input,\n" + "which removes unused values in dictionary.\n" + "The function assumes every indices has its corresponding value\n" + "in dictionary."), + {"dictionary_array"}}; + +class DictionaryCompactKernel : public KernelState { + public: + virtual Result<std::shared_ptr<Array>> Exec(std::shared_ptr<Array> dict_array, + ExecContext* ctx) const = 0; +}; + +template <typename IndiceArrowType> Review Comment: Nit: "indices" is the plural, but the singular is "index" and not "indice" ```suggestion template <typename IndexArrowType> ``` ########## cpp/src/arrow/compute/kernels/vector_dictionary.cc: ########## @@ -0,0 +1,201 @@ +// 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/array/array_base.h" +#include "arrow/array/array_dict.h" +#include "arrow/array/builder_primitive.h" +#include "arrow/array/dict_internal.h" +#include "arrow/compute/api_vector.h" +#include "arrow/compute/kernels/common_internal.h" +#include "arrow/result.h" + +namespace arrow { + +namespace compute { +namespace internal { + +namespace { + +// Dictionary compaction implementation + +const FunctionDoc dictionary_compact_doc{ + "Compact dictionary array", + ("Return a compacted version of the dictionary array input,\n" + "which removes unused values in dictionary.\n" + "The function assumes every indices has its corresponding value\n" Review Comment: FWIW, I don't think it would be a significant performance cost to check that the maximum index is not out of bounds. This would also be much safer than exposing the user to risk of segfault if they have a dictionary array which doesn't satisfy this assumption. -- 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]
