Skip to content

Add cmdstan_csv_to_parquet() and read_cmdstan_parquet() for CmdStan output in Parquet files - #1342

Draft
avehtari wants to merge 14 commits into
v1.0from
csv-to-parquet
Draft

avehtari wants to merge 14 commits into
v1.0from
csv-to-parquet

Conversation

@avehtari

@avehtari avehtari commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Submission Checklist

  • Run unit tests
  • Declare copyright holder and agree to license (see below)

Summary

This PR adds cmdstan_csv_to_parquet(). The function converts the CSV files of the MCMC sampler to one Parquet file and does not read all draws into memory. The goal is that posterior can read draws from Parquet files (stan-dev/posterior#240). Users run large models on a cluster, and the draws may need more memory than a laptop has. A Parquet reader can read only the columns of the selected variables.

The PR also adds read_cmdstan_parquet() and Parquet input for as_cmdstan_fit(). read_cmdstan_parquet() gives the same result as read_cmdstan_csv(). Thus one Parquet file can replace the CSV files or a saved fit object. As in read_cmdstan_csv(), the draws (lp__ and the model variables) and the sampler diagnostics are separate elements of the result.

CmdStan writes comment lines before the header, after the warmup draws and at the end of the file. The Arrow C++ CSV reader has no option to skip comment lines, so Arrow cannot read CmdStan CSV files directly.

I based this PR on v1.0. On master, the Jarl step of the format-suggest workflow failed with 52 findings in files that this PR does not change. v1.0 has the Jarl fixes for these files.

fit <- cmdstanr_example("logistic", save_warmup = TRUE)
cmdstan_csv_to_parquet(fit$output_files(), "logistic.parquet",
                       warmup_file = "logistic_warmup.parquet")

# the same list as read_cmdstan_csv(); the draws have only beta
x <- read_cmdstan_parquet("logistic.parquet", variables = "beta",
                          warmup_file = "logistic_warmup.parquet")

# a fit object (CmdStanMCMC_Parquet)
fit2 <- as_cmdstan_fit("logistic.parquet",
                       warmup_file = "logistic_warmup.parquet")
fit2$summary()

Design of the writer

  • The only new dependency is nanoparquet (>= 0.5.0) in Suggests. nanoparquet has no package dependencies. Version 0.5.0 fixed the writing of files larger than 4 GB and of data frames with zero rows.
  • The function reads each CSV file in chunks of chunk_rows lines with readLines() and drops the comment lines. It parses each chunk with data.table::fread(text = ) and appends it to the Parquet file with nanoparquet::append_parquet().
  • The default chunk_rows is 10^7 divided by the number of columns, so a chunk has about 10 million values.
  • With keep_row_groups = TRUE, append_parquet() writes each chunk as new row groups. Without this option, append_parquet() can read the last row group back into memory and write it again with the new rows. nanoparquet splits a chunk with more rows than its num_rows_per_row_group option (10 million rows in 0.5.1, 122,880 rows in 0.5.2).
  • The columns are those of a draws_df: all CSV columns as doubles, with names in the beta[1,2] form, then .chain, .iteration and .draw. Thus posterior::as_draws_df(nanoparquet::read_parquet(file)) gives all columns in one data frame. .chain is the position of the file in files, as in read_cmdstan_csv().
  • The function writes the warmup draws to an optional second file (warmup_file), because posterior would read an extra column such as .warmup as a variable.
  • The function stores the CmdStan metadata as JSON in the key-value metadata of the Parquet file, so no separate metadata file is necessary:
    • stan.format_version = "1";
    • stan.draws = "sampling" or "warmup";
    • stan.metadata: the values that read_csv_metadata() reads and the variable dimensions. The array chains has one element per chain. Each element always has the id, the seed, the init, the step size, the adapted step size, the inverse metric and the timing. It also has each other value that differs between the chains (for example profile_file).
  • The JSON keeps the values exact. Doubles have 17 significant digits, and NaN, Inf, -Inf and NA are JSON strings. The CSV values true and false are JSON booleans. nanoparquet::read_parquet_metadata() and arrow::read_parquet(as_data_frame = FALSE)$schema$metadata read these keys.
  • The function writes to temporary files next to the output files and renames them at the end. An error does not leave a partial output file and does not change an existing output file.
  • The first commit moves the file preparation from read_cmdstan_csv() to a new helper prepare_csv_files(). The helper copies CSV files from the WSL file system to a Windows temporary directory (stage_wsl_csv_files()) and checks the files (assert_file_exists()). It also converts the WSL paths and decompresses .csv.gz and .csv.bz2 files (decompress_csv_files()). cmdstan_csv_to_parquet() uses the same helper. The behavior of read_cmdstan_csv() does not change.

Design of the reader

  • Commit 4866460e moves three steps of read_cmdstan_csv() to helpers: merge_csv_metadata() merges the per-chain metadata, select_csv_columns() selects the requested columns, and add_variable_metadata() adds the variable dimensions. read_cmdstan_parquet() rebuilds the per-chain metadata from the JSON and uses the same helpers. Thus the two readers select variables and sampler diagnostics in the same way and give the same errors.
  • read_cmdstan_parquet() reads only the selected columns, and it copies one column at a time into the draws array.
  • as_cmdstan_fit() accepts one .parquet file and an optional warmup_file. It returns a CmdStanMCMC_Parquet object, a subclass of CmdStanMCMC_CSV. CmdStanMCMC has a new private method read_output_(), which read_csv_() calls. The subclass overrides read_output_() to read from the Parquet file. The object reads further variables when you ask for them, as an object from CSV files does.
  • read_cmdstan_parquet() stops with an error in three cases:
    • the warmup file has other stan.metadata text than the post-warmup file (another run);
    • the stan.draws values show swapped files;
    • the post-warmup file is not from the MCMC sampler.
  • Without warmup_file, metadata$save_warmup stays as in the CSV files, and warmup_draws and warmup_sampler_diagnostics are NULL. The fit object then stops with an error for $draws(inc_warmup = TRUE) and $sampler_diagnostics(inc_warmup = TRUE), with a message that names warmup_file.

Limits

  • The functions support only the output of $sample(). The other methods give one draw set without chains. A later PR can add them.
  • Each append reads and writes the Parquet footer. The footer grows with the number of row groups times the number of columns. For output with many columns (for example 10^5), a large chunk_rows keeps the number of row groups small. The details section of the documentation states this.
  • If a chain has a different number of draws than the sampler arguments give, cmdstan_csv_to_parquet() warns and still writes the draws. An example is a chain that stopped early. read_cmdstan_csv() and read_cmdstan_parquet() stop with an error when the chains have different numbers of draws, so read_cmdstan_parquet() cannot read such a file.
  • The fields of metadata from read_cmdstan_parquet() can be in another order than from read_cmdstan_csv(). The values are the same.
  • For a CSV file with algorithm = fixed_param and save_warmup = true, cmdstan_csv_to_parquet() writes all rows as post-warmup draws. The fixed_param sampler of CmdStan writes no warmup draws. cmdstanr sets save_warmup = FALSE for fixed_param, but CmdStan accepts fixed_param with save_warmup=1. With CmdStan 2.40.0, num_warmup=10 num_samples=5 save_warmup=1 algorithm=fixed_param writes 5 rows. read_cmdstan_csv() does not check for this case and takes the first rows as warmup draws. Read no warmup draws from fixed_param CSV files #1343 fixes read_cmdstan_csv() for this case.

Tests

The new file tests/testthat/test-parquet.R has 194 expectations. The tests of the writer compare the Parquet draws, sampler diagnostics and warmup draws with $draws(), $sampler_diagnostics() and $draws(inc_warmup = TRUE). These tests use thin = 3 and chunks of 7 lines, so that some chunks contain comment lines. Other tests of the writer check:

  • chunk_rows = 1;
  • the metadata, with a diagonal and a dense inverse metric;
  • compressed CSV files: gzip files that R writes, and bzip2 files from $sample(compress = "bzip2");
  • tuple and complex variables;
  • fits without draws (iter_sampling = 0);
  • fixed_param;
  • a chain with missing draws;
  • malformed lines;
  • CSV files with different headers;
  • the argument checks.

The tests of the reader compare read_cmdstan_parquet() with read_cmdstan_csv():

  • all columns, selected variables and sampler diagnostics, and format = "draws_df";
  • dense and diagonal inverse metrics, also for a model with one parameter;
  • tuple and complex variables, fixed_param, and an init file;
  • a nan in the inverse metric.

Another test writes the metadata of read_csv_metadata() to JSON and reads it back. The test expects identical values, also for 1/3, pi, NaN and Inf, and for a field that differs between the chains.

The tests of the fit object compare as_cmdstan_fit() of the Parquet file with the original fit: draws, warmup draws, sampler diagnostics, inverse metric and summary. They check the time and the metadata against as_cmdstan_fit() of the CSV files. They also check the error without the warmup file, and a variable that the object reads later, also after saveRDS() and readRDS(). Other tests check the errors of read_cmdstan_parquet() for a swapped warmup file and for a warmup file from another run.

I ran the tests at commit c2a8eabe (cmdstanr 0.99.0) on my Linux workstation with R 4.6.2, CmdStan 2.40.0, nanoparquet 0.5.1 and testthat 3.3.2. I did not test nanoparquet 0.5.2.

file expectations failed skipped
test-parquet.R 194 0 0
test-csv.R 515 0 2 (WSL only)
test-fit-mcmc.R 144 0 0
test-fit-shared.R 396 0 0

With Air 0.12.0 and Jarl 0.7.1 (the versions of the format-suggest workflow), Air makes no changes and Jarl reports no findings.

test-csv.R, test-fit-mcmc.R and test-fit-shared.R cover the moved code of read_cmdstan_csv() and the new read_output_() method. I did not edit NEWS.md. Please add an item if you want one.

Next step in posterior

With this file layout, posterior can add a reader that needs only nanoparquet. The reader can:

  1. get the column names from the Parquet schema;
  2. select the columns of the requested variables with posterior's variable matching;
  3. read these columns together with .chain, .iteration and .draw.

Lazy queries with arrow or duckdb can use the same files.

Copyright and Licensing

Please list the copyright holder for the work you are submitting
(this will be you or your assignee, such as a university or company):
Aalto University

By submitting this pull request, the copyright holder is agreeing to
license the submitted work under the following licenses:

This PR was assisted by Claude

@avehtari
avehtari requested a review from n-kall November 17, 2026 09:50
@avehtari
avehtari marked this pull request as draft November 17, 2026 09:50
@avehtari avehtari added the I/O label Nov 17, 2026
@avehtari

Copy link
Copy Markdown
Member Author

I made this to be a draft as there may be need for further design discussion, but I think it's easier to test as cmdstanr branch and we can discuss here

@n-kall

n-kall commented Nov 17, 2026

Copy link
Copy Markdown

I didn't know about nanoparquet, that could be a nice way of adding this functionality. I experimented with duckdb for both writing the parquet and the reading in the draws. See https://github.com/n-kall/lazydraws

Also, should this branch be based on the v1.0 branch?

@avehtari

Copy link
Copy Markdown
Member Author

wait a sec, I'm rebasing this to v1.0

@codecov-commenter

codecov-commenter commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.44195% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.30%. Comparing base (a3a8e50) to head (c2a8eab).
⚠️ Report is 3 commits behind head on v1.0.

Files with missing lines Patch % Lines
R/parquet.R 95.47% 18 Missing ⚠️
R/csv.R 99.23% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             v1.0    #1342      +/-   ##
==========================================
- Coverage   94.00%   93.30%   -0.71%     
==========================================
  Files          19       20       +1     
  Lines        9232     7782    -1450     
==========================================
- Hits         8679     7261    -1418     
+ Misses        553      521      -32     

☔ 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.

@avehtari
avehtari changed the base branch from master to v1.0 November 17, 2026 10:54
@n-kall

n-kall commented Nov 17, 2026

Copy link
Copy Markdown

This seems to work well. Reading the resulting parquet with lazydraws works.
However, the parquet combines both the fit$draws() and the fit$sampler_diagnostics() into one data frame.
This is fine, but maybe there can be a separation of these.

@avehtari

Copy link
Copy Markdown
Member Author

Options for handling sampler diagnostics

A) Add read_cmdstan_parquet(file, variables = NULL, sampler_diagnostics = NULL, warmup_file = NULL), which returns the same structure as read_cmdstan_csv(): post_warmup_draws, post_warmup_sampler_diagnostics, the warmup equivalents, and metadata. It reads only the requested columns with col_select.

  • One file keeps .chain, .iteration and the metadata in one place.
  • Parquet is a column format, so reading only the diagnostics costs nothing extra.
  • The reader would use only nanoparquet, as the writer does.
  • posterior could use the same split in its later reader.

B) The diagnostics go to their own files, so as_draws_df(read_parquet(file)) gives exactly $draws(). But with warmup, one fit becomes 4 files, and each file needs its own copy of .chain, .iteration, .draw and the metadata.

Which one would you prefer?

@n-kall

n-kall commented Nov 17, 2026

Copy link
Copy Markdown

I think there should be a read_cmdstan_parquet method, so the object can be reconstructed as can be done with csv. This would be simple enough for many use cases and would allow a single parquet to be moved around rather than a binary RDS or several csv files.

@avehtari avehtari changed the title Add cmdstan_csv_to_parquet() to convert CmdStan CSV files to Parquet Add cmdstan_csv_to_parquet() and read_cmdstan_parquet() for CmdStan output in Parquet files Nov 17, 2026
@avehtari

Copy link
Copy Markdown
Member Author

In addition to read_cmdstan_parquet(), as_cmdstan_fit() now supports parquet files.

fit <- cmdstanr_example("logistic", save_warmup = TRUE)
cmdstan_csv_to_parquet(fit$output_files(), "logistic.parquet",
                       warmup_file = "logistic_warmup.parquet")

# the same list as read_cmdstan_csv(); the draws have only beta
x <- read_cmdstan_parquet("logistic.parquet", variables = "beta",
                          warmup_file = "logistic_warmup.parquet")

# a fit object (CmdStanMCMC_Parquet)
fit2 <- as_cmdstan_fit("logistic.parquet",
                       warmup_file = "logistic_warmup.parquet")
fit2$summary()

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants