Repository navigation
convertToCyclopsData(): less memory for data frames; sparse matrix covariates - #120
Merged
Merged
Conversation
egillax
added a commit
that referenced
this pull request
Nov 20, 2026
So that #120 and #121 merge in either order without a NEWS conflict: NEWS lists #120's items as 44-45 and this branch's as 46-50. Claude-Session: https://claude.ai/code/session_01EJFmbxRwsu3excuHaQP49K
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #120 +/- ##
===========================================
+ Coverage 86.05% 86.17% +0.12%
===========================================
Files 73 73
Lines 16705 17026 +321
===========================================
+ Hits 14375 14672 +297
- Misses 2330 2354 +24 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…ough a permutation Converting data frames peaked at about 48 bytes per covariate value beyond the input (72 when the covariates came sorted by rowId), almost all of it copies: bit64::as.integer64() copies of covariateId and rowId, Rcpp copies of all three vectors into std::vector<double>, isSorted() coercing integer columns, unique() and match() vectors and hash tables as long as the covariates, and for unsorted lr/pr covariates order() plus a sorted copy of the data frame. Now: - ModelData::loadMultipleX() reads through NumberView, a read-only view of the R vector (integer, logical, integer64 or double; ids read as bit64::as.integer64() reads them, doubles outside the int64 range as NA, integer NA values as R's NA_real_), optionally through a permutation, and reserves each indicator or sparse column once for the entries it keeps. Other id types (character) and doubles that overflow int64 still go through bit64 in R, so its warning stays; values of other types go through Rcpp's conversion as before. - isSorted() reads integer columns without coercing them (R_xlen_t rows). - .runStarts() gives the distinct covariate ids of sorted covariates, .allIn() the rowId check, .sortOrder() order(covariateId, rowId) by two stable counting sorts over value ranks. Each uses a direct table for whole numbers in a moderate range and a capped hash otherwise, and returns NULL or NA where it cannot decide (unsorted, NA/NaN, integer64 keys): the old code runs. The loader checks a given order (an integer permutation of the covariates). Andromeda tables keep the database sort; their batches are read in place by the same loader. 26 million values (100,000 rows x 20,000 covariates), process peak: sorted by covariateId 1.96 GB -> 0.82 GB, sorted by rowId 2.57 GB -> 1.04 GB; Andromeda unchanged (2.43 GB lr, 3.56 GB cox). Identical ids, names, types, rows and fits against develop on 166 data-frame designs, 295 lr/pr and 676 clr/cpr/Cox-family Andromeda designs and 82 inputs named in reviews (character, NA, fractional, -1/0 and out-of-range ids; two of them crash on develop and here, the id-0 bug). On 8 real prediction tasks (Andromeda, lr and cox) the data were identical to develop's: per-column counts, sums and sums of squares against SQL, types, row order and predictions. R suite 416 tests and Python suite 171 pass. Reviewed by three Astra and three Gemini Carbon reviews and an ultrareview (with the Andromeda unsorted load, which this commit leaves out); the fixes for the in-place reads are included. Claude-Session: https://claude.ai/code/session_01EJFmbxRwsu3excuHaQP49K
…in place Studies that hold their covariates as a Matrix sparse matrix (e.g. PLP's toSparseM() output, subset by rows per fold) built a data frame of its entries to convert it. convertToCyclopsData() now takes the matrix as covariates for lr and pr models with data-frame outcomes: row r belongs to outcomes row r, column j is covariate j (named by colnames() if present). dgCMatrix, lgCMatrix and ngCMatrix are read in place (@p, @i, @x); other Matrix classes, other model types and a row count different from the outcomes' are refused with a message. Columns without entries are left out, as covariates without rows in a data frame; explicit zeros are dropped, as covariateValue 0 is. When the outcomes are not sorted by rowId the matrix rows are reordered with them. The data-frame method dispatches as before (the generic dispatches on outcomes) and checks the covariates' class first; data frames take the same code as before. In C++, ModelData::loadColumns() loads the columns through the same per-column code as loadMultipleX() (appendEntries(), factored out of it), with row ids read through the matrix's 0-based row indices (NumberView orderBase). 26 million binary values (100,000 rows x 20,000 columns), beyond the matrix: matrix 0.08 GB / 0.3 s; data frame of its entries 0.28 GB / 0.7 s (develop: 1.25 GB / 3.6 s). Tests: dgC, lgC and ngC matrices with explicit zeros, an empty column, unsorted non-contiguous rowIds and an offset give the data of the data frame of their entries, for lr and pr; colnames name the covariates; refusals. R suite 417 tests and Python suite 171 pass; the data-frame, Andromeda and review-input equivalence harnesses are still identical to develop. Claude-Session: https://claude.ai/code/session_01EJFmbxRwsu3excuHaQP49K
egillax
force-pushed
the
data-frame-memory
branch
from
November 23, 2026 08:04
0bcd099 to
a0f5677
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
This came from a study that compares many penalized logistic models on large claims data. Its pipeline works like this:
toSparseM()) and keeps that matrix in R.It computes per-fold quantities from it that Cyclops doesn't provide: per-covariate weights for its priors, starting
scales, held-out log-likelihoods at every variance tried, KKT residuals and predictions.
runs several hundred fits on them.
DuckDB and sorted again.
So the study converts by building a data frame of the matrix's entries and passing it to
convertToCyclopsData(). Atraining set holds up to about 72 million covariate values. Each analysis runs on a shared 64 GB server and peaks at
4–10 GB. Much of that is the matrix, the Cyclops datasets, and the copies made while converting. On develop, converting a data frame takes about 48 bytes per
covariate value on top of the input, mostly copies of the input. This PR removes those copies. It also lets the matrix be
passed directly, so the data frame of its entries is no longer needed either.
What it does
convertToCyclopsData()made several full copies of the covariates when converting a data frame (tointeger64, theninto C++, plus a sorted copy when the covariates were not sorted). It now reads the vectors in place and sorts through a
permutation. The resulting data are identical; only the memory and time to build them change.
It also accepts the covariates of
lrandprmodels as a sparse matrix (dgCMatrix,lgCMatrixorngCMatrix;row r belongs to outcomes row r, column j is covariate j). Studies that already hold a sparse matrix in R, for example
from PLP's
toSparseM(), no longer need to build a data frame of its entries. The data are the same as from that dataframe. The new input is an extra branch in the data-frame method, so existing calls take the same code as before.
Andromeda tables keep the database sort, and their memory is unchanged: their peak comes from DuckDB's sort, not from
this code. PLP and CohortMethod use Andromeda, so this PR doesn't change their memory; it helps code that passes data
frames or sparse matrices.
Numbers
26 million covariate values (100,000 rows × 20,000 covariates), process peak:
Sparse matrix input, 26 million binary values, memory beyond the matrix itself:
How it was checked
clr, cpr, cox, fgr, cox_counting) and 82 unusual inputs from reviews (character, NA, fractional, negative and very large
ids).
count. Column types, row order and predictions are the same as develop's.
frame of their entries.
PatientLevelPrediction (develop) tests: 3,438 expectations, 0 failures; one error in an IHT test that earlier builds
have too.
Not in this PR
Loading Andromeda covariates without the database sort (it lowers the peak further, 2.4 → 1.5 GB for lr) is still being
evaluated: on a large server it was slower than develop.
This PR was prepared with the help of an AI assistant (Claude); the changes were reviewed and tested as described above.
https://claude.ai/code/session_01EJFmbxRwsu3excuHaQP49K