Skip to content

feat: add Bootstrap split strategy for sampling with replacement - #4597

Merged
jackye1995 merged 8 commits into
lancedb:mainfrom
jackye1995:jack/bootstrap-sampling-split
Oct 22, 2026
Merged

jackye1995 merged 8 commits into
lancedb:mainfrom
jackye1995:jack/bootstrap-sampling-split

Conversation

@jackye1995

@jackye1995 jackye1995 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Context

StreamingDataset's shipped split strategies (split_random, split_sequential, split_hash, split_calculated) all share one trait: every row in the base table is assigned to exactly one split, exactly once. They only differ in how that one-to-one assignment is chosen -- none of them can express "give me a resampled stream of N rows, allowing repeats."

That's a distinct, common need in ML training: the bootstrap -- the statistical technique (Efron, 1979) of estimating a dataset's properties by resampling it with replacement. It's the same sense scikit-learn's bagging classifiers mean by bootstrap=True. SplitStrategy::Bootstrap adds exactly this to the data loader: sample rows uniformly with replacement from the (optionally filtered) base table, independently per split.

Main use cases

  • Bagging / ensemble training (e.g. random forests): each split trains on an independent bootstrap resample of the training set.
  • Oversampling a rare class: filter to the minority class, then sample it up to whatever count balances it against the majority, instead of exhausting its small set once per epoch.
  • Fixed-size training steps independent of dataset size: want exactly N batches per epoch regardless of whether the table has 50 rows or 50 million? Set num_samples directly instead of it being implicitly len(dataset).
  • Weighted sampling without a weight column: filter to "eligible" rows (e.g. a windowed-sampling workload filtering to valid window-start positions), then bootstrap the filtered set -- an item with more eligible rows is naturally drawn proportionally more often, with no explicit per-row weight needed.

Example (an actual run, not a hypothetical one)

A 5-row base table (row_id 0..4), sampled via Bootstrap { num_samples: 8, sizes: Fixed(2), seed: Some(42) }:

row_id  split_id
     0         0
     2         0
     4         0
     4         0      <- row 4 repeated within split 0
     4         1      <- row 4 also drawn in split 1 (independent draw)
     4         1
     1         1
     2         1

8 output rows from a 5-row table -- not 5. Row 4 drawn 4 times total, row 3 never drawn. That's with-replacement sampling actually behaving like with-replacement sampling, not an even round-robin dressed up with a new name.

What changed

Adds SplitStrategy::Bootstrap (uniform sampling with replacement, optionally filtered, independently seeded per split -- a given split's content doesn't depend on how many other splits there are, the same elastic-determinism property documented for the loader's other strategies). No new PermutationBuilder Rust method was needed: with_split_strategy already accepts any SplitStrategy value generically. Python binding: PermutationBuilder.bootstrap_sample(num_samples, *, ratios=None, counts=None, fixed=None, seed=None, split_names=None), mirroring split_random's existing shape.

Also adds a generic split_strategy parameter to StreamingDataset's constructor (a callable taking/returning a PermutationBuilder), since it previously could only reach split_random/split_sequential even though split_hash/split_calculated already shipped. This unblocks Bootstrap and any future strategy without further constructor changes.

StreamingDataset's shipped split strategies (split_random, split_sequential,
split_hash, split_calculated) all assign each of a table's existing rows to
exactly one split, exactly once -- none can produce a multiset with repeats.
This adds SplitStrategy::Bootstrap: uniform sampling with replacement,
optionally filtered, independently seeded per split so a split's content
does not depend on how many other splits there are. Useful for bootstrap
resampling, oversampling rare classes, or any training workload that wants
a fixed-size stream of random draws rather than a single deterministic pass
over every row -- e.g. time-series/video-clip windowed sampling, where a
window is a contiguous row range and valid starts are filtered in.

Also adds a generic split_strategy escape hatch to StreamingDataset's
constructor (a callable taking/returning a PermutationBuilder), since it
previously could only reach split_random/split_sequential even though
split_hash/split_calculated already shipped. This unblocks Bootstrap and
any future strategy without further constructor changes.

No new PermutationBuilder Rust method needed: with_split_strategy already
accepts any SplitStrategy value. Added the Python binding
(bootstrap_sample) mirroring split_random's existing shape.
…teration

Permutation's plain sequential __iter__() returns empty for a permutation
table with repeated row_ids (confirmed directly: len() is correct,
__getitems__ returns the right rows, but iterating yields nothing) --
a pre-existing limitation of Permutation's iterator unrelated to Bootstrap
sampling's correctness. Doesn't affect StreamingDataset or any real caller,
since both only ever read via explicit-index batched fetches
(take_offsets/__getitems__), never the plain iterator. Noted in the test,
not fixed here (separate, out of scope).
@github-actions github-actions Bot added enhancement New feature or request Python Python SDK Rust Rust related issues labels Oct 19, 2026

@westonpace westonpace left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No concerns if we want to proceed. We should also make it easy though for users to provide their own sampler. I had originally thought they could do that with split_calculated but I think a UDF-based splitter is also useful.

Otherwise the list of sampling methods will just keep growing. For example, some users want to sample clumps of rows. Other users want to sample in such a way that they pick a representative set of samples (e.g. if there is some color column they want an equal number of samples for each color), etc. etc.

@jackye1995
jackye1995 marked this pull request as ready for review October 21, 2026 20:59

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@jackye1995

Copy link
Copy Markdown
Contributor Author

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Findings marked 🟡 are optional suggestions and need no follow-up push.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🔴 rust/lancedb/src/dataloader/permutation/builder.rs — Callers who combine bootstrap_sample with .shuffle() on a large filtered table get a failed execute(). The shuffler is still told the input row count rather than num_samples. builder.rs:317 passes num_rows, the filtered count_rows. Bootstrap's splitter now outputs num_samples rows instead. Once num_rows reaches max_rows_per_file (10M), the disk shuffle checks the row count and fails with "Expected {num_rows} rows but saw {n} rows". Fix: pass the splitter's real output row count to the shuffler, i.e. num_samples for Bootstrap and num_rows for every other strategy.

    Why this was flagged

    Trigger: permutation_builder(tbl).bootstrap_sample(N, fixed=k).shuffle(seed=..) (or the same chain inside a StreamingDataset(split_strategy=...) callable). The filtered table has at least 1010241024 rows and N > num_rows. builder.rs:293 sets num_rows from count_rows(filter). builder.rs:317 then calls shuffler.shuffle(split_data, num_rows). But apply_bootstrap (split.rs) emits num_samples rows. shuffle.rs:286 takes the do_shuffle path because num_rows >= max_rows_per_file. shuffle.rs:172 then fails with Expected {} rows but saw {} rows. When N < num_rows, the is_last check at shuffle.rs:171 never matches the real stream end. On the base branch every split strategy outputs exactly num_rows rows, so the count was always right. No validation rejects Bootstrap combined with a shuffle strategy.

    Verification: Trigger: Bootstrap combined with .shuffle(), where the filtered row count is at least 1010241024 and num_samples is larger than that count. builder.rs calls shuffler.shuffle(split_data, num_rows), but apply_bootstrap (split.rs) emits about num_samples rows. shuffle.rs then takes do_shuffle, which fails with "Expected {} rows but saw {} rows". Before this PR, every strategy produced exactly num_rows rows.

Comment thread python/python/lancedb/streaming.py Resolved
Comment thread python/python/lancedb/streaming.py Resolved
Comment on lines +127 to +132
/// exactly the with-replacement behavior the name promises, not an even round-robin.
Bootstrap {
num_samples: u64,
sizes: SplitSizes,
seed: Option<u64>,
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 (optional) Possible SDK parity gap: TypeScript users cannot use the new Bootstrap strategy. Python gets bootstrap_sample, but the nodejs permutation builder has no equivalent. SplitStrategy::Bootstrap was added in the shared core. nodejs/src/permutation.rs and nodejs/lancedb/permutation.ts already expose splitRandom and the other strategies, but nothing builds Bootstrap. Fix: a follow-up issue to add bootstrapSample(numSamples, {ratios, counts, fixed, seed, splitNames}) to the nodejs builder, mirroring the Python binding. [also at: python/src/permutation.rs:223 - Possible SDK parity gap: Node.js users cannot use the new Bootstrap strategy. The Python binding adds bootstrap_sample, but the TypeScript PermutationBuilder has no equivalent.]

Why this was flagged

The core enum gains a user-facing Bootstrap variant at split.rs:127-132. python/src/permutation.rs adds bootstrap_sample. A grep shows nodejs/src/permutation.rs and nodejs/lancedb/permutation.ts implement splitRandom and the sibling split strategies but contain no Bootstrap construction. So the feature is reachable from Python only. This is advisory per the repository's cross-SDK parity guidance, not a merge blocker.

Verification: The diff adds a user-facing SplitStrategy::Bootstrap { num_samples, sizes, seed } variant to the shared core (rust/lancedb/src/dataloader/permutation/split.rs, around lines 128-132). Python exposes it through bootstrap_sample in python/src/permutation.rs. The nodejs binding does not. So the new feature can only be reached from Python and Rust.

- Shuffler was told the input row count instead of Bootstrap's actual
  output count (num_samples), causing a disk-shuffle row-count mismatch
  error once the filtered input crossed max_rows_per_file. Splitter now
  exposes output_row_count() and the builder uses it.
- apply_bootstrap sampled against a separately-computed row count rather
  than the scan's actual length, and used unwrap() throughout; a
  concurrent append/delete between the two queries could panic instead
  of erroring. Now samples against the scanned length directly, rejects
  an empty scan cleanly, and propagates every Arrow error with `?`.
- num_samples had no upper bound, and allocation failure aborted the
  process instead of raising. Vec::try_reserve_exact makes it a normal
  catchable error (peak memory and full streaming are unchanged, and
  remain a follow-up).
- StreamingDataset.split_strategy never validated that the strategy's
  split count matches num_splits, silently dropping rows or leaving
  ranks with empty splits on a mismatch. Now validated at construction.
- load_state_dict/merge_state_dicts only checked num_splits/shuffle_seed,
  which split_strategy ignores entirely -- a non-deterministically
  reseeded strategy (e.g. bootstrap_sample with no seed) could resume
  against a completely different permutation undetected. Both now also
  check a cached permutation fingerprint, backward compatible with
  checkpoints saved before this key existed.

Node.js binding parity for Bootstrap is a separate, larger follow-up
(flagged, not addressed here).
@jackye1995

Copy link
Copy Markdown
Contributor Author

Addressed in 83eb3e6:

  • Shuffle row-count mismatch (🔴): fixed. Splitter now exposes output_row_count() (num_samples for Bootstrap, num_rows for everything else) and the builder passes that to the shuffler instead of assuming input/output row counts always match.
  • Checkpoint resume against a different permutation (🔴): fixed. state_dict()/load_state_dict()/merge_state_dicts() now also carry a cached permutation fingerprint (row count + a hash of row_id/split_id), checked alongside num_splits/shuffle_seed, backward compatible with checkpoints saved before this key existed.
  • num_rows vs scanned length, unwrap() panics: fixed. apply_bootstrap now samples against the scan's actual materialized length, rejects an empty scan with a proper error, and propagates every Arrow error with ? instead of unwrap().
  • num_splits not validated against split_strategy's actual split count: fixed. Validated at StreamingDataset construction now.
  • Unbounded num_samples allocation aborting the process: partially fixed. Vec::try_reserve_exact turns an allocation failure into a normal catchable error instead of a process abort. Peak memory and full chunked/streamed output are unchanged -- a larger follow-up if this needs to support very large num_samples efficiently, not done here.
  • Node.js parity: not addressed here, tracked as a follow-up -- agreed this is advisory, not a blocker for this PR.

New test coverage for each: test_output_row_count, test_bootstrap_rejects_empty_scan_cleanly (split.rs), test_split_strategy_num_splits_mismatch_raises, test_split_strategy_permutation_mismatch_on_resume_raises, test_split_strategy_resume_with_matching_permutation_succeeds (test_elastic_dataloader.py). Full existing suite (2152 passed) plus cargo test/clippy/fmt all clean against this change.

@jackye1995

Copy link
Copy Markdown
Contributor Author

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

Comment thread python/python/lancedb/streaming.py Resolved
- output_row_count returned num_samples for Bootstrap, not the row count
  apply_bootstrap actually emits. sizes.to_counts(num_samples) can sum to
  less than num_samples (e.g. Fixed(n) when n doesn't divide evenly, or
  explicit counts/ratios that don't use every sample), so the shuffler
  could be told a count higher than the real stream -- a disk-shuffle
  row-count mismatch in a different shape than before, or a clump-size
  divisibility error. Now sums to_counts' actual per-split counts.
- The permutation fingerprint added for split_strategy checkpoints was
  being recorded and checked unconditionally, including for the default
  split_random/split_sequential paths. It hashes physical row ids, which
  are not stable across compaction by default -- compacting the table
  between state_dict() and load_state_dict() on a plain StreamingDataset
  now spuriously raised "permutation mismatch" even though the seeded
  permutation itself hadn't changed. Scoped to split_strategy only, where
  shuffle_seed/num_splits alone can't already guard it; the default paths
  go back to relying on those two checks exactly as before this feature.

New tests: test_output_row_count's uneven-Fixed case, and three
checkpoint tests confirming the fingerprint is split_strategy-only and
that a plain checkpoint survives real compaction (empirically confirmed
row ids change: 2 fragments -> 1 via optimize()).
@jackye1995

Copy link
Copy Markdown
Contributor Author

Both caught regressions fixed in 5aed1b9:

  • `output_row_count` for Bootstrap returning `num_samples` instead of what `apply_bootstrap` actually emits (`sizes.to_counts(num_samples)` can sum to less, e.g. `Fixed(n)` not dividing evenly): fixed, now sums `to_counts`' real per-split counts.
  • Permutation fingerprint applied unconditionally, breaking compaction-based resume for the default `split_random`/`split_sequential` paths (row ids aren't stable across compaction by default): fixed, scoped to the `split_strategy` path only -- the default paths rely solely on `shuffle_seed`/`num_splits` again, exactly as before this feature existed.

New tests for both, including an end-to-end one that actually compacts a table (confirmed empirically: a 2-fragment table's row ids differ after `optimize()`) and resumes a plain checkpoint across it.

@jackye1995

Copy link
Copy Markdown
Contributor Author

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

Comment thread python/python/lancedb/streaming.py Resolved
…l ids

The num_splits check added earlier only compared the set of split ids
against range(num_splits), not each split's row count. The round-robin
iteration (_iter_owned) assumes every owned split has the same size and
stops as soon as any one is exhausted, so a split_strategy using
ratios/counts/weighted split_hash (unlike fixed=num_splits, which every
other path always uses) could pass that check while still silently
dropping rows from the larger splits -- or, across ranks, ending at
different row counts and desyncing a distributed run's end-of-epoch
collectives. Now also rejects unequal per-split row counts.
@jackye1995

Copy link
Copy Markdown
Contributor Author

Third regression fixed in 700c648: the `num_splits` validation added earlier only checked that all split ids 0..num_splits-1 exist, not that each split has the same row count. `split_strategy` with `ratios`/`counts`/weighted `split_hash` (unlike `fixed=num_splits`) can produce unequal split sizes, which the round-robin iteration doesn't handle -- it stops as soon as any one owned split is exhausted, silently dropping rows from larger splits and desyncing ranks in a distributed run. Now also rejects unequal per-split row counts, with a new test (`test_split_strategy_unequal_split_sizes_raises`).

@jackye1995

Copy link
Copy Markdown
Contributor Author

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

Comment on lines +641 to 649
f"split_strategy produced unequal split sizes "
f"{counts_by_split} (split id -> row count). Every split must "
"have the same row count. Use `fixed=num_splits` rather than "
"`ratios`/`counts`/weighted `split_hash`, which can produce "
"unequal sizes, or split unevenly-sized groups into separate "
"StreamingDatasets instead."
)
elif shuffle:
perm_seed = shuffle_seed + epoch * _EPOCH_PRIME

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 (optional) Users who follow the docstring and pass split_hash or split_calculated as split_strategy will nearly always get a ValueError at construction. The new exact-equal-size check at streaming.py:641 compares exact row counts per split. Hash and calculated splits assign rows by value, so their counts are almost never exactly equal, even with equal weights like [1, 1]. The docstring (streaming.py:250-252) and the error text ("weighted split_hash") still say these strategies are supported. Fix: either make the docs and error message say only exact-count strategies (fixed=num_splits) are accepted, or truncate or pad splits to the smallest size instead of raising. [also at: python/python/lancedb/streaming.py:647 - Sequence-packing users who pass a split_strategy with uneven split row counts now get a ValueError at construction, even though packed iteration handles uneven splits.]

Why this was flagged

Example: StreamingDataset(tbl, num_splits=2, split_strategy=lambda b: b.split_hash(["user_id"], [1, 1])). apply_hash assigns each row by its hash value, so split 0 and split 1 end up with close but rarely identical counts, for example 5,012 and 4,988. The check len(set(counts_by_split.values())) > 1 at streaming.py:641 then raises "split_strategy produced unequal split sizes". The docstring at streaming.py:250-252 names split_hash and split_calculated as the use case for this escape hatch, and the PR description says the parameter unblocks them. The error message suggests only weighted split_hash is the problem, but unweighted hash splits fail too. So two of the three strategies the escape hatch advertises cannot be used. Only bootstrap_sample/split_random with fixed= passes the check. The base branch had no split_strategy parameter at all, so this is a new contract that does not match its own documentation.

Verification: Trigger: a user passes split_strategy=lambda b: b.split_hash([...], [1, 1]), which is the use the docstring advertises. The new check in streaming.py requires every split to have exactly the same row count. The Hash doc in split.rs:51-54 says the weights set only "the approximate number of rows in each split". So even equal weights give counts that are almost never identical, and construction raises.

@HaochengLIU

HaochengLIU commented Oct 22, 2026 •

Copy link
Copy Markdown

@jackye1995 @westonpace Hey, if possible, can you wait for a few days before merging until I fully grasp what this PR is doing and make sure it addresses the scenario I'm facing for my firm?

"provide their own sampler"
yes, that's something we are also exploring with. Though we dont need to do everything in one PR.

@jackye1995
jackye1995 merged commit 1564ec1 into lancedb:main Oct 22, 2026
32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request Python Python SDK Rust Rust related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants