diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index 6f38d226c..f73d8636a 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -80,6 +80,12 @@ To include newly appended rows, build a new `Permutation` (and any `StreamingDat against the updated table. Permutations written before this behavior shipped continue to read as they did before. +## Sort memory for permutation builds + +The permutation sort runs on the SDK client for both Embedded and Enterprise tables. Its memory pool defaults to +100 MiB. If a permutation sort runs out of memory, set `LANCEDB_PERM_BUILDER_MEMORY_LIMIT` to a byte count in the +client environment. Shuffle buffers and the materialized permutation can use additional client memory. + ## Output formats {#output-formats} By default, a `Table` data loader emits Arrow data. `collate_fn` is PyTorch's batching hook: PyTorch calls it to diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 357a98f13..37b1806ac 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -4,10 +4,12 @@ use std::{collections::HashMap, sync::Arc}; use arrow_array::RecordBatch; +use datafusion::error::DataFusionError; use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_common::utils::memory::get_record_batch_memory_size; use datafusion_execution::{disk_manager::DiskManagerBuilder, runtime_env::RuntimeEnvBuilder}; use datafusion_expr::col; -use futures::TryStreamExt; +use futures::{StreamExt, TryStreamExt, stream}; use lance_core::ROW_ID; use lance_datafusion::exec::SessionContextExt; @@ -17,7 +19,7 @@ use crate::{ connect, database::{CreateTableMode, CreateTableRequest, Database}, dataloader::permutation::{ - shuffle::{Shuffler, ShufflerConfig}, + shuffle::{PERMUTATION_SHUFFLE_RUN_ROWS, Shuffler, ShufflerConfig}, split::{SPLIT_ID_COLUMN, SplitStrategy, Splitter}, util::{TemporaryDirectory, rename_column}, }, @@ -216,21 +218,48 @@ impl PermutationBuilder { async fn sort_by_column( &self, - data: SendableRecordBatchStream, + mut data: SendableRecordBatchStream, column: &str, + memory_limit: usize, + ordered_single_batch: bool, ) -> Result { - let memory_limit = std::env::var("LANCEDB_PERM_BUILDER_MEMORY_LIMIT") - .unwrap_or_else(|_| DEFAULT_MEMORY_LIMIT.to_string()) - .parse::() - .unwrap_or_else(|_| { - log::error!( - "Failed to parse LANCEDB_PERM_BUILDER_MEMORY_LIMIT, using default: {}", - DEFAULT_MEMORY_LIMIT - ); - DEFAULT_MEMORY_LIMIT + let config = SessionConfig::default(); + if ordered_single_batch && let Some(batch) = data.try_next().await? { + let merge_reservation = match self.config.temp_dir { + TemporaryDirectory::None => 0, + _ => config.options().execution.sort_spill_reservation_bytes, + }; + // This path only receives the two primitive columns from a single + // random-split run. DataFusion charges both the retained buffers and + // the size of the rows, even if a split count truncated the batch. + let logical_size = batch.columns().iter().try_fold(0usize, |size, column| { + Ok::<_, Error>(size.saturating_add(column.to_data().get_slice_memory_size()?)) }); + let charge = get_record_batch_memory_size(&batch).saturating_add(logical_size?); + let schema = data.schema(); + if charge > memory_limit.saturating_sub(merge_reservation) { + // Split IDs were assigned in ascending order after the shuffle. + // Write that order directly when an empty sorter cannot admit + // the batch. The writer can consume zero-copy slices. + let batch_size = config.batch_size(); + let batches = (0..batch.num_rows()) + .step_by(batch_size) + .map(move |offset| { + Ok(batch.slice(offset, batch_size.min(batch.num_rows() - offset))) + }); + return Ok(Box::pin(SimpleRecordBatchStream::new( + stream::iter(batches).chain(data), + schema, + ))); + } + data = Box::pin(SimpleRecordBatchStream::new( + stream::once(async move { Ok(batch) }).chain(data), + schema, + )); + } + let ctx = SessionContext::new_with_config_rt( - SessionConfig::default(), + config, RuntimeEnvBuilder::new() .with_memory_limit(memory_limit, 1.0) .with_disk_manager_builder( @@ -261,9 +290,17 @@ impl PermutationBuilder { let column = column.to_string(); let schema = df_stream.schema(); - let stream = df_stream.map_err(move |e| Error::Other { - message: format!("Failed to execute sort by {}: {}", column, e), - source: Some(e.into()), + let stream = df_stream.map_err(move |e| { + let mut message = format!("Failed to execute sort by {}: {}", column, e); + if matches!(e.find_root(), DataFusionError::ResourcesExhausted(_)) { + message.push_str( + " Set LANCEDB_PERM_BUILDER_MEMORY_LIMIT on the client to change the sort budget in bytes.", + ); + } + Error::Other { + message, + source: Some(e.into()), + } }); Ok(Box::pin(SimpleRecordBatchStream { schema, stream })) } @@ -295,7 +332,21 @@ impl PermutationBuilder { } /// Builds the permutation table and stores it in the given database. - pub async fn build(mut self) -> Result { + pub async fn build(self) -> Result
{ + let memory_limit = std::env::var("LANCEDB_PERM_BUILDER_MEMORY_LIMIT") + .unwrap_or_else(|_| DEFAULT_MEMORY_LIMIT.to_string()) + .parse::() + .unwrap_or_else(|_| { + log::error!( + "Failed to parse LANCEDB_PERM_BUILDER_MEMORY_LIMIT, using default: {}", + DEFAULT_MEMORY_LIMIT + ); + DEFAULT_MEMORY_LIMIT + }); + self.build_with_sort_memory_limit(memory_limit).await + } + + async fn build_with_sort_memory_limit(mut self, memory_limit: usize) -> Result
{ // Remote tables resolve latest independently for each request, and a // native handle can refresh or answer a query from a namespace server. // Use a separate pinned handle so count, projection, and scan all refer @@ -369,7 +420,8 @@ impl PermutationBuilder { let rows = if self.base_table.base_table().scan_order_is_deterministic() { rows } else { - self.sort_by_column(rows, ROW_ID).await? + self.sort_by_column(rows, ROW_ID, memory_limit, false) + .await? }; let split_data = splitter.apply(rows, num_rows).await?; @@ -381,7 +433,7 @@ impl PermutationBuilder { seed, clump_size, temp_dir: self.config.temp_dir.clone(), - max_rows_per_file: 10 * 1024 * 1024, + max_rows_per_file: PERMUTATION_SHUFFLE_RUN_ROWS, }); shuffler.shuffle(split_data, output_rows).await? } @@ -392,7 +444,17 @@ impl PermutationBuilder { needs_sort |= !matches!(self.config.shuffle_strategy, ShuffleStrategy::None); let sorted = if needs_sort { - self.sort_by_column(shuffled, SPLIT_ID_COLUMN).await? + let ordered_single_batch = + matches!(self.config.split_strategy, SplitStrategy::Random { .. }) + && matches!(self.config.shuffle_strategy, ShuffleStrategy::None) + && num_rows < PERMUTATION_SHUFFLE_RUN_ROWS; + self.sort_by_column( + shuffled, + SPLIT_ID_COLUMN, + memory_limit, + ordered_single_batch, + ) + .await? } else { shuffled }; @@ -994,6 +1056,71 @@ mod tests { ); } + #[tokio::test] + async fn test_oversized_random_split_keeps_seeded_order() { + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let data = lance_datagen::gen_batch() + .col("value", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(4096), BatchCount::from(1)); + let base = db.create_table("base", data).execute().await.unwrap(); + + let builder = || { + PermutationBuilder::new(base.clone()) + .with_split_strategy( + SplitStrategy::Random { + seed: Some(42), + sizes: SplitSizes::Counts(vec![1000, 1000, 1000]), + clump_size: None, + }, + None, + ) + .with_filter("value >= 8".to_string()) + .with_temp_dir(TemporaryDirectory::None) + }; + let read = |table: Table| async move { + let stream = table.query().execute().await.unwrap(); + let schema = stream.schema(); + let batches: Vec<_> = stream.try_collect().await.unwrap(); + arrow::compute::concat_batches(&schema, &batches).unwrap() + }; + + let reference = read( + builder() + .build_with_sort_memory_limit(DEFAULT_MEMORY_LIMIT) + .await + .unwrap(), + ) + .await; + let memory_limit = 64 * 1024; + let bounded = read( + builder() + .build_with_sort_memory_limit(memory_limit) + .await + .unwrap(), + ) + .await; + assert_eq!(bounded.num_rows(), 3000); + assert_eq!(bounded, reference); + + let error = builder() + .with_shuffle_strategy(ShuffleStrategy::Random { + seed: Some(13), + clump_size: None, + }) + .build_with_sort_memory_limit(memory_limit) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("LANCEDB_PERM_BUILDER_MEMORY_LIMIT") + ); + } + /// Rows that have not been flushed to the base table have no row id, so a /// permutation cannot reference them. Reading the base table alone would drop /// them from training without saying so, so the table is refused instead. diff --git a/rust/lancedb/src/dataloader/permutation/shuffle.rs b/rust/lancedb/src/dataloader/permutation/shuffle.rs index adacdb881..33551a4e4 100644 --- a/rust/lancedb/src/dataloader/permutation/shuffle.rs +++ b/rust/lancedb/src/dataloader/permutation/shuffle.rs @@ -28,6 +28,8 @@ use crate::{ dataloader::permutation::util::{TemporaryDirectory, non_crypto_rng}, }; +pub(super) const PERMUTATION_SHUFFLE_RUN_ROWS: u64 = 10 * 1024 * 1024; + #[derive(Debug, Clone)] pub struct ShufflerConfig { /// An optional seed to make the shuffle deterministic diff --git a/rust/lancedb/src/dataloader/permutation/split.rs b/rust/lancedb/src/dataloader/permutation/split.rs index 4bc7aee0f..1913e6389 100644 --- a/rust/lancedb/src/dataloader/permutation/split.rs +++ b/rust/lancedb/src/dataloader/permutation/split.rs @@ -19,7 +19,7 @@ use crate::{ Error, Result, arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}, dataloader::{ - permutation::shuffle::{Shuffler, ShufflerConfig}, + permutation::shuffle::{PERMUTATION_SHUFFLE_RUN_ROWS, Shuffler, ShufflerConfig}, permutation::util::{TemporaryDirectory, non_crypto_rng}, }, query::{Query, QueryBase, Select}, @@ -531,7 +531,7 @@ impl Splitter { let shuffler = Shuffler::new(ShufflerConfig { seed: *seed, // In this case we are only shuffling row ids so we can use a large max_rows_per_file - max_rows_per_file: 10 * 1024 * 1024, + max_rows_per_file: PERMUTATION_SHUFFLE_RUN_ROWS, temp_dir: self.temp_dir.clone(), clump_size: *clump_size, });