Repository navigation
feat: add Bootstrap split strategy for sampling with replacement - #4597
Conversation
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).
westonpace
left a comment
There was a problem hiding this comment.
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.
|
@claude review |
There was a problem hiding this comment.
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 combinebootstrap_samplewith.shuffle()on a large filtered table get a failedexecute(). The shuffler is still told the input row count rather thannum_samples. builder.rs:317 passesnum_rows, the filteredcount_rows. Bootstrap's splitter now outputsnum_samplesrows instead. Oncenum_rowsreachesmax_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_samplesfor Bootstrap andnum_rowsfor every other strategy.Why this was flagged
Trigger:
permutation_builder(tbl).bootstrap_sample(N, fixed=k).shuffle(seed=..)(or the same chain inside aStreamingDataset(split_strategy=...)callable). The filtered table has at least 1010241024 rows and N > num_rows. builder.rs:293 setsnum_rowsfromcount_rows(filter). builder.rs:317 then callsshuffler.shuffle(split_data, num_rows). Butapply_bootstrap(split.rs) emitsnum_samplesrows. shuffle.rs:286 takes thedo_shufflepath becausenum_rows >= max_rows_per_file. shuffle.rs:172 then fails withExpected {} rows but saw {} rows. When N < num_rows, theis_lastcheck at shuffle.rs:171 never matches the real stream end. On the base branch every split strategy outputs exactlynum_rowsrows, 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 andnum_samplesis larger than that count. builder.rs callsshuffler.shuffle(split_data, num_rows), butapply_bootstrap(split.rs) emits aboutnum_samplesrows. shuffle.rs then takesdo_shuffle, which fails with "Expected {} rows but saw {} rows". Before this PR, every strategy produced exactlynum_rowsrows.
| /// exactly the with-replacement behavior the name promises, not an even round-robin. | ||
| Bootstrap { | ||
| num_samples: u64, | ||
| sizes: SplitSizes, | ||
| seed: Option<u64>, | ||
| }, |
There was a problem hiding this comment.
🟡 (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).
|
Addressed in 83eb3e6:
New test coverage for each: |
|
@claude review |
- 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()).
|
Both caught regressions fixed in 5aed1b9:
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. |
|
@claude review |
…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.
|
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`). |
|
@claude review |
| 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 |
There was a problem hiding this comment.
🟡 (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.
|
@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" |
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::Bootstrapadds exactly this to the data loader: sample rows uniformly with replacement from the (optionally filtered) base table, independently per split.Main use cases
num_samplesdirectly instead of it being implicitlylen(dataset).Example (an actual run, not a hypothetical one)
A 5-row base table (
row_id0..4), sampled viaBootstrap { num_samples: 8, sizes: Fixed(2), seed: Some(42) }: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 newPermutationBuilderRust method was needed:with_split_strategyalready accepts anySplitStrategyvalue generically. Python binding:PermutationBuilder.bootstrap_sample(num_samples, *, ratios=None, counts=None, fixed=None, seed=None, split_names=None), mirroringsplit_random's existing shape.Also adds a generic
split_strategyparameter toStreamingDataset's constructor (a callable taking/returning aPermutationBuilder), since it previously could only reachsplit_random/split_sequentialeven thoughsplit_hash/split_calculatedalready shipped. This unblocksBootstrapand any future strategy without further constructor changes.