Skip to content

Fix/json reader - #3438

Open
SteveBronder wants to merge 20 commits into
developfrom
fix/json-reader
Open

SteveBronder wants to merge 20 commits into
developfrom
fix/json-reader

Conversation

@SteveBronder

Copy link
Copy Markdown
Collaborator

Submission Checklist

  • Run unit tests: ./runTests.py src/test/unit
  • Run cpplint: make cpplint
  • Declare copyright holder and open-source license: see below

Summary

Fixes json_data::vals_c for complex values inside arrays of tuples, and adds stan/io/read_from_context.hpp for reading a named variable out of a var_context into an already sized destination.

vals_c paired components across the whole flat buffer, using the product of all but the last dimension as the offset. That is only correct when the variable has no enclosing array. For

{"x": [{"1": [[1, 2], [3, 4]]}, {"1": [[5, 6], [7, 8]]}]}

x.1 has dims {2, 2, 2} and values {1, 3, 2, 4, 5, 7, 6, 8}. The old offset of 4 gave (1,5) (3,7) (2,6) (4,8). Components are paired within each innermost block, so the answer is (1,2) (3,4) (5,6) (7,8).

dims alone cannot say how many leading dimensions are enclosing arrays, so var_entry records num_outer_arrays at the point the handler concatenates the dims, and vals_c uses it for the block size. Nonempty data with no trailing dimension of 2 now throws instead of returning half a result.

read_from_context is two overloads split on whether the destination has a std::tuple in it. Without one, the variable is a single name and a single buffer. With one, every tuple slot is a separate name, so it reads one name per leaf of the tuple skeleton and fills that slot of every array element off a shared cursor. Supports int, double, complex, Eigen vectors/row vectors/matrices, and any std::vector/std::tuple nesting of those.

The io for the array of tuples / complex types is a monster so I included an example at the top of that doc describing how the io for those nested types passes through the functions recursively.

Intended Effect

read_from_context is new and not called anywhere yet. It is meant for the compiler to use for reading data.

read_from_context assumes the data structure it is filling in is already

How to Verify

python3 ./runTests.py ./src/test/unit/io/read_from_context_test.cpp
python3 ./runTests.py ./src/test/unit/io/json/

Side Effects

names_r and names_i use a boost flat map instead of std::map since they did not need to be sorted. The json var maps changed from std::map to boost::unordered_flat_map.

json_handler::key and json_handler::string take std::string_viewing&, so anything subclassing json_handler outside this repo needs updating.

Documentation

Doxygen on both read_from_context overloads. File comment walks a worked example of the name tree and the slot traversal.

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): Simons Foundation

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

Replace the array_block_sizes() accessor and its parallel side map with a
field on the per-variable record.

The JSON format erases where the enclosing array-of-tuples dimensions stop
and a leaf variable's own dimensions begin, so that split has to be stored.
var_entry::num_outer_dims records it, set once in update_array_dims() at the
point the two are concatenated. block_size() and the leaf shape derive from
it. This drops the boost unordered_flat_map dependency, the public accessor,
and the remove() sync line.

Other cleanups in the same area:

- json_data::validate_dims delegates to stan::io::validate_dims, as every
  other var_context subclass already does; only the JSON '[]'-ambiguity
  guard stays local
- document the mixed array-of-tuples layout on the json_data class, which
  claimed column-major with no carve-out
- vals_c rejects a trailing 2 that belongs to an enclosing array rather than
  to the variable itself, which is what the old block_size == 0 test meant
- rename var_value to var_entry and num_elements to size_from_dims, both of
  which collided with differently-behaving names in stan::math
- replace per-element map lookups in the append path with a single lookup
  and a range insert; move the column-major temporaries instead of copying
  them; pass variable names by const reference
The rapidjson callbacks were passing a bare const char* into a
const std::string& parameter, discarding the length rapidjson already
provides. That cost a strlen and a heap allocation for every key and every
string token in the input, for text that was then copied again into the key
stack. json_handler::key and json_handler::string now take std::string_view
and the parser passes {str, length}.

Also take string_view in valid_varname, unexpected_error, to_column_major
and convert_offset_rtl_2_ltr. All seven unexpected_error call sites pass
string literals, each of which was building a std::string only to stream it
into a stringstream and destroy it.

slot_types_map gets a std::less<> comparator so key() can look up a view
without converting it back to a string; it is the only map looked up that
way. The two signatures that changed are marked override in both handler
subclasses, since otherwise a missed subclass silently becomes a
non-overriding overload and stops receiving events.

The std::string parameters left in json_data are var_context virtuals, which
cannot change without changing the interface and its other implementations.
Rename num_outer_dims to num_outer_arrays, since it counts enclosing array
depth rather than dimensions in general, and has_own_dims to is_array, which
is what it actually asks. That makes own_dims_begin() redundant.

Replace the prose describing the array-of-tuples layout with a worked
example in both the var_entry and json_data docs, and show the complex
block layout as a decode of six values rather than describing it.

The handler's five bookkeeping maps are keyed by name and only ever looked
up, apart from update_array_dims, which does not depend on iteration order.
Use boost::unordered_flat_map with a transparent hasher so that key() can
still look up a string_view without building a string. vars_r and vars_i
stay ordered because names_r and names_i report their iteration order.

Rename objects called var, which collides with stan::math::var.
A destination holding no tuples consumes its buffer as a single payload, so
add if constexpr arms for std::vector<double>, std::vector<int> and Eigen
destinations with int or double scalars alongside the existing scalar and
complex arms.

read_whole_payload is read_from_buffer_block followed by check_consumed,
which is exactly what the general path does once the tuple-field path is
empty, so errors and behavior are unchanged while the index_sequence
plumbing is not instantiated. Eigen destinations with complex scalars and
nested std::vectors still take the general path.
vars_map_r and vars_map_i do not need to be ordered. names_r and names_i are
their only consumers of iteration order, var_context does not document one,
and random_var_context already reports insertion order rather than sorted
order, so no caller could rely on it. Nothing in the tree reads the order.

Reference stability still holds under open addressing: the reference into
vars_i in the promote branch is last read before vars_r is written and
before the erase, and append_block consumes its reference within the call.

Drops the now unused <map> includes from both headers, and converts the
remaining typedefs in the header to using aliases.
The Eigen and std::vector readers each took an imaginary_offset that only
meant anything for complex destinations, documented as "ignored for
non-complex destinations" in both. Split each into read_real and
read_complex and dispatch at the call site, where read_from_buffer_block
already branches on is_complex<scalar_type_t<T>> to pick the size check and
the cursor advance.

The recursion stays complex-aware throughout, so imaginary_offset is gone
from the real path end to end rather than being threaded through unused.

Factors the strided source map the Eigen readers share into source_block,
which also removes the Stride and SourceMap aliases from each caller.
@SteveBronder

Copy link
Copy Markdown
Collaborator Author

@WardBrian The line change number looks scary but most of this is the json data examples.

SteveBronder and others added 7 commits October 6, 2026 03:02
The entry point funneled every destination through the same traversal, so
an int and an array of tuples both paid for the index_sequence path, the
dotted-name walk and the field-path plumbing. Hand-tracing one leaf of
very_deep crossed eleven instantiations.

A name maps to more than one destination only when an array encloses a
tuple. std::get<I>(x) on a plain tuple is a real subobject, so that case
never needs a path. Split the entry point into two overloads on
contains_tuple. Without a tuple the variable is one name and one whole
buffer, fetched once, checked against num_elements and copied in place.
With one, SlotType walks the tuple skeleton that scalar_type_t leaves
behind, producing one context name per leaf, and fill_slots walks the
destination for that name off a shared cursor. x is never descended by the
name walk, only forwarded.

Replaces read_leaves, load_from_context, read_from_buffer, source_block,
read_whole_payload and check_consumed, and drops index_apply from the leaf
path. The slot path is never empty at a leaf, since the overload is only
selected when scalar_type_t<T> is a tuple, so fill_slots terminates on
sizeof...(Rest) and no longer needs an index_sequence<> overload to pair
against.

read_real and read_complex become read_payload and read_payload_complex
with offset-zero overloads for the top-level call, and the strided source
map they share is named source_map_t.

Adds a file comment working through
std::vector<std::tuple<std::vector<std::tuple<MatrixXcd, double>>>> as a
name tree and a slot walk, and records that an array enclosing a tuple is
filled in element order while a tuple-free payload is column-major. That
fact only existed in test comments. Doxygen on both overloads documents
SlotType and the slot path as recursion parameters rather than arguments a
caller supplies.
@SteveBronder

Copy link
Copy Markdown
Collaborator Author

Seems like a weird Jenkins error...

@SteveBronder SteveBronder reopened this Oct 6, 2026
disableConcurrentBuilds(abortPrevious) aborts the running build on every
push to a PR branch. When the abort lands while the git plugin is inside
"git submodule foreach --recursive git reset --hard", git is killed holding
.git/modules/lib/stan_math/index.lock, and every later build in that
workspace fails while cleaning, before it fetches anything. Neither
"git reset --hard" nor "git clean -fdx" can recover, since both want the
same lock.

runIntegration already deleteDir()s before its checkouts, so only the unit
stages are exposed. They reuse their workspace on purpose, so that
math-libs is not rebuilt every run, and wiping unconditionally would pay
that cost on every build rather than on the broken ones. Wrap their
checkout instead and wipe only after it throws.

Aborting a superseded build is worth keeping, so this recovers from the
abort rather than removing it. A workspace already holding a stale lock
still has to be cleared once by hand before a build gets far enough to run
this.
@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.04 0.04 0.94 -5.86% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.17 0.98 -1.55% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.87 0.86 1.01 1.13% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.01 0.79% faster
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 1.01 0.91% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.03 8.36 0.96 -4.09% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.75 3.75 1.0 -0.05% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 31.74 33.27 0.95 -4.83% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.38 0.99 -1.0% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.86 6.96 0.99 -1.34% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 129.89 129.42 1.0 0.37% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.25 3.21 1.01 1.29% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.6 0.59 1.01 0.91% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 24.93 24.93 1.0 -0.0% slower
performance.compilation 397.53 399.55 0.99 -0.51% slower
Mean result: 0.9913199157609921

Jenkins Console Log
Jenkins Build Stages
Commit hash: 993f35f70b6d7c411c87d88bbb003259bfff0fcd

Machine information
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04.3 LTS
Release:	20.04
Codename:	focal

CPU:

Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Byte Order:                              Little Endian
Address sizes:                           52 bits physical, 57 bits virtual
CPU(s):                                  192
On-line CPU(s) list:                     0-191
Thread(s) per core:                      2
Core(s) per socket:                      48
Socket(s):                               2
NUMA node(s):                            2
Vendor ID:                               AuthenticAMD
CPU family:                              25
Model:                                   17
Model name:                              AMD EPYC 9474F 48-Core Processor
Stepping:                                1
Frequency boost:                         enabled
CPU MHz:                                 1497.569
CPU max MHz:                             4114.4229
CPU min MHz:                             1500.0000
BogoMIPS:                                7189.39
Virtualization:                          AMD-V
L1d cache:                               3 MiB
L1i cache:                               3 MiB
L2 cache:                                96 MiB
L3 cache:                                512 MiB
NUMA node0 CPU(s):                       0-47,96-143
NUMA node1 CPU(s):                       48-95,144-191
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Mitigation; Safe RET
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Mitigation; Clear CPU buffers
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap

G++:

g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang:

clang version 10.0.0-4ubuntu1 
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

@WardBrian WardBrian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall I think this looks good, I'd like to plug it into a branch of stanc for testing before merging though

Comment thread Jenkinsfile
Comment on lines +103 to +115
// The unit stages reuse their workspace so math-libs is not rebuilt
// every run, so an aborted build can leave a stale index.lock behind
// and every later checkout into that workspace fails while cleaning.
def checkoutResilient = {
try {
checkout scm
} catch (e) {
echo "checkout failed (${e.message}); wiping workspace and retrying"
deleteDir()
checkout scm
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @dylex -- does this seem fine?

Comment thread src/stan/io/read_from_context.hpp Outdated
Comment thread src/stan/io/read_from_context.hpp Outdated
Comment thread src/stan/io/read_from_context.hpp Outdated
@WardBrian

Copy link
Copy Markdown
Member

Running stan-dev/stanc3#1742 against this branch here

Comment thread src/stan/io/read_from_context.hpp
@SteveBronder

Copy link
Copy Markdown
Collaborator Author

I also like this PR because, once the model is agnostic to the var context's data layout ,we can look at improving the serialization of the input data so we can avoid all of this wacky indexing stuff.

@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.04 0.04 0.99 -0.52% slower
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.16 0.99 -0.62% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.88 0.87 1.01 1.44% faster
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.02 0.91 -9.67% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 0.99 -0.73% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.04 8.32 0.97 -3.47% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.72 3.73 1.0 -0.28% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.52 33.55 0.97 -3.17% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.38 1.0 -0.43% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.86 7.0 0.98 -2.06% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 130.08 136.07 0.96 -4.61% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.2 3.22 1.0 -0.49% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.62 0.59 1.06 6.04% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.3 25.13 1.01 0.69% faster
performance.compilation 386.74 382.51 1.01 1.09% faster
Mean result: 0.989975081132633

Jenkins Console Log
Jenkins Build Stages
Commit hash: 993f35f70b6d7c411c87d88bbb003259bfff0fcd

Machine information
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04.3 LTS
Release:	20.04
Codename:	focal

CPU:

Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Byte Order:                              Little Endian
Address sizes:                           52 bits physical, 57 bits virtual
CPU(s):                                  192
On-line CPU(s) list:                     0-191
Thread(s) per core:                      2
Core(s) per socket:                      48
Socket(s):                               2
NUMA node(s):                            2
Vendor ID:                               AuthenticAMD
CPU family:                              25
Model:                                   17
Model name:                              AMD EPYC 9474F 48-Core Processor
Stepping:                                1
Frequency boost:                         enabled
CPU MHz:                                 1499.094
CPU max MHz:                             4114.4229
CPU min MHz:                             1500.0000
BogoMIPS:                                7189.39
Virtualization:                          AMD-V
L1d cache:                               3 MiB
L1i cache:                               3 MiB
L2 cache:                                96 MiB
L3 cache:                                512 MiB
NUMA node0 CPU(s):                       0-47,96-143
NUMA node1 CPU(s):                       48-95,144-191
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Mitigation; Safe RET
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Mitigation; Clear CPU buffers
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap

G++:

g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang:

clang version 10.0.0-4ubuntu1 
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants