Repository navigation
Conversation
…ounting
### Rationale for this change
Counting how many of a run of int16_t levels match a predicate (e.g. how
many definition levels equal the max definition level, or how many
repetition levels are 0) is a hot loop in the Parquet reader and writer.
It is currently open-coded as a scalar loop or a std::count() call.
`std::count` accumulates into a 64-bit integer, which forces the compiler
to widen every 16-bit compare result before accumulating and prevents
efficient vectorization. Accumulating into a `uint16_t` instead lets the
compiler keep the whole reduction in 16-bit lanes (e.g. `cmeq.8h` +
`sub.8h` + `addv.8h` on Neon, 32 levels per iteration), and the chunked
loop keeps that accumulator from overflowing: at most `0xFFFF` levels are
counted before the accumulator is folded into the 64-bit total.
The chunk bookkeeping (clamping the chunk length, folding the partial
count, advancing the pointer) is a fixed cost per call, and for inputs
shorter than one vector iteration it dominates: counting 7 levels that
way is measurably slower than `std::count`, even though both end up
running the same scalar loop. Such short inputs are therefore counted
directly, without going through the chunk loop.
On an Apple M-series machine, counting 2048 int16 levels where every
tenth is missing drops from ~232 ns to ~32 ns (about 7x), while short
inputs are at least as fast as `std::count`.
### What changes are included in this PR?
- Add `parquet::internal::CountIf16` next to the other level scanning
primitives in `parquet/level_comparison.h`. It is a header-only inline
template, since the level conversion translation unit is compiled twice
(standard and BMI2).
- Add unit tests covering empty input, a mixed predicate, short inputs
around the vectorization threshold, and the `0xFFFF` chunk boundaries.
- Add `BM_CountPresentLevels{StdCount,CountIf16}` to the level conversion
benchmark to track the improvement.
### Are these changes tested?
New `CountIf16.*` tests in `level_conversion_test.cc`, run as part of
`parquet-reader-test`.
### Are there any user-facing changes?
No.
|
|
|
It looks like an interesting change. It might be worth submitting to LLVM to optimize the implementation of |
|
There're existing discussion about this, see: llvm/llvm-project#204897 But anyway if you want to benefit from this, you need at least |
| // unrolled ladder of 8/16/24-wide compares instead of scalar code. | ||
| constexpr int64_t kSmallLevels = 32; | ||
| constexpr int64_t kMaxCount = std::numeric_limits<uint16_t>::max(); | ||
| if (num_levels < kSmallLevels) { |
There was a problem hiding this comment.
Does it make sense to keep this if branch, rather than letting LLVM automatically generate optimized code for short loops?
There was a problem hiding this comment.
I don't know, it would making the very short loops (9-31 elements?) a bit slower ( like 1.5ns -> 3ns ) on my Mac M4 Pro. If this doesn't matter just counting by chunk is ok.
…ader and writer ### Rationale for this change Follow-up to the `CountIf16` helper: use it for the level counting loops in the Parquet column reader/writer and in the file scanner, replacing open-coded scalar loops and `std::count` calls. Converted sites: - `TypedColumnReaderImpl::ReadLevelsInCurrentPage`: count non-null values. - `TypedRecordReader::SkipRecordsInBufferNonRepeated`: count values to skip. - `TypedRecordReader::DelimitRecords`: count records (rep level == 0) and values seen (def level == max). - `TypedRecordReader::ReadDenseForOptionalInBuffer`: count values to read. - `TypedColumnWriterImpl::WriteLevels`: count values to write (both overloads) and records written (rep level == 0). - `TypedColumnWriterImpl::MaybeCalculateValidityBits`: count values to write and spaced values to write. - `ScanFileContents`: count rows (rep level == 0). Sites are left as is where counting is not the bottleneck: the per-element bitmap loops in `DefRepLevelsToListInfo` also build validity bitmaps and write list offsets for every level, `page_index.cc` counts pages rather than levels, and the non-nullable validation loop in `WriteArrow` needs to `break` early on the first mismatch. `UpdateLevelHistogram`'s `max_level == 1` fast path is also left as is: its levels are known to be 0 or 1, so it sums them with `std::accumulate` in the `int16_t` space, which is a single 16-bit add per vector, while counting the 1s costs a compare and a subtract. ### What changes are included in this PR? Use `CountIf16` for the level counting call sites above. ### Are these changes tested? Covered by the existing Parquet reader, writer and Arrow reader/writer tests. ### Are there any user-facing changes? No.
e1291b9 to
7ce5324
Compare
|
Does this even make a difference in a benchmark? There are so many expensive things happening when reading or writing Parquet (such as compression or encoding) that I doubt the cost of |
|
I'm a bit busy this two days, I'll solve the comments this Sunday, sorry for delaying =_= |
| } | ||
| *out_values_to_write += | ||
| internal::CountLevels(def_levels, batch_size, level_info_.def_level); | ||
| *out_spaced_values_to_write += internal::CountLevelsGreaterEqual( |
There was a problem hiding this comment.
This function is used only once, I don't know whether I should extract it or not ( DType was dispatch multiple times, so I think it's ok to extract it)
| /// It is kept out of line so that the common path (a single Parquet page chunk, | ||
| /// always short enough for one accumulator) is a plain loop without any chunk | ||
| /// bookkeeping in front of it. |
There was a problem hiding this comment.
This is measured to make a difference. Generally see https://llvm.org/docs/Passes.html#licm-loop-invariant-code-motion
A code sample is here: https://godbolt.org/z/56oWjTGWW
LLVM will hoist some checking to outside, and it will trying to broadcast the level, and trying to simd comparing, which is useful for large loop but in-efficient for short loop.
I think keeping or reming it is both ok for me, if we think just making short inputs a bit slower is ok, we can just keep a while (num_levels > 0) loop.
| } | ||
|
|
||
| /// \brief Count the levels equal to `value`. | ||
| inline int64_t CountLevels(const int16_t* levels, int64_t num_levels, int16_t value) { |
There was a problem hiding this comment.
Here I found CountLevelsIf will be compiled into DType multiple times, which making output binary 0.5% more larger whichout linker's help. So I extract a short CountLevels here to help compiler able to not copy and paste this function everywhere 😅
|
Some file are already inside namespace parquet::internal; Copilot Lite mode just missed the surrounding file context. I think it's f**king mad 😅 |
There was a problem hiding this comment.
🟢 Approval recommended
The review identifies no active issues with the Parquet level-counting optimization.
No open issues 🎉
16 resolved since last review
The file mixesinternal::CountLevels(...)(line 1551) with unqualifiedCountLevels(...)calls… The file mixesinternal::CountLevels(...)(line 1551) with unqualifiedCountLevels(...)calls… The file mixesinternal::CountLevels(...)(line 1551) with unqualifiedCountLevels(...)calls… The file mixesinternal::CountLevels(...)(line 1551) with unqualifiedCountLevels(...)calls… The file mixesinternal::CountLevels(...)(line 1551) with unqualifiedCountLevels(...)calls… These calls useCountLevelswithout theinternal::qualifier, while earlier changes in the same… These calls useCountLevelswithout theinternal::qualifier, while earlier changes in the same… These calls useCountLevelswithout theinternal::qualifier, while earlier changes in the same… The PR description mentions that non-template wrappers allow ODR deduplication of the out-of-line… The PR description mentions that non-template wrappers allow ODR deduplication of the out-of-line… These calls use unqualifiedCountLevels, but other call sites in the same file use… These calls use unqualifiedCountLevels, but other call sites in the same file use…CountLevelsis called unqualified here, while other changes in this file use…CountLevelsIfChunkedis a templated function defined in a header; even withARROW_NOINLINE, it… The PR description mentions introducing anum_levels < 32fast-path because small inputs may not… Same as above: this unqualifiedCountLevelscall is inconsistent with other call sites using…
Review effort: Balanced
| EXPECT_EQ(CountLevelsIf(levels.data(), /*num_levels=*/6, [](int16_t) { return false; }), | ||
| 0); | ||
|
|
||
| // Cross-check various prefix lengths across vector and scalar tail boundaries. |
There was a problem hiding this comment.
What's the point of this test? Do you not trust the compiler?
There was a problem hiding this comment.
My bad, this is not long enough =_=



Rationale for this change
std::countoverint16_tlevels widens every comparison result to a 64-bit accumulator, preventing efficient 16-bit lane vectorization. Accumulating inuint16_tchunks keeps the reduction in 16-bit lanes without overflowing:-O2x86 AVX2 & ARM NEON): https://godbolt.org/z/rvobWjrfaBefore x86:
After x86:
Before ARM:
After ARM:
Some notes:
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+vzeroupperon x86 AVX2 /dup.8hon NEON) on short inputs.inlinewrappers (CountLevelsandCountLevelsGreaterEqual) are provided on top ofCountLevelsIfto keep call sites concise and ensure a single shared closure type per wrapper across translation units (so the linker ODR-deduplicatesCountLevelsIfChunkedto one copy per wrapper across physical-type template instantiations and TUs).What changes are included in this PR?
CountLevels,CountLevelsGreaterEqual,CountLevelsIf, and out-of-line fallbackCountLevelsIfChunkedincpp/src/parquet/level_comparison_internal.h.CountLevels/CountLevelsGreaterEqualincpp/src/parquet/column_reader.cc,cpp/src/parquet/column_writer.cc, andcpp/src/parquet/file_reader.cc.cpp/src/parquet/level_conversion_test.cccovering predicates, tail lengths, anduint16_t::max()chunk boundaries.Are these changes tested?
Yes, unit tests in
cpp/src/parquet/level_conversion_test.ccand 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:
Reviewed before submission by: