This is an automated email from the ASF dual-hosted git repository.
pitrou pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow.git
The following commit(s) were added to refs/heads/main by this push:
new cb43482917f GH-55399: [C++][Parquet] Minor optimize level counting
with CountLevels (#55408)
cb43482917f is described below
commit cb43482917f23ccaaa932216336fc901e2d918dd
Author: mwish <[email protected]>
AuthorDate: Tue Nov 24 00:34:02 2026 +0800
GH-55399: [C++][Parquet] Minor optimize level counting with CountLevels
(#55408)
### Rationale for this change
`std::count` over `int16_t` levels widens every comparison result to a
64-bit accumulator, preventing efficient 16-bit lane vectorization.
Accumulating in `uint16_t` chunks keeps the reduction in 16-bit lanes without
overflowing:
1. x86: https://godbolt.org/z/Gqc7fxe55
2. ARM: https://godbolt.org/z/sGhG8crYa
3. Fast-path vs out-of-line chunked fallback (`-O2` x86 AVX2 & ARM NEON):
https://godbolt.org/z/rvobWjrfa
Before x86:
```
vmovq (%rdi,%rax,2), %xmm6 # Load 8 bytes = 4 levels
vpcmpeqw %xmm1, %xmm6, %xmm6
vpmovzxwq %xmm6, %ymm6 # 8×16 bits -> 4×64 bits, only 4 lanes
vpand %ymm2, %ymm6, %ymm6 # & 1
vpaddq %ymm6, %ymm0, %ymm0 # 64-bit adds
```
After x86:
```
vpcmpeqw (%rdi,%r8,2), %ymm1, %ymm5 # compare 16 levels
vpsubw %ymm5, %ymm0, %ymm0 # add 16 lanes
```
Before ARM:
```
ldp q18,q19,[x8,#-16] ; 2 cmeq 16 bits mask
cmeq v18.8h, v18.8h, v16.8h
cmeq v19.8h, v19.8h, v16.8h
ushll2 v20.4s, v18.8h, #0 ; 16->32 bits
ushll v18.4s, v18.4h, #0
...
and v22.16b, v22.16b, v17.16b
add v4.2d, v4.2d, v20.2d
subs x14,x14,#16 ; b.ne
```
After ARM:
```
ldp q3,q4,[x9,#-16]
cmeq v3.8h, v3.8h, v2.8h
cmeq v4.8h, v4.8h, v2.8h
sub v0.8h, v0.8h, v3.8h
sub v1.8h, v1.8h, v4.8h
subs/add/b.ne
```
Some notes:
1. Inputs larger than `uint16_t::max()` (`65535`) use an out-of-line
chunked fallback (`CountLevelsIfChunked`), so the common single-page path
avoids outer-loop LICM hoisting of vector broadcasts (`vpbroadcastw` +
`vzeroupper` on x86 AVX2 / `dup.8h` on NEON) on short inputs.
2. Non-template `inline` wrappers (`CountLevels` and
`CountLevelsGreaterEqual`) are provided on top of `CountLevelsIf` to keep call
sites concise and ensure a single shared closure type per wrapper across
translation units (so the linker ODR-deduplicates `CountLevelsIfChunked` to one
copy per wrapper across physical-type template instantiations and TUs).
3. Optimizes both read and write paths (though level counting is only a
small part of end-to-end Parquet I/O).
### What changes are included in this PR?
- Add internal helpers `CountLevels`, `CountLevelsGreaterEqual`,
`CountLevelsIf`, and out-of-line fallback `CountLevelsIfChunked` in
`cpp/src/parquet/level_comparison_internal.h`.
- Use `CountLevels` / `CountLevelsGreaterEqual` in
`cpp/src/parquet/column_reader.cc`, `cpp/src/parquet/column_writer.cc`, and
`cpp/src/parquet/file_reader.cc`.
- Add unit tests in `cpp/src/parquet/level_conversion_test.cc` covering
predicates, tail lengths, and `uint16_t::max()` chunk boundaries.
### Are these changes tested?
Yes, unit tests in `cpp/src/parquet/level_conversion_test.cc` and covered
by existing Parquet reader/writer tests.
### Are there any user-facing changes?
No
### Was AI used for this PR?
**PR code and description written by:**
- [x] Human
- [x] AI
**Reviewed before submission by:**
- [x] Human
* GitHub Issue: #55399
Authored-by: mwish <[email protected]>
Signed-off-by: Antoine Pitrou <[email protected]>
---
cpp/src/parquet/column_reader.cc | 20 +++++------
cpp/src/parquet/column_writer.cc | 35 +++++++------------
cpp/src/parquet/file_reader.cc | 7 ++--
cpp/src/parquet/level_comparison_internal.h | 53 +++++++++++++++++++++++++++++
cpp/src/parquet/level_conversion_test.cc | 29 ++++++++++++++++
5 files changed, 107 insertions(+), 37 deletions(-)
diff --git a/cpp/src/parquet/column_reader.cc b/cpp/src/parquet/column_reader.cc
index 8594acb41d6..ce1a918e13e 100644
--- a/cpp/src/parquet/column_reader.cc
+++ b/cpp/src/parquet/column_reader.cc
@@ -47,6 +47,7 @@
#include "parquet/encryption/encryption_internal.h"
#include "parquet/encryption/internal_file_decryptor.h"
#include "parquet/exception.h"
+#include "parquet/level_comparison_internal.h"
#include "parquet/level_conversion.h"
#include "parquet/level_decoder_internal.h"
#include "parquet/properties.h"
@@ -1566,7 +1567,7 @@ class TypedColumnReaderImpl
// cache-efficiency if fused with the level decoding.
ARROW_DCHECK_LE(*num_def_levels, std::numeric_limits<int32_t>::max());
*non_null_values_to_read += static_cast<int32_t>(
- std::count(def_levels, def_levels + *num_def_levels,
this->max_def_level()));
+ internal::CountLevels(def_levels, *num_def_levels,
this->max_def_level()));
} else {
// Required field, read all values
if (num_def_levels != nullptr) {
@@ -1981,8 +1982,8 @@ int64_t TypedRecordReader<DT,
VS>::SkipRecordsInBufferNonRepeated(int64_t num_re
// we do not have a buffer, so we need to read them and throw them away.
// First we need to figure out how many present/not-null values there are.
const auto values_to_read = static_cast<int32_t>(
- std::count(def_levels() + levels_position_, def_levels() +
remaining_levels_pos,
- this->max_def_level()));
+ CountLevels(def_levels() + levels_position_,
+ remaining_levels_pos - levels_position_,
this->max_def_level()));
// Now that we have figured out number of values to read, we do not need
// these levels anymore. We will remove these values from the buffer.
@@ -2147,9 +2148,7 @@ int64_t TypedRecordReader<DT, VS>::DelimitRecords(int64_t
num_records,
const int64_t stride =
std::min(levels_written() - levels_position_, num_records -
records_read);
const int64_t position_end = levels_position_ + stride;
- for (int64_t i = levels_position_; i < position_end; ++i) {
- records_read += rep_levels[i] == 0;
- }
+ records_read += CountLevels(rep_levels + levels_position_, stride, 0);
levels_position_ = position_end;
if (records_read == num_records) {
// Check last rep_level reaches the boundary and
@@ -2163,8 +2162,8 @@ int64_t TypedRecordReader<DT, VS>::DelimitRecords(int64_t
num_records,
}
}
// Scan definition levels to find number of physical values
- *values_seen = std::count(def_levels + level, def_levels + levels_position_,
- this->max_def_level());
+ *values_seen =
+ CountLevels(def_levels + level, levels_position_ - level,
this->max_def_level());
return records_read;
}
@@ -2253,8 +2252,9 @@ void TypedRecordReader<DT,
VS>::ReadDenseForOptionalInBuffer(
// When reading dense we need to figure out number of values to read.
const int16_t* def_levels = this->def_levels();
- *values_to_read += std::count(def_levels + start_levels_position,
- def_levels + levels_position_,
this->max_def_level());
+ *values_to_read +=
+ CountLevels(def_levels + start_levels_position,
+ levels_position_ - start_levels_position,
this->max_def_level());
// This is only reading in the current page so this fits in an int32.
value_sink_.ReadValuesDense(*this->current_decoder_.get(),
clamp_to<int32_t>(*values_to_read));
diff --git a/cpp/src/parquet/column_writer.cc b/cpp/src/parquet/column_writer.cc
index fbd34677b03..e08009dd5c1 100644
--- a/cpp/src/parquet/column_writer.cc
+++ b/cpp/src/parquet/column_writer.cc
@@ -55,6 +55,7 @@
#include "parquet/encoding.h"
#include "parquet/encryption/encryption_internal.h"
#include "parquet/encryption/internal_file_encryptor.h"
+#include "parquet/level_comparison_internal.h"
#include "parquet/level_conversion.h"
#include "parquet/metadata.h"
#include "parquet/page_index.h"
@@ -1698,11 +1699,8 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
int64_t values_to_write = 0;
// If the field is required and non-repeated, there are no definition
levels
if (descr_->max_definition_level() > 0) {
- for (int64_t i = 0; i < num_levels; ++i) {
- if (def_levels[i] == descr_->max_definition_level()) {
- ++values_to_write;
- }
- }
+ values_to_write =
+ internal::CountLevels(def_levels, num_levels,
descr_->max_definition_level());
WriteDefinitionLevels(num_levels, def_levels);
} else {
@@ -1714,12 +1712,9 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
if (descr_->max_repetition_level() > 0) {
// A row could include more than one value
// Count the occasions where we start a new row
- for (int64_t i = 0; i < num_levels; ++i) {
- if (rep_levels[i] == 0) {
- rows_written_++;
- num_buffered_rows_++;
- }
- }
+ const int64_t records_written = internal::CountLevels(rep_levels,
num_levels, 0);
+ rows_written_ += records_written;
+ num_buffered_rows_ += records_written;
WriteRepetitionLevels(num_levels, rep_levels);
} else {
@@ -1749,11 +1744,10 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
*out_spaced_values_to_write = batch_size;
*null_count = 0;
} else {
- for (int x = 0; x < batch_size; x++) {
- *out_values_to_write += def_levels[x] == level_info_.def_level ? 1 :
0;
- *out_spaced_values_to_write +=
- def_levels[x] >= level_info_.repeated_ancestor_def_level ? 1 : 0;
- }
+ *out_values_to_write +=
+ internal::CountLevels(def_levels, batch_size,
level_info_.def_level);
+ *out_spaced_values_to_write += internal::CountLevelsGreaterEqual(
+ def_levels, batch_size, level_info_.repeated_ancestor_def_level);
*null_count = batch_size - *out_values_to_write;
}
return;
@@ -1809,12 +1803,9 @@ class TypedColumnWriterImpl : public ColumnWriterImpl,
if (descr_->max_repetition_level() > 0) {
// A row could include more than one value
// Count the occasions where we start a new row
- for (int64_t i = 0; i < num_levels; ++i) {
- if (rep_levels[i] == 0) {
- rows_written_++;
- num_buffered_rows_++;
- }
- }
+ const int64_t records_written = internal::CountLevels(rep_levels,
num_levels, 0);
+ rows_written_ += records_written;
+ num_buffered_rows_ += records_written;
WriteRepetitionLevels(num_levels, rep_levels);
} else {
// Each value is exactly one row
diff --git a/cpp/src/parquet/file_reader.cc b/cpp/src/parquet/file_reader.cc
index fb9b389cb15..0ddbfb48114 100644
--- a/cpp/src/parquet/file_reader.cc
+++ b/cpp/src/parquet/file_reader.cc
@@ -44,6 +44,7 @@
#include "parquet/encryption/internal_file_decryptor.h"
#include "parquet/exception.h"
#include "parquet/file_writer.h"
+#include "parquet/level_comparison_internal.h"
#include "parquet/metadata.h"
#include "parquet/page_index.h"
#include "parquet/platform.h"
@@ -980,11 +981,7 @@ int64_t ScanFileContents(std::vector<int> columns, const
int32_t column_batch_si
ScanAllValues(column_batch_size, def_levels.data(),
rep_levels.data(),
values.data(), &values_read, col_reader.get());
if (col_reader->descr()->max_repetition_level() > 0) {
- for (size_t i = 0; i < static_cast<size_t>(levels_read); i++) {
- if (rep_levels[i] == 0) {
- total_rows[col]++;
- }
- }
+ total_rows[col] += internal::CountLevels(rep_levels.data(),
levels_read, 0);
} else {
total_rows[col] += levels_read;
}
diff --git a/cpp/src/parquet/level_comparison_internal.h
b/cpp/src/parquet/level_comparison_internal.h
index 966b21fad37..8b3235ae2bf 100644
--- a/cpp/src/parquet/level_comparison_internal.h
+++ b/cpp/src/parquet/level_comparison_internal.h
@@ -18,6 +18,8 @@
#include <algorithm>
#include <cstdint>
+#include <limits>
+#include <utility>
#include "parquet/platform.h"
@@ -35,4 +37,55 @@ struct MinMax {
MinMax PARQUET_EXPORT FindMinMax(const int16_t* levels, int64_t num_levels);
+// Fallback for num_levels > uint16_t::max(), counting in chunks to avoid
overflow.
+template <typename Predicate>
+ARROW_NOINLINE int64_t CountLevelsIfChunked(const int16_t* levels, int64_t
num_levels,
+ Predicate&& pred) {
+ constexpr int64_t kMaxChunkSize = std::numeric_limits<uint16_t>::max();
+ int64_t total = 0;
+ while (num_levels > 0) {
+ const int64_t chunk_size = std::min(num_levels, kMaxChunkSize);
+ uint16_t chunk_count = 0;
+ for (int64_t i = 0; i < chunk_size; ++i) {
+ chunk_count += pred(levels[i]) ? 1 : 0;
+ }
+ total += chunk_count;
+ levels += chunk_size;
+ num_levels -= chunk_size;
+ }
+ return total;
+}
+
+/// \brief Count the levels that satisfy `pred`.
+///
+/// Accumulates matches in a `uint16_t` so the compiler can vectorize the loop
+/// using 16-bit lanes without widening each comparison result to 64 bits.
+/// Inputs longer than `uint16_t::max()` are counted in chunks to avoid
overflow.
+template <typename Predicate>
+inline int64_t CountLevelsIf(const int16_t* levels, int64_t num_levels,
+ Predicate&& pred) {
+ constexpr int64_t kMaxChunkSize = std::numeric_limits<uint16_t>::max();
+ if (num_levels > kMaxChunkSize) {
+ return CountLevelsIfChunked(levels, num_levels,
std::forward<Predicate>(pred));
+ }
+ uint16_t count = 0;
+ for (int64_t i = 0; i < num_levels; ++i) {
+ count += pred(levels[i]) ? 1 : 0;
+ }
+ return count;
+}
+
+/// \brief Count the levels equal to `value`.
+inline int64_t CountLevels(const int16_t* levels, int64_t num_levels, int16_t
value) {
+ return CountLevelsIf(levels, num_levels,
+ [value](int16_t level) { return level == value; });
+}
+
+/// \brief Count the levels greater than or equal to `min_level`.
+inline int64_t CountLevelsGreaterEqual(const int16_t* levels, int64_t
num_levels,
+ int16_t min_level) {
+ return CountLevelsIf(levels, num_levels,
+ [min_level](int16_t level) { return level >= min_level;
});
+}
+
} // namespace parquet::internal
diff --git a/cpp/src/parquet/level_conversion_test.cc
b/cpp/src/parquet/level_conversion_test.cc
index 15f5aab77ca..4dbf63e11f0 100644
--- a/cpp/src/parquet/level_conversion_test.cc
+++ b/cpp/src/parquet/level_conversion_test.cc
@@ -23,6 +23,7 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include <limits>
#include <string>
#include <vector>
@@ -113,6 +114,34 @@ TEST(GreaterThanBitmap, GeneratesExpectedBitmasks) {
}
#endif
+TEST(CountLevels, CountsMatchingLevels) {
+ const std::vector<int16_t> levels = {3, 1, 3, 0, 3, 2};
+ auto is_odd = [](int16_t level) { return level % 2 != 0; };
+
+ EXPECT_EQ(CountLevels(levels.data(), /*num_levels=*/0, 3), 0);
+ EXPECT_EQ(CountLevels(levels.data(), /*num_levels=*/6, 3), 3);
+ EXPECT_EQ(CountLevels(levels.data(), /*num_levels=*/6, 0), 1);
+ EXPECT_EQ(CountLevelsGreaterEqual(levels.data(), /*num_levels=*/6, 1), 5);
+ EXPECT_EQ(CountLevelsGreaterEqual(levels.data(), /*num_levels=*/6, 3), 3);
+ EXPECT_EQ(CountLevelsIf(levels.data(), /*num_levels=*/6, is_odd), 4);
+ EXPECT_EQ(CountLevelsIf(levels.data(), /*num_levels=*/6, [](int16_t) {
return false; }),
+ 0);
+}
+
+TEST(CountLevels, HandlesChunkBoundaries) {
+ // Verify 16-bit accumulator does not overflow and chunk boundaries are
exact.
+ constexpr int64_t kChunkSize = std::numeric_limits<uint16_t>::max();
+ std::vector<int16_t> levels(/*count=*/5 * kChunkSize, 1);
+ auto is_one = [](int16_t level) { return level == 1; };
+ const std::vector<int64_t> num_levels = {kChunkSize - 1, kChunkSize,
kChunkSize + 1,
+ 3 * kChunkSize, 5 * kChunkSize};
+ for (const int64_t n : num_levels) {
+ EXPECT_EQ(CountLevels(levels.data(), n, 1), n) << "num_levels: " << n;
+ EXPECT_EQ(CountLevelsGreaterEqual(levels.data(), n, 1), n) << "num_levels:
" << n;
+ EXPECT_EQ(CountLevelsIf(levels.data(), n, is_one), n) << "num_levels: " <<
n;
+ }
+}
+
TEST(DefLevelsToBitmap, WithRepetitionLevelFiltersOutEmptyListValues) {
std::vector<uint8_t> validity_bitmap(/*count*/ 8, 0);