Skip to content

convertToCyclopsData(): less memory for data frames; sparse matrix covariates - #120

Merged
msuchard merged 2 commits into
developfrom
data-frame-memory
Nov 25, 2026
Merged

msuchard merged 2 commits into
developfrom
data-frame-memory

Conversation

@egillax

@egillax egillax commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Why

This came from a study that compares many penalized logistic models on large claims data. Its pipeline works like this:

  • It takes the covariates out of FeatureExtraction/PLP as a sparse matrix (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.
  • From that matrix it builds 4 Cyclops datasets per training set (3 cross-validation fold subsets plus the full set) and
    runs several hundred fits on them.
  • Andromeda doesn't fit this pipeline: the data are already in R, and each subset would have to be written back to
    DuckDB and sorted again.

So the study converts by building a data frame of the matrix's entries and passing it to convertToCyclopsData(). A
training 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 (to integer64, then
into 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 lr and pr models as a sparse matrix (dgCMatrix, lgCMatrix or ngCMatrix;
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 data
frame. 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:

input develop this PR
data frame sorted by covariateId 1.96 GB 0.82 GB
data frame sorted by rowId 2.57 GB 1.04 GB
Andromeda lr / cox 2.43 / 3.56 GB unchanged

Sparse matrix input, 26 million binary values, memory beyond the matrix itself:

route memory time
data frame of the entries, develop 1.25 GB 3.6 s
data frame of the entries, this PR 0.28 GB 0.7 s
the matrix directly, this PR 0.08 GB 0.3 s

How it was checked

  • Same ids, names, column types, rows and fits as develop on 166 data-frame designs, 971 Andromeda designs (lr, pr,
    clr, cpr, cox, fgr, cox_counting) and 82 unusual inputs from reviews (character, NA, fractional, negative and very large
    ids).
  • 8 real prediction tasks (Andromeda, lr and cox): the per-column counts, sums and sums of squares match a direct SQL
    count. Column types, row order and predictions are the same as develop's.
  • Sparse matrices of each class, with explicit zeros, empty columns and unsorted row ids, give the data of the data
    frame of their entries.
  • R tests 417 pass, Python tests 171 pass, R CMD check OK.
  • CohortMethod 6.0.3 tests: same results as on develop (646 expectations; one failure that develop has too).
    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

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

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.67358% with 36 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.17%. Comparing base (1b6318d) to head (a0f5677).

Files with missing lines Patch % Lines
src/RcppIsSorted.cpp 91.85% 11 Missing ⚠️
src/RcppModelData.cpp 84.74% 9 Missing ⚠️
src/cyclops/ModelData.h 77.77% 6 Missing ⚠️
src/cyclops/ModelData.cpp 94.80% 4 Missing ⚠️
R/NewDataConversion.R 93.75% 3 Missing ⚠️
src/IsSorted.cpp 93.10% 2 Missing ⚠️
R/DataManagement.R 90.90% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…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
@msuchard
msuchard merged commit 116c5fb into develop Nov 25, 2026
26 checks passed
@msuchard
msuchard deleted the data-frame-memory branch November 25, 2026 00:23
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.

2 participants