Repository navigation
Fix/json reader - #3438
Open
SteveBronder wants to merge 20 commits into
Open
Fix/json reader#3438SteveBronder wants to merge 20 commits into
SteveBronder wants to merge 20 commits into
Conversation
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.
Collaborator
Author
|
@WardBrian The line change number looks scary but most of this is the json data examples. |
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.
Collaborator
Author
|
Seems like a weird Jenkins error... |
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.
Contributor
Jenkins Console Log Machine informationDistributor 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
reviewed
Oct 6, 2026
WardBrian
left a comment
Member
There was a problem hiding this comment.
Overall I think this looks good, I'd like to plug it into a branch of stanc for testing before merging though
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 | ||
| } | ||
| } | ||
|
|
2 of 3 tasks
Member
|
Running stan-dev/stanc3#1742 against this branch here |
WardBrian
reviewed
Oct 6, 2026
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. |
Contributor
Jenkins Console Log Machine informationDistributor 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 |
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.
Submission Checklist
Summary
Fixes
json_data::vals_cfor 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_cpaired 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. Forx.1has 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_contextis two overloads split on whether the destination has astd::tuplein 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. Supportsint,double,complex, Eigen vectors/row vectors/matrices, and anystd::vector/std::tuplenesting 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_contextis new and not called anywhere yet. It is meant for the compiler to use for reading data.read_from_contextassumes the data structure it is filling in is alreadyHow to Verify
Side Effects
names_randnames_iuse a boost flat map instead ofstd::mapsince they did not need to be sorted. The json var maps changed fromstd::maptoboost::unordered_flat_map.json_handler::keyandjson_handler::stringtakestd::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: