Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support fastlanes bitpacking #2886

Merged
merged 35 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
c089644
feature: support fastlanes bitpacking for uint8 type
broccoliSpicy Sep 16, 2024
a1e3cdf
minor fix
broccoliSpicy Sep 16, 2024
3f340a3
fix a bug, add self.buffer_offset in byte range
broccoliSpicy Sep 17, 2024
9a6c489
minor fix 2
broccoliSpicy Sep 17, 2024
f55a445
feat: add fastlanes bitpacking for other types
broccoliSpicy Sep 18, 2024
7c21438
address initial PR comments
broccoliSpicy Sep 18, 2024
3b82ec5
Merge branch 'main' into fastlanes
broccoliSpicy Sep 18, 2024
f0bd3a8
fix lint
broccoliSpicy Sep 18, 2024
ce0f798
return a slice of LanceBuffer in `decode`
broccoliSpicy Sep 18, 2024
fb9ede2
use `elems_per_chunk` constant to represent 1024, delete
broccoliSpicy Sep 19, 2024
3ad773c
use macro in encode method
broccoliSpicy Sep 19, 2024
403e89d
Don't pass strings to the choose_array_encoder method when choosing a…
westonpace Sep 18, 2024
0ae8362
fix a bug in `bitpacked_for_non_neg_decode`
broccoliSpicy Sep 20, 2024
23e261c
add stable rust fastlanes
broccoliSpicy Sep 20, 2024
3f92fcd
Merge remote-tracking branch 'refs/remotes/origin/fastlanes' into fas…
broccoliSpicy Sep 20, 2024
dba9a48
fix lint
broccoliSpicy Sep 20, 2024
1eb75e2
remove external fastlanes crate
broccoliSpicy Sep 21, 2024
1485759
license header
broccoliSpicy Sep 21, 2024
8543f54
fix lint
broccoliSpicy Sep 21, 2024
ee78fc6
delete a unnecessary file rust/lance-encoding/compression-algo/mod.rs
broccoliSpicy Sep 21, 2024
fe3fda8
delete two redundant file
broccoliSpicy Sep 21, 2024
697af4a
hangle nullable and all null data block in `encode`.
broccoliSpicy Sep 23, 2024
922c2fe
fix `choose_array_encoder` issue when enable V2.1
broccoliSpicy Sep 24, 2024
f09cad7
fix lint
broccoliSpicy Sep 24, 2024
fc89bf4
fix a bug scheduling ranges for data types other than 32-bit width
broccoliSpicy Sep 24, 2024
d5b9201
Make sure to use version 2.1 in tests for bitpacking
westonpace Sep 24, 2024
13b757a
make `locate_chunk_start` and `locate_chunk_end` a method
broccoliSpicy Sep 24, 2024
ca4dba3
Merge branch 'main' into fastlanes
broccoliSpicy Sep 24, 2024
f42af4c
add test_pack
broccoliSpicy Sep 25, 2024
1c2878b
add test_unchecked_pack
broccoliSpicy Sep 25, 2024
688bb1f
address PR comments
broccoliSpicy Sep 25, 2024
4d7557f
Update rust/lance-encoding/src/buffer.rs
broccoliSpicy Sep 25, 2024
c7ecb08
Merge branch 'fix/use-v2-1-on-bitpack-tests' of https://github.com/we…
broccoliSpicy Sep 25, 2024
dedb306
fix fastlanes original code link
broccoliSpicy Sep 27, 2024
655a063
lint
broccoliSpicy Sep 27, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions protos/encodings.proto
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,18 @@ message Bitpacked {
bool signed = 4;
}

// Items are bitpacked in a buffer
message BitpackedForNonNeg {
// the number of bits used for a value in the buffer
uint64 compressed_bits_per_value = 1;

// the number of bits of the uncompressed value. e.g. for a u32, this will be 32
uint64 uncompressed_bits_per_value = 2;

// The items in the list
Buffer buffer = 3;
}
Comment on lines +193 to +203
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think BitpackedWithNeg` will look like?

Copy link
Contributor Author

@broccoliSpicy broccoliSpicy Sep 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I plan to make it a cascading encoding of a BTreeMap of row number index to real value for a few very wide(bit-width) values (negative values) then bitpacking, for arrays that have too many negative values (for example: 50 percent), I think we should not use bitpacking on it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In theory these should still may be bitpackable right? For example if all data is between [-8, 8] then we could shift to [0, 16] and bitpack? Although I suppose frame-of-reference would do that for us 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, I think there might be some literatures focusing on how to intuitively combine lightweight integer encoding algorithms, I will research on that.


// An array encoding for shredded structs that will never be null
//
// There is no actual data in this column.
Expand Down Expand Up @@ -240,6 +252,7 @@ message ArrayEncoding {
PackedStruct packed_struct = 9;
Bitpacked bitpacked = 10;
FixedSizeBinary fixed_size_binary = 11;
BitpackedForNonNeg bitpacked_for_non_neg = 12;
}
}

Expand Down
2 changes: 2 additions & 0 deletions rust/lance-encoding/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ snafu.workspace = true
tokio.workspace = true
tracing.workspace = true
zstd.workspace = true
fastlanes = "0.1.5"
bytemuck = "=1.18.0"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these being used?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, they are used in the bitpacking_fastlanes.rs


[dev-dependencies]
lance-testing.workspace = true
Expand Down
45 changes: 43 additions & 2 deletions rust/lance-encoding/benches/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright The Lance Authors
use std::{collections::HashMap, sync::Arc};

use arrow_array::{RecordBatch, UInt32Array};
use arrow_array::{RecordBatch, UInt32Array, UInt8Array};
use arrow_schema::{DataType, Field, Schema, TimeUnit};
use arrow_select::take::take;
use criterion::{criterion_group, criterion_main, Criterion};
Expand Down Expand Up @@ -60,6 +60,47 @@ const ENCODING_OPTIONS: EncodingOptions = EncodingOptions {
keep_original_array: true,
};

fn bench_decode2(c: &mut Criterion) {
let rt = tokio::runtime::Runtime::new().unwrap();
let mut group = c.benchmark_group("decode_uint8");
group.measurement_time(std::time::Duration::new(12, 0));
let array = UInt8Array::from(vec![5; 1024 * 1024 * 1024]);
let data = RecordBatch::try_new(
Arc::new(Schema::new(vec![Field::new(
"uint8",
DataType::UInt8,
false,
)])),
vec![Arc::new(array)],
)
.unwrap();
let lance_schema =
Arc::new(lance_core::datatypes::Schema::try_from(data.schema().as_ref()).unwrap());
let input_bytes = data.get_array_memory_size();
group.throughput(criterion::Throughput::Bytes(input_bytes as u64));
let encoding_strategy = CoreFieldEncodingStrategy::default();
let encoded = rt
.block_on(encode_batch(
&data,
lance_schema,
&encoding_strategy,
&ENCODING_OPTIONS,
))
.unwrap();
group.bench_function("uint8", |b| {
b.iter(|| {
let batch = rt
.block_on(lance_encoding::decoder::decode_batch(
&encoded,
&FilterExpression::no_filter(),
&DecoderMiddlewareChain::default(),
))
.unwrap();
assert_eq!(data.num_rows(), batch.num_rows());
})
});
}

fn bench_decode(c: &mut Criterion) {
let rt = tokio::runtime::Runtime::new().unwrap();
let mut group = c.benchmark_group("decode_primitive");
Expand Down Expand Up @@ -314,7 +355,7 @@ criterion_group!(
name=benches;
config = Criterion::default().significance_level(0.1).sample_size(10)
.with_profiler(pprof::criterion::PProfProfiler::new(100, pprof::criterion::Output::Flamegraph(None)));
targets = bench_decode, bench_decode_fsl, bench_decode_str_with_dict_encoding, bench_decode_packed_struct,
targets = bench_decode2, bench_decode, bench_decode_fsl, bench_decode_str_with_dict_encoding, bench_decode_packed_struct,
bench_decode_str_with_fixed_size_binary_encoding);

// Non-linux version does not support pprof.
Expand Down
30 changes: 30 additions & 0 deletions rust/lance-encoding/src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,36 @@ impl LanceBuffer {
Self::Borrowed(Buffer::from_vec(vec))
}

pub fn reinterpret_to_rust_native<T>(&mut self) -> Result<&[T]>
where
T: Copy, // Ensure `T` can be copied (as needed for safely reinterpreting bytes)
{
let buffer = self.borrow_and_clone();

let buffer = buffer.into_buffer();

// Get the raw byte slice from the buffer.
let byte_slice = buffer.as_slice();

// Safety check - ensure that the byte slice length is a multiple of `T`.
if byte_slice.len() % std::mem::size_of::<T>() != 0 {
return Err(Error::Internal {
message: "Buffer size is not a multiple of the target type size".to_string(),
location: location!(),
});
}

// Reinterpret the byte slice as a slice of `T`.
let typed_slice = unsafe {
std::slice::from_raw_parts(
byte_slice.as_ptr() as *const T,
byte_slice.len() / std::mem::size_of::<T>(),
)
};

Ok(typed_slice)
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is this different from borrow_to_typed_slice?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, this is actually the same, I should delete this function

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

/// Reinterprets a LanceBuffer into a Vec<T>
///
/// Unfortunately, there is no way to do this safely in Rust without a copy, even if
Expand Down
19 changes: 19 additions & 0 deletions rust/lance-encoding/src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use snafu::{location, Location};
use crate::buffer::LanceBuffer;
use crate::data::DataBlock;
use crate::encodings::logical::r#struct::StructFieldEncoder;
use crate::encodings::physical::bitpack_fastlanes::compute_compressed_bit_width_for_non_neg;
use crate::encodings::physical::bitpack_fastlanes::BitpackedForNonNegArrayEncoder;
use crate::encodings::physical::block_compress::CompressionScheme;
use crate::encodings::physical::dictionary::AlreadyDictionaryEncoder;
use crate::encodings::physical::fsst::FsstArrayEncoder;
Expand Down Expand Up @@ -331,6 +333,23 @@ impl CoreArrayEncodingStrategy {

Ok(Box::new(PackedStructEncoder::new(inner_encoders)))
}
DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 => {
let compressed_bit_width = compute_compressed_bit_width_for_non_neg(arrays);
Ok(Box::new(BitpackedForNonNegArrayEncoder::new(
compressed_bit_width as usize,
data_type.clone(),
)))
}

// for signed integers, I intend to make it a cascaded encoding, a sparse array for the negative values and very wide(bit-width) values,
// then a bitpacked array for the narrow(bit-width) values, I need `BitpackedForNeg` to be merged first
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// for signed integers, I intend to make it a cascaded encoding, a sparse array for the negative values and very wide(bit-width) values,
// then a bitpacked array for the narrow(bit-width) values, I need `BitpackedForNeg` to be merged first
// TODO: for signed integers, I intend to make it a cascaded encoding, a sparse array for the negative values and very wide(bit-width) values,
// then a bitpacked array for the narrow(bit-width) values, I need `BitpackedForNeg` to be merged first

Minor nit: add TODO to make it clear this is a todo

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => {
let compressed_bit_width = compute_compressed_bit_width_for_non_neg(arrays);
Ok(Box::new(BitpackedForNonNegArrayEncoder::new(
compressed_bit_width as usize,
data_type.clone(),
)))
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's make sure we only use the bitpacking encoder if the version is 2.1.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

_ => Ok(Box::new(BasicEncoder::new(Box::new(
ValueEncoder::default(),
)))),
Expand Down
17 changes: 17 additions & 0 deletions rust/lance-encoding/src/encodings/physical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod basic;
pub mod binary;
pub mod bitmap;
pub mod bitpack;
pub mod bitpack_fastlanes;
pub mod block_compress;
pub mod dictionary;
pub mod fixed_size_binary;
Expand Down Expand Up @@ -109,6 +110,19 @@ fn get_bitpacked_buffer_decoder(
))
}

fn get_bitpacked_for_non_neg_buffer_decoder(
encoding: &pb::BitpackedForNonNeg,
buffers: &PageBuffers,
) -> Box<dyn PageScheduler> {
let (buffer_offset, _buffer_size) = get_buffer(encoding.buffer.as_ref().unwrap(), buffers);

Box::new(bitpack_fastlanes::BitpackedForNonNegScheduler::new(
encoding.compressed_bits_per_value,
encoding.uncompressed_bits_per_value,
buffer_offset,
))
}

/// Convert a protobuf array encoding into a physical page scheduler
pub fn decoder_from_array_encoding(
encoding: &pb::ArrayEncoding,
Expand Down Expand Up @@ -252,6 +266,9 @@ pub fn decoder_from_array_encoding(
buffer_offset,
))
}
pb::array_encoding::ArrayEncoding::BitpackedForNonNeg(bitpacked) => {
get_bitpacked_for_non_neg_buffer_decoder(bitpacked, buffers)
}
// Currently there is no way to encode struct nullability and structs are encoded with a "header" column
// (that has no data). We never actually decode that column and so this branch is never actually encountered.
//
Expand Down
Loading
Loading