Skip to content

Bound the window-cache build to the memory available — Closes #32 - #36

Open
conradbzura wants to merge 3 commits into
mainfrom
32-bounded-cache-build
Open

conradbzura wants to merge 3 commits into
mainfrom
32-bounded-cache-build

Conversation

@conradbzura

@conradbzura conradbzura commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Build the window cache within a memory budget, writing it to disk as it is built, so the build no longer holds every contig's sites beside the finished arrays. The grouping runs in two passes: it reads the channels and spills ordered runs of sites to a scratch directory beside the result, then lays out offsets from the counts and fills pos, val and chan through a mapping, a block of windows at a time. bigWig channels are read in groups of 32, each group's readers made for it and let go before the next. The entry's bytes are unchanged: a test pinning the digests recorded from main passes at the default budget and at one byte, a Hypothesis test holds the arrays identical to the default's at any budget up to 1 MB, and a 64-channel synthetic entry built in Docker from this head is byte-identical to main's.

Under --memory=8g --memory-swap=8g --cpus=8, with the mapped residency, 1,024 sparse channels now build and drain. The build's peak anonymous memory climbs with the channels until it reaches the process baseline plus the budget, 2.80 GiB, and holds there from 512 channels to 1,024; main was OOM-killed at 512. That is how this reads criterion #1's "flat, within a fixed margin": the peak is bounded by the baseline plus the budget at every channel count, and flat once the grouping fills the budget. It is met for the mapped residency only: the default residency, memory under fork, is killed at 1,024 channels while loading the finished 8.1 GB cache, which choosing the residency from the budget (#35) addresses. The trade is build time, from the spill pass.

Closes #32

Proposed changes

Two-pass grouping within a budget (quadrat.cache)

  • The budget. group_track, WindowSignalCache.build and window_cache take a keyword-only budget: a positive integer of bytes, or None for half of quadrat.pileup.plan.memory_budget(), or half of 4 GiB where that reads nothing. Three things are fitted to it (_build_sizes):
    • the bigWig channels read at once, as many as half the budget holds of their read buffers, up to 8 and the cores this process may use;
    • the sites a run is flushed at, half of what those reads leave or of a quarter of the budget where they leave less, so never below an eighth of the budget, at 42 bytes a site;
    • the sites a block is sized to, the whole budget at 42 bytes a site.
  • What it does not count is written in group_track's docstring: one channel's sites on one contig, read whole, of which as many as channels read at once plus one are held; a channel of coverage deltas' whole contig of delta rows; the first join of channels of counts on a contig, which overlapping windows can make larger than a run, and the join engine's own buffers; one window's sites over every channel, the least a block takes; a group's readers' data indexes; and the spill and result where the scratch directory is a tmpfs.
  • The first pass (_Spill, _spill_tracks, _spill_bigwigs).
    • Every site of a channel on a contig goes into one run, ordered by _site_order, at the widths the result keeps.
    • A run's offsets, values and channels are appended to three files, and its cumulative counts per window to a fourth, so the window index is never spilled.
    • Channels of counts still share one join per contig wherever their sites fit a run.
    • A bigWig group's reads cover every (contig, channel) pair, taken as they finish (_bigwig_channel_reads); a contig is flushed once its last channel is in.
  • The second pass (_Spill.merge).
    • pos, val and chan are reserved at full length (posix_fallocate, or zeros written from one 1 MiB buffer), so a full disk is an OSError rather than a SIGBUS, then mapped.
    • A block is consecutive windows of one contig, sized from the exact counts and gathered from every run on it, stable-sorted on the packed key and scattered to its slots. A block drawn from one run is already in order and is written as it is.
    • Sites that tie on (window, offset, channel) are of one channel, so they come from one run already ordered by value, and the stable sort keeps that order: the arrays are those one sort over the contig makes.
  • Every grouping goes through _group_into, on tracks opened and verified up front by _open_frames, which holds a bigWig as its path until its group.

Callers

  • group_track(..., *, scratch_dir=None, budget=None) keeps its contract. It groups into a scratch directory, loads the four arrays one at a time, unlinking each, and removes the directory.
  • WindowSignalCache.build(..., *, budget=None) groups a mapped cache straight into its scratch directory, which _owned_scratch_dir makes (the reap-at-exit logic factored out of from_arrays), and holds a memory cache as group_track answers it.
  • window_cache(..., *, verbose=False, budget=None):
    • checks its arguments, the budget included, before the read, and opens every kind's tracks before anything is staged;
    • groups straight into the staged entry, commits it through _commit_entry (which write_window_cache shares), and reads it back in the resolved residency, so a memory build loads the committed arrays once;
    • where the staged entry cannot be written, groups again into a scratch directory; a track that cannot be read removes the staging and propagates;
    • when verbose, prints a line per grouping: the budget, the bigWig channels read at once and their groups, the runs and the sites a run is flushed at, the MiB spilled, and the blocks and the sites a block is sized to.
  • A write fault keeps its type. Only _commit_entry tells a write from a track fault; a build that persists nothing raises what the write raised, a PermissionError as one.
  • window_group_sums reads bigWig channels in the same groups, every contig of a group in one stream, and adds a group's totals per window in channel order once the group is in, so each window takes its bigWig channels in channel order and then its other channels, as on main, and its float64 totals do not change.
  • build_training_loader passes verbose to window_cache.
  • stores.BIGWIG_CHUNK_BYTES loses its underscore, since quadrat.cache sizes a read from it.

Docs

group_track's docstring states what a grouping fits to its budget and what it does not, the two passes, the cost of ordering a site (_ORDERING_BYTES_PER_SITE, 42 bytes) and the 10 bytes a site of scratch disk. window_cache documents the fallback's cost, that a keyed build spills inside its staged entry, and that residency and budget are checked on every call, a hit included; window_group_sums states what its reads hold and the fixed order each window's totals are added in, its bigWig channels in channel order and then its other channels, as on main; extract_signal and extract_loci document the scratch directory a grouping needs.

Docker acceptance

Synthetic data: 30,000 peaks and 30,000 negatives, sparse bigWig channels plus 4 controls, --memory=8g --memory-swap=8g --cpus=8, workers 0, one epoch drained. Build peak anonymous memory in GiB; the branch column is this head, and main is unchanged since it was measured:

Channels main default main mapped branch mapped Cache Drain (batches/s)
64 2.54 2.66 1.36 0.58 GB 9.2
128 3.93 4.01 1.69 1.10 GB 17.3
256 6.96 6.83 2.24 2.04 GB 5.7
512 OOM OOM 2.80 4.08 GB 4.4
1,024 not run not run 2.80 8.15 GB 1.4
  • The budget there resolves to 1.89 GiB. At 64 channels the signals report "bigWig channels read 6 at a time in 2 groups, 16 runs flushed at 13,341,881 sites (553.7 MiB spilled), merged in 8 blocks sized to 48,254,468 sites", measured before the line's wording changed from "of up to" to what the figures are.
  • Default residency. Measured at an earlier head of this branch, whose grouping peaked the same: the build phase includes loading the finished cache into memory, so its peak is the cache plus about 1.3 GiB, and at 1,024 channels it is killed loading the cache (Choose the cache's residency from the memory budget, and let callers set the budget #35).
  • Dense. Measured at an earlier head: at 8 channels, which main OOM-killed, both residencies finish; at 16, mapped builds a 14.4 GB cache at 3.43 GiB and default is killed loading it. 32 and 64 were not run, since their entries and spill would fill the Docker VM's disk.
  • Build time. At an earlier head, mapped under a 12 GiB cap, two alternated runs each: 64 channels 13.2–19.5 s against main's 11.0–16.4 s, and 256 channels 37.4–41.8 s against 27.7–28.1 s, with mean build cores falling from 3.5 to 2.5. At this head, one run each with the host short of memory: 12.8 s at 64 channels and 53.4 s at 256. The pool stalling while a run flushes is recorded as a follow-up.

Test cases

# Test Suite Given When Then Coverage Target
1 window_cache A channel of counts, one recording positions twice, coverage deltas and a bigWig, as signals and reversed as controls The entry is built at the default budget and at one byte Its eight array files and its record hash to the pinned digests, recorded from main, and nothing else is left Byte identity
2 group_track Any budget up to 1 MB and any non-empty selection of those channels in any order Grouped at that budget and the default The arrays are identical (Hypothesis) Budget independence over any subset and order of channels
3 group_track A named scratch directory A grouping is run there It is left empty scratch_dir cleanup
4 group_track A bigWig with a zeroed data block and a named scratch directory Grouped there ValueError naming it, and the directory left empty Cleanup of a grouping held in memory
5 group_track A scratch directory named under a regular file A grouping is asked for OSError scratch_dir is the one used
6 group_track 33 bigWig channels and the counts tracks of their values, on a pinned machine of 16 cores, the first channel's reads finishing last Each set is grouped The arrays are identical Several reads at once, taken as they finish, across reader groups
7 group_track A budget that is not an integer, or below one A grouping is asked for TypeError or ValueError Budget refusal
8 group_track The bigWig channel alone Grouped at the default budget and within one byte The arrays are identical A block a contig and a block a window
9 window_group_sums 33 bigWig channels and the counts tracks of their values Totalled in groups of one and of all Equal totals Reader groups in totals
10 window_group_sums 33 bigWigs whose last three hold 1e16, -1e16 and 1 at one base Totalled as one group 1 Channel order across a group of readers
11 window_group_sums A counts channel holding 1, then bigWigs holding 1e16 and -1e16, at one base Totalled as one group 1 bigWig channels added before the others
12 WindowSignalCache.build A channel of each kind, in either residency Built within one byte and within the default Every window draws the same Budget independence through build
13 WindowSignalCache.build A channel of each kind and a named scratch directory Built mapped, and in memory Equal draws; the scratch holds only the mapped cache, holding only the four arrays Mapped build straight into scratch
14 WindowSignalCache.build A disk refusing the arrays' blocks with ENOSPC, or with EACCES Built OSError carrying ENOSPC and nothing left; PermissionError itself in either residency, and nothing left Write faults
15 WindowSignalCache.build A channel of each kind and a one-byte budget Built mapped Exactly the four files write_cache_arrays writes, with array_meta's counts Mapped build straight to disk
16 WindowSignalCache.build No os.posix_fallocate Built mapped within one byte The same files The zero-fill reservation
17 WindowSignalCache.build No os.posix_fallocate, and a disk refusing the zeros Built mapped OSError carrying ENOSPC, the refusal made, nothing left A full disk without posix_fallocate
18 WindowSignalCache.build Windows on a contig no track holds Built mapped Zero offsets and empty pos, val and chan, readable mapped or loaded Zero-length output
19 WindowSignalCache.build A bigWig with a zeroed data block Built mapped ValueError naming it, and an empty scratch directory Cleanup on a track fault
20 WindowSignalCache.build 33 bigWig channels and a record of the readers made and alive Built mapped A reader made for every file, and fewer readers than channels ever alive Readers per group
21 WindowSignalCache.build Sparse bigWigs, 8 of whose spilled sites exceed a 1 MiB budget and 32 of whose hold about four times as many Built over each within that budget, their Python and numpy allocations traced Both traced peaks under twice the budget The build follows its budget
22 window_cache No key, a one-byte budget, the mapped residency Built with controls Draws equal a keyed build's, and the scratch holds only the two caches The scratch path
23 window_cache A key, a disk refusing the arrays' blocks or the tables once Built with controls Caches in the scratch directory given, drawing what an unpersisted build draws, and no entry or staging The write fallback
24 window_cache A key, a disk refusing the spill inside the staged entry once Built A cache in the scratch directory given, drawing the same, and no entry or staging The fallback from the first pass
25 window_cache A key and verbose Built, then hit A signal and a control line from the build, nothing from the hit verbose
26 window_cache A one-byte budget and verbose Built The report gives a budget of 1 byte, one channel at a time in one group, runs flushed at and blocks sized to one site, more than one of each, and spilled bytes The report at the floor
27 window_cache 33 bigWigs, any budget up to 4 GiB and any cores up to 16 Built with verbose The channels at once, the run size and the block size are those group_track states (Hypothesis) The sizes for any budget
28 window_cache A pinned machine with an 8 GiB cgroup, and no budget Built with verbose The report gives half of memory_budget() The default budget
29 window_cache A machine whose memory cannot be read, and no budget Built with verbose The report gives 2.00 GiB The fallback budget
30 window_cache No bigWig channel and verbose Built The report says nothing of bigWig channels The report without bigWigs
31 window_cache 33 bigWig channels and verbose Built The report counts more than one group Groups reported
32 window_cache A numpy-integer budget and the same as an int Built mapped with verbose The same arrays and the same report Numpy budgets
33 window_cache An entry on disk Asked for with a budget of 2.5 or 0 TypeError or ValueError Budget checked on a hit
34 window_cache A corrupt bigWig signal and a key Asked for ValueError, with no entry or staging left Track faults propagate
35 window_cache A missing control and a key Asked for FileNotFoundError, and no cache directory made Tracks opened before staging
36 window_cache A key and the memory residency Built, then hit Each array loaded once from the entry, held in memory A memory build reads its entry once (rewritten from the earlier "no read-back" test)
37 build_training_loader verbose and an empty cache directory Built cold, then from the entry The grouping line from the cold build only The loader passes verbose
38 builders Three bigWigs written with an unreadable block The second and the others are read Only the second fails The test builder

@conradbzura conradbzura self-assigned this Dec 3, 2026
@conradbzura
conradbzura force-pushed the 32-bounded-cache-build branch 4 times, most recently from f61f6bb to fbe1b88 Compare December 4, 2026 00:33
Records the sha256 of all eight array files and of the record of an
entry built from a channel of counts, one recording positions twice,
one of coverage deltas and a bigWig, as signals and reversed as
controls, over overlapping windows of two widths. The digests were
taken from the current build, so a rewrite of how the entry is built
has to write the same bytes.
The build held every contig's ordered sites until the last contig was
grouped and allocated the result beside them, so its peak followed the
whole cache: about 2.8 bytes per byte of entry on top of the bigWig
read buffers, and every bigWig reader was held for the whole build.
Under an 8 GiB cgroup cap the build was killed at 512 sparse channels
while draining the finished cache needed under 1.6 GiB.

group_into now groups in two passes, fitted to a budget that defaults
to half of what quadrat.pileup.plan.memory_budget reads. The first
reads the channels and spills runs of ordered sites to a scratch
directory beside the result. bigWig channels are taken 32 to a group,
each group's readers made for it and let go after, its reads running
across every contig as they finish, as many at once as half the
budget holds of their read buffers and the cores allow. The second
lays out offsets from the sites counted per window and fills pos, val
and chan through a mapping whose blocks are allocated first, a block of
windows at a time. Runs and blocks are sized at the cost a site was
measured to have while it is put in order, and whoever hands sites on
lets go of them first. Sites sharing a window, offset and channel are
of one run, already ordered by value, and a stable sort keeps them so,
so the arrays are byte for byte what one sort over each contig made.
group_into reports how it split the work as a GroupingReport.

window_cache opens every track before it stages anything, groups
straight into the staged entry through the one staging and commit path
write_window_cache now shares, and reads the build back in the
residency it resolves to, so a memory build holds one copy rather than
two. Only a failed write to the entry is retried in a scratch
directory; a track that cannot be read raises once. window_cache and
WindowSignalCache.build take budget, and window_cache verbose, to print
how each grouping was split. window_group_sums reads bigWig channels in
the same groups. BIGWIG_CHUNK_BYTES loses its underscore, since the
build's sizing now reads it.
build_training_loader passes verbose to window_cache, so a cold build
prints the budget each grouping was sized to and how many runs, reader
groups and blocks it took, beside the loci it kept.
@conradbzura
conradbzura force-pushed the 32-bounded-cache-build branch from fbe1b88 to f91438e Compare December 4, 2026 01:03
@conradbzura
conradbzura marked this pull request as ready for review December 4, 2026 01:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bound the window-cache build to the memory available

1 participant