mbutrovich commented on code in PR #12018:
URL: https://github.com/apache/arrow-rs/pull/12018#discussion_r4494561814
##########
parquet/benches/arrow_reader.rs:
##########
@@ -2733,6 +2859,22 @@ fn add_benches(c: &mut Criterion) {
}
group.finish();
+ let int32_list_list_desc = build_int32_list_list_desc();
+ let mut group =
c.benchmark_group("arrow_array_reader/ListArray/Int32ListList");
+ for (label, null_density) in [("no NULLs", 0.0), ("half NULLs", 0.5)] {
Review Comment:
Could we add a long-list case to the bench commit? Every list bench here
draws its lengths from below [`MAX_LIST_LEN =
10`](https://github.com/apache/arrow-rs/blob/dd111fee723c606dbbc8d7fb73de434fc6f7bb41/parquet/benches/arrow_reader.rs#L130)
(or `MAX_NESTED_LIST_LEN = 5` here), so `r < rep_level` is hard to predict in
all of them. That's exactly the case where removing the branch pays off, and
it's why the regression above didn't show. Branchless code losing in the
predictable case has happened here before: in #11656 the branchless view copy
was 12% slower on x86 for long strings
([discussion](https://github.com/apache/arrow-rs/pull/11656#discussion_r4303917768)).
This is the case I used, with every list holding the same number of non-null
items, which is the shape of embedding vectors stored as `list<float>`. Both
sizes read about 10M levels per iteration. The generator goes next to
`build_int32_list_page_iterator`:
```rust
/// Builds pages of a nullable list of nullable INT32 where every list has
/// `list_len` non-null items, the case where branches on the levels predict
well.
fn build_int32_fixed_list_page_iterator(
column_desc: ColumnDescPtr,
list_len: usize,
rows_per_page: usize,
) -> impl PageIterator + Clone {
let max_def_level = column_desc.max_def_level();
let max_rep_level = column_desc.max_rep_level();
let mut rng = seedable_rng();
let mut pages: Vec<Vec<parquet::column::page::Page>> = Vec::new();
for _i in 0..NUM_ROW_GROUPS {
let mut column_chunk_pages = Vec::new();
for _j in 0..PAGES_PER_GROUP {
let mut values: Vec<i32> = Vec::with_capacity(rows_per_page *
list_len);
let mut def_levels = Vec::with_capacity(rows_per_page *
list_len);
let mut rep_levels = Vec::with_capacity(rows_per_page *
list_len);
for _k in 0..rows_per_page {
rep_levels.push(0);
(1..list_len).for_each(|_| rep_levels.push(1));
for _l in 0..list_len {
def_levels.push(3);
values.push(rng.random());
}
}
let mut page_builder =
DataPageBuilderImpl::new(column_desc.clone(), values.len()
as u32, true);
page_builder.add_rep_levels(max_rep_level, &rep_levels);
page_builder.add_def_levels(max_def_level, &def_levels);
page_builder.add_values::<Int32Type>(Encoding::PLAIN, &values);
column_chunk_pages.push(page_builder.consume());
}
pages.push(column_chunk_pages);
}
InMemoryPageIterator::new(pages)
}
```
The group goes in `add_benches`, after `Int32ListList`:
```rust
let mut group =
c.benchmark_group("arrow_array_reader/ListArray/Int32LongList");
for (list_len, rows_per_page) in [(128, 10_000), (1024, 1_250)] {
let list_data =
build_int32_fixed_list_page_iterator(int32_list_desc.clone(),
list_len, rows_per_page);
let rows = NUM_ROW_GROUPS * PAGES_PER_GROUP * rows_per_page;
group.bench_function(format!("{list_len} items, no NULLs"), |b| {
b.iter(|| {
let reader = create_int32_list_reader(list_data.clone(),
int32_list_desc.clone());
count = bench_array_reader(reader);
});
assert_eq!(count, rows);
});
}
group.finish();
```
##########
parquet/src/arrow/array_reader/list_array.rs:
##########
@@ -78,6 +78,126 @@ impl<OffsetSize: OffsetSizeTrait>
ListArrayReader<OffsetSize> {
}
}
+/// Computes a list's offsets, its validity bitmap when `nullable`, and the
+/// number of child values it references, from the def/rep levels of its
+/// item reader.
+///
+/// Definition levels identify whether each list boundary contributes a
+/// child slot. For a nullable list, the states are:
+///
+/// - `d >= def_level`: list is present with a child item
+/// - `d == def_level - 1`: list is present but empty
+/// - `d <= def_level - 2`: list is null
+///
+/// Required lists do not have the null state, but still use the same
+/// `d >= def_level` test to distinguish child items from empty lists.
+/// Repetition levels identify list boundaries and whether a child item
+/// belongs directly to this list or to a nested child list.
+///
+/// `parent_threshold` is set when this list is itself a child of another
+/// list; entries with `d < threshold` belong to null/empty parent lists and
+/// are skipped.
+fn build_list_offsets_and_validity<O: OffsetSizeTrait>(
+ def_levels: &[i16],
+ rep_levels: &[i16],
+ def_level: i16,
+ rep_level: i16,
+ parent_threshold: Option<i16>,
+ nullable: bool,
+) -> Result<(Vec<O>, Option<BooleanBuffer>, usize)> {
+ let levels_len = def_levels.len().min(rep_levels.len());
+ // At most one list starts per level, plus the trailing offset
+ let mut offsets = vec![O::default(); levels_len + 1];
+ let mut validity = BooleanBufferBuilder::new(if nullable { levels_len }
else { 0 });
+
+ // Specialize the scan by nullable/parent-threshold mode so the hot loop
+ // does not check these options once per decoded level.
+ let fill = match (parent_threshold.is_some(), nullable) {
+ (false, false) => fill_list_offsets::<O, false, false>,
+ (false, true) => fill_list_offsets::<O, false, true>,
+ (true, false) => fill_list_offsets::<O, true, false>,
+ (true, true) => fill_list_offsets::<O, true, true>,
+ };
+ let (num_lists, num_children) = fill(
+ def_levels,
+ rep_levels,
+ def_level,
+ rep_level,
+ // Only read by the scans specialized with a threshold
+ parent_threshold.unwrap_or(i16::MIN),
+ &mut offsets,
+ &mut validity,
+ );
+
+ // Offsets never decrease, so the last one fitting means they all do
+ offsets[num_lists] = O::from_usize(num_children)
+ .ok_or_else(|| general_err!("offset of {} would overflow list array",
num_children))?;
+ offsets.truncate(num_lists + 1);
+
+ Ok((offsets, nullable.then(|| validity.finish()), num_children))
+}
+
+/// Writes the start offset of each list to `offsets` and, when `NULLABLE`,
+/// its validity bit to `validity`. Returns the number of lists and of child
+/// values. The trailing offset is left to the caller.
+///
+/// The scan does not branch on the level values: every level writes the
+/// current child count to the slot of the next list, and only a list start
+/// advances past that slot, so each list keeps the count from before its own
+/// first level. Validity bits collect in a word that is flushed every 64
lists.
+fn fill_list_offsets<O: OffsetSizeTrait, const HAS_THRESHOLD: bool, const
NULLABLE: bool>(
+ def_levels: &[i16],
+ rep_levels: &[i16],
+ def_level: i16,
+ rep_level: i16,
+ threshold: i16,
+ offsets: &mut [O],
+ validity: &mut BooleanBufferBuilder,
+) -> (usize, usize) {
+ // A list is present (empty or not) from this level up
+ let empty_level = def_level - 1;
+
+ let mut num_lists = 0;
+ let mut num_children = 0;
+ let mut word = 0u64;
+ let mut word_bits = 0;
+
+ for (&d, &r) in def_levels.iter().zip(rep_levels) {
+ // Entries of null/empty parent lists do not belong to this list
+ let keep = !HAS_THRESHOLD || d >= threshold;
+ // A level below this list's rep level starts a new list.
+ let start = keep & (r < rep_level);
+ // `d >= def_level` excludes null/empty lists, which carry no child
+ // value: emptiness is handled by this definition-level guard, not by
+ // the repetition level.
+ //
+ // `r <= rep_level` (not `==`) keeps only direct children: the first
+ // element of each list has `r < rep_level` (it coincides with an
+ // outer/row boundary), so `==` would drop it; continuation entries of
+ // a nested child's own list have `r > rep_level` and are excluded.
+ let child = keep & (d >= def_level) & (r <= rep_level);
+
+ offsets[num_lists] = O::usize_as(num_children);
+ if NULLABLE {
+ // Only a list start may set a bit, as non-starts do not advance
+ word |= ((start & (d >= empty_level)) as u64) << word_bits;
+ word_bits += start as usize;
+ if word_bits == 64 {
+ validity.append_word(word, 64);
+ word = 0;
+ word_bits = 0;
+ }
+ }
+ num_lists += start as usize;
+ num_children += child as usize;
+ }
+
+ if NULLABLE {
+ validity.append_word(word, word_bits);
+ }
+ (num_lists, num_children)
+}
Review Comment:
This scan makes long lists without NULLs about a third slower than `main`. I
ran the `arrow_reader` ListArray benches locally with the long-list case from
my other comment added. The setup was an Apple M5 Max, thin LTO with 16 codegen
units like the benchmark bot, and two rounds in alternating order. Every row
comes from the same run, and the untouched `Int32Array/plain encoded,
mandatory, no NULLs` case moved by at most 3%:
| Case | This PR | The change below |
|---|---:|---:|
| `Int32List/no NULLs` | -26% | -9% |
| `Int32List/half NULLs` | -27% | +1% |
| `StringList/half NULLs` | -27% | -6% |
| `Int32ListList/half NULLs` | -57% | -9% |
| `Int32LongList/128 items, no NULLs` | **+33%** | -14% |
| `Int32LongList/1024 items, no NULLs` | **+33%** | -8% |
A run with `-C llvm-args=-align-all-functions=7 -C
llvm-args=-align-all-nofallthru-blocks=7` on both sides gave every row in the
table the same sign, within 7 points. The cost is per level. When lists are
long, every branch in the old loop goes the same way and costs almost nothing.
Meanwhile the new loop does about 30 instructions per level on x86-64 and 22 on
aarch64, against 16 and 15 in the old one. It writes `offsets[num_lists]` on
every level and checks its bounds, and on x86 it reloads three values from the
stack because the loop runs out of registers:
```asm
cmp r12, qword ptr [rsp + 0x70] # offsets.len(), for the
offsets[num_lists] bounds check
cmp dx, word ptr [rsp + 0xc] # empty_level
mov rdx, qword ptr [rsp + 0x68] # offsets.as_mut_ptr()
mov dword ptr [rdx + 4*r12], r15d # offsets[num_lists] = num_children
```
The change in the right column of the table is one line in each of the four
loops on `main`, and no case I measured got slower with it by more than the 3%
the control moved:
```diff
- if d >= def_level && r <= rep_level {
- cur_offset += 1;
- }
+ cur_offset += (d >= def_level && r <= rep_level) as
usize;
```
LLVM keeps the old form as two branches, and on x86-64 it keeps `cur_offset`
on the stack (rustc 1.99.1, `x86_64-unknown-linux-gnu`):
```asm
cmp r8w, word ptr [rsp + 0x4] # d < def_level: skip
jl 0x753
cmp di, ax # r > rep_level: skip
jg 0x753
mov rdx, qword ptr [rsp + 0x8] # load cur_offset
inc rdx
mov qword ptr [rsp + 0x8], rdx # store it back
```
The `+=` form has no branch, and the counter stays in a register:
```asm
cmp di, word ptr [rsp + 0xe] # d >= def_level
setge al
cmp bp, word ptr [rsp + 0xc] # r <= rep_level
setle cl
and cl, al
movzx eax, cl
add r12, rax
```
The `r < rep_level` branch that guards `push` and `validity.append` is still
there, so this keeps only part of the short-list gain. Removing that branch is
what costs the long lists.
I also tried a version that builds 64-level bitmasks of list starts and
children and walks only the start bits with `trailing_zeros` and `count_ones`.
It kept most of the short-list gain, but long lists were still 10% (128 items)
and 18% (1024 items) slower than `main`. LLVM vectorizes `mask |= (bit as u64)
<< i` with 64-bit lanes. On x86-64-v3 that comes to about 10 instructions per
level, so it doesn't beat a branch that predicts well.
Could we start from the one-line change? If you find a design that keeps the
short-list gain without the long-list regression, that's great too. If the
design you land on still trades long lists for short ones, please say so in the
description with numbers for both cases. Once you push either version, we'll
run the benchmark bot on it so we can compare on x86 and Neoverse. These local
numbers are from Apple silicon only.
With the one-line change, `reference_offsets_and_validity`,
`test_offsets_and_validity_match_reference`, and their helpers can go. The
rewrite is equivalent by construction, because `bool as usize` is 0 or 1, and
the existing tests in this module already run all four loops.
`test_roundtrip_list_of_list` and `test_roundtrip_list_in_struct` can go too. I
planted five bugs in this PR's scan one at a time, and they failed only when
`test_list_array_reader` or `test_large_list_array_reader` also failed.
--
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]