Repository navigation
Conversation
|
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 |
|
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? |
|
wait a sec, I'm rebasing this to v1.0 |
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
5f67d17 to
ec4e8cb
Compare
|
This seems to work well. Reading the resulting parquet with lazydraws works. |
|
Options for handling sampler diagnostics A) Add
B) The diagnostics go to their own files, so Which one would you prefer? |
|
I think there should be a |
|
In addition to |
Submission Checklist
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 foras_cmdstan_fit().read_cmdstan_parquet()gives the same result asread_cmdstan_csv(). Thus one Parquet file can replace the CSV files or a saved fit object. As inread_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. Onmaster, the Jarl step of theformat-suggestworkflow failed with 52 findings in files that this PR does not change.v1.0has the Jarl fixes for these files.Design of the writer
chunk_rowslines withreadLines()and drops the comment lines. It parses each chunk withdata.table::fread(text = )and appends it to the Parquet file withnanoparquet::append_parquet().chunk_rowsis 10^7 divided by the number of columns, so a chunk has about 10 million values.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 itsnum_rows_per_row_groupoption (10 million rows in 0.5.1, 122,880 rows in 0.5.2).draws_df: all CSV columns as doubles, with names in thebeta[1,2]form, then.chain,.iterationand.draw. Thusposterior::as_draws_df(nanoparquet::read_parquet(file))gives all columns in one data frame..chainis the position of the file infiles, as inread_cmdstan_csv().warmup_file), because posterior would read an extra column such as.warmupas a variable.stan.format_version="1";stan.draws="sampling"or"warmup";stan.metadata: the values thatread_csv_metadata()reads and the variable dimensions. The arraychainshas 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 exampleprofile_file).NaN,Inf,-InfandNAare JSON strings. The CSV valuestrueandfalseare JSON booleans.nanoparquet::read_parquet_metadata()andarrow::read_parquet(as_data_frame = FALSE)$schema$metadataread these keys.read_cmdstan_csv()to a new helperprepare_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.gzand.csv.bz2files (decompress_csv_files()).cmdstan_csv_to_parquet()uses the same helper. The behavior ofread_cmdstan_csv()does not change.Design of the reader
4866460emoves three steps ofread_cmdstan_csv()to helpers:merge_csv_metadata()merges the per-chain metadata,select_csv_columns()selects the requested columns, andadd_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.parquetfile and an optionalwarmup_file. It returns aCmdStanMCMC_Parquetobject, a subclass ofCmdStanMCMC_CSV.CmdStanMCMChas a new private methodread_output_(), whichread_csv_()calls. The subclass overridesread_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:stan.metadatatext than the post-warmup file (another run);stan.drawsvalues show swapped files;warmup_file,metadata$save_warmupstays as in the CSV files, andwarmup_drawsandwarmup_sampler_diagnosticsareNULL. The fit object then stops with an error for$draws(inc_warmup = TRUE)and$sampler_diagnostics(inc_warmup = TRUE), with a message that nameswarmup_file.Limits
$sample(). The other methods give one draw set without chains. A later PR can add them.chunk_rowskeeps the number of row groups small. The details section of the documentation states this.cmdstan_csv_to_parquet()warns and still writes the draws. An example is a chain that stopped early.read_cmdstan_csv()andread_cmdstan_parquet()stop with an error when the chains have different numbers of draws, soread_cmdstan_parquet()cannot read such a file.metadatafromread_cmdstan_parquet()can be in another order than fromread_cmdstan_csv(). The values are the same.algorithm = fixed_paramandsave_warmup = true,cmdstan_csv_to_parquet()writes all rows as post-warmup draws. The fixed_param sampler of CmdStan writes no warmup draws. cmdstanr setssave_warmup = FALSEfor fixed_param, but CmdStan accepts fixed_param withsave_warmup=1. With CmdStan 2.40.0,num_warmup=10 num_samples=5 save_warmup=1 algorithm=fixed_paramwrites 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 fixesread_cmdstan_csv()for this case.Tests
The new file
tests/testthat/test-parquet.Rhas 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 usethin = 3and chunks of 7 lines, so that some chunks contain comment lines. Other tests of the writer check:chunk_rows = 1;$sample(compress = "bzip2");iter_sampling = 0);The tests of the reader compare
read_cmdstan_parquet()withread_cmdstan_csv():format = "draws_df";nanin 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,NaNandInf, 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 againstas_cmdstan_fit()of the CSV files. They also check the error without the warmup file, and a variable that the object reads later, also aftersaveRDS()andreadRDS(). Other tests check the errors ofread_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.test-parquet.Rtest-csv.Rtest-fit-mcmc.Rtest-fit-shared.RWith Air 0.12.0 and Jarl 0.7.1 (the versions of the
format-suggestworkflow), Air makes no changes and Jarl reports no findings.test-csv.R,test-fit-mcmc.Randtest-fit-shared.Rcover the moved code ofread_cmdstan_csv()and the newread_output_()method. I did not editNEWS.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:
.chain,.iterationand.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