Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/3299 improved ess rhat #3312

Merged
merged 10 commits into from
Oct 11, 2024
Merged

Conversation

mitzimorris
Copy link
Member

@mitzimorris mitzimorris commented Oct 7, 2024

Submission Checklist

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

Summary

Refactor of method for computing rank-normalized split bulk and tail rhat and addition of method to compute rank-normalized split bulk and tail ess as described in https://arxiv.org/abs/1903.08008.

Intended Effect

Refactor the logic added to stan/analyze/mcmc/compute_potential_scale_reduction.hpp via PR #3266. so that some of the logic can be reused to implement rank-normalized split ESS.

  • added helper functions rank_normalization and split_chains and new functions rank_normalized_split_rhat and rank_normalized_split_ess, each in a separate file.

This PR will be followed by another refactor of the stan::mcmc::chains object. In anticipation of that refactoring, both rank_normalized_split_rhat and rank_normalized_split_ess have a single argument which is an Eigen::MatrixXd of draws instead of vectors draws, sizes.

How to Verify

Unit tests based on running the same Stan CSV files through CmdStanR and using the current implementations in R's posterior library to get rhat and ess.

Side Effects

N/A

Documentation

N/A - when CmdStan's stansummary method is updated, will be documented in CmdStan docs.

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): Columbia University

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

@stan-buildbot
Copy link
Contributor


Name Old Result New Result Ratio Performance change( 1 - new / old )
arma/arma.stan 0.36 0.36 0.99 -1.3% slower
low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.0 0.11% faster
gp_regr/gen_gp_data.stan 0.03 0.03 0.99 -0.53% slower
gp_regr/gp_regr.stan 0.09 0.1 0.99 -1.1% slower
sir/sir.stan 73.32 72.86 1.01 0.63% faster
irt_2pl/irt_2pl.stan 4.41 4.26 1.04 3.57% faster
eight_schools/eight_schools.stan 0.06 0.06 1.07 6.75% faster
pkpd/sim_one_comp_mm_elim_abs.stan 0.26 0.25 1.05 4.92% faster
pkpd/one_comp_mm_elim_abs.stan 20.2 19.02 1.06 5.86% faster
garch/garch.stan 0.46 0.42 1.08 7.49% faster
low_dim_gauss_mix/low_dim_gauss_mix.stan 2.82 2.65 1.06 6.09% faster
arK/arK.stan 1.89 1.74 1.08 7.72% faster
gp_pois_regr/gp_pois_regr.stan 2.9 2.73 1.06 5.97% faster
low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 9.16 8.55 1.07 6.62% faster
performance.compilation 199.22 190.83 1.04 4.21% faster
Mean result: 1.0406367197239463

Jenkins Console Log
Blue Ocean
Commit hash: d669f2b029575d5191b8f394b58b652e4bc4c805


Machine information No LSB modules are available. 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: 46 bits physical, 48 bits virtual
CPU(s): 80
On-line CPU(s) list: 0-79
Thread(s) per core: 2
Core(s) per socket: 20
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 85
Model name: Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
Stepping: 4
CPU MHz: 3394.563
CPU max MHz: 3700.0000
CPU min MHz: 1000.0000
BogoMIPS: 4800.00
Virtualization: VT-x
L1d cache: 1.3 MiB
L1i cache: 1.3 MiB
L2 cache: 40 MiB
L3 cache: 55 MiB
NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78
NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Mitigation; IBRS
Vulnerability Spec rstack overflow: Not affected
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; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear flush_l1d arch_capabilities

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

@mitzimorris
Copy link
Member Author

this is ready for review.

@stan-buildbot
Copy link
Contributor


Name Old Result New Result Ratio Performance change( 1 - new / old )
arma/arma.stan 0.46 0.39 1.19 15.93% faster
low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.04 4.06% faster
gp_regr/gen_gp_data.stan 0.03 0.03 1.06 5.56% faster
gp_regr/gp_regr.stan 0.1 0.1 1.03 2.98% faster
sir/sir.stan 78.92 74.95 1.05 5.02% faster
irt_2pl/irt_2pl.stan 5.92 4.9 1.21 17.12% faster
eight_schools/eight_schools.stan 0.06 0.06 1.02 2.24% faster
pkpd/sim_one_comp_mm_elim_abs.stan 0.28 0.26 1.07 6.21% faster
pkpd/one_comp_mm_elim_abs.stan 21.15 20.52 1.03 2.98% faster
garch/garch.stan 0.52 0.46 1.11 10.17% faster
low_dim_gauss_mix/low_dim_gauss_mix.stan 3.31 2.82 1.17 14.78% faster
arK/arK.stan 2.0 1.87 1.07 6.64% faster
gp_pois_regr/gp_pois_regr.stan 3.18 2.94 1.08 7.59% faster
low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 9.77 9.19 1.06 5.93% faster
performance.compilation 203.68 197.84 1.03 2.87% faster
Mean result: 1.0822159046829158

Jenkins Console Log
Blue Ocean
Commit hash: d669f2b029575d5191b8f394b58b652e4bc4c805


Machine information No LSB modules are available. 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: 46 bits physical, 48 bits virtual
CPU(s): 80
On-line CPU(s) list: 0-79
Thread(s) per core: 2
Core(s) per socket: 20
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 85
Model name: Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
Stepping: 4
CPU MHz: 2400.000
CPU max MHz: 3700.0000
CPU min MHz: 1000.0000
BogoMIPS: 4800.00
Virtualization: VT-x
L1d cache: 1.3 MiB
L1i cache: 1.3 MiB
L2 cache: 40 MiB
L3 cache: 55 MiB
NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78
NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Mitigation; IBRS
Vulnerability Spec rstack overflow: Not affected
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; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear flush_l1d arch_capabilities

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

@mitzimorris mitzimorris requested a review from WardBrian October 9, 2024 19:17
for (std::size_t k = i; k < j; ++k) {
double p = (avg_rank - 0.375) / (size + 0.25);
const Eigen::Index index = value_with_index[k].second;
rank_matrix(index) = boost::math::quantile(dist, p);
Copy link
Member

Choose a reason for hiding this comment

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

am I correct that this is stan::math::inv_Phi?

I know this is just moving code around, but if so that's probably worth calling instead

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure - this is a question for @aleksgorica or @avehtari

Copy link
Collaborator

Choose a reason for hiding this comment

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

@WardBrian, can you clarify the question? I'm not certain to which part you refer to be stan::math::inv_Phi()

Copy link
Member

Choose a reason for hiding this comment

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

We're computing rank[index] by using the boost::math::quantile function where this dist object is just a standard normal -- I believe that is equivalent to calling our own inv_Phi

src/test/unit/mcmc/chains_test.cpp Show resolved Hide resolved
Copy link
Member

@WardBrian WardBrian left a comment

Choose a reason for hiding this comment

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

Looks good -- if we get an answer on that inv_Phi question we can address separately

@mitzimorris mitzimorris merged commit 2550bbd into develop Oct 11, 2024
3 checks passed
@mitzimorris mitzimorris deleted the feature/3299-improved-ESS-Rhat branch October 11, 2024 20:41
@mitzimorris mitzimorris restored the feature/3299-improved-ESS-Rhat branch October 11, 2024 20:41
@mitzimorris mitzimorris mentioned this pull request Oct 12, 2024
3 tasks
@bob-carpenter
Copy link
Contributor

Looks good -- if we get an answer on that inv_Phi question we can address separately

Yes, inv_Phi is the quantile function for standard normal distributions, so this should be the same.

Our internal inv_Phi is hard coded directly:

https://mc-stan.org/math/prim_2fun_2inv___phi_8hpp_source.html

and then in what looks like an identical implementation to me to first order, for OpenCL:

https://mc-stan.org/math/opencl_2kernels_2device__functions_2inv___phi_8hpp_source.html

@WardBrian WardBrian deleted the feature/3299-improved-ESS-Rhat branch October 16, 2024 15:33
* @param chains stores chains in columns
* @return normal scores for average ranks of draws
*/
inline Eigen::MatrixXd rank_transform(const Eigen::MatrixXd& chains) {
Copy link
Member Author

Choose a reason for hiding this comment

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

this function moved to file rank_normalization.hpp

@mitzimorris
Copy link
Member Author

@avehtari - in this PR, file split_rank_normalized_ess.hpp, function ess is a refactor of this:

Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains);
Eigen::VectorXd chain_mean(num_chains);
Eigen::VectorXd chain_var(num_chains);
for (int chain = 0; chain < num_chains; ++chain) {
Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(
draws[chain], sizes[chain]);
autocovariance<double>(draw, acov(chain));
chain_mean(chain) = draw.mean();
chain_var(chain) = acov(chain)(0) * num_draws / (num_draws - 1);
}
double mean_var = chain_var.mean();
double var_plus = mean_var * (num_draws - 1) / num_draws;
if (num_chains > 1)
var_plus += math::variance(chain_mean);
Eigen::VectorXd rho_hat_s(num_draws);
rho_hat_s.setZero();
Eigen::VectorXd acov_s(num_chains);
for (int chain = 0; chain < num_chains; ++chain)
acov_s(chain) = acov(chain)(1);
double rho_hat_even = 1.0;
rho_hat_s(0) = rho_hat_even;
double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;
rho_hat_s(1) = rho_hat_odd;
// Convert raw autocovariance estimators into Geyer's initial
// positive sequence. Loop only until num_draws - 4 to
// leave the last pair of autocorrelations as a bias term that
// reduces variance in the case of antithetical chains.
size_t s = 1;
while (s < (num_draws - 4) && (rho_hat_even + rho_hat_odd) > 0) {
for (int chain = 0; chain < num_chains; ++chain)
acov_s(chain) = acov(chain)(s + 1);
rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus;
for (int chain = 0; chain < num_chains; ++chain)
acov_s(chain) = acov(chain)(s + 2);
rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;
if ((rho_hat_even + rho_hat_odd) >= 0) {
rho_hat_s(s + 1) = rho_hat_even;
rho_hat_s(s + 2) = rho_hat_odd;
}
s += 2;
}
int max_s = s;
// this is used in the improved estimate, which reduces variance
// in antithetic case -- see tau_hat below
if (rho_hat_even > 0)
rho_hat_s(max_s + 1) = rho_hat_even;
// Convert Geyer's initial positive sequence into an initial
// monotone sequence
for (int s = 1; s <= max_s - 3; s += 2) {
if (rho_hat_s(s + 1) + rho_hat_s(s + 2) > rho_hat_s(s - 1) + rho_hat_s(s)) {
rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2;
rho_hat_s(s + 2) = rho_hat_s(s + 1);
}
}
double num_total_draws = num_chains * num_draws;
// Geyer's truncated estimator for the asymptotic variance
// Improved estimate reduces variance in antithetic case
double tau_hat = -1 + 2 * rho_hat_s.head(max_s).sum() + rho_hat_s(max_s + 1);
return std::min(num_total_draws / tau_hat,
num_total_draws * std::log10(num_total_draws));

do you see any problems here?

@avehtari
Copy link
Collaborator

  1. Why ess function is in split_rank_normalize_ess.hpp while it's needed also for non-rank-normalized ess?
  2. The new code is dropping the following and I don't understand how it can be done
  for (int chain = 0; chain < num_chains; ++chain)
    acov_s(chain) = acov(chain)(1);
  1. The initial monotone sequence part has been moved before "the improved estimate" lines
  // this is used in the improved estimate, which reduces variance
  // in antithetic case -- see tau_hat below
  if (rho_hat_even > 0)
    rho_hat_s(max_s + 1) = rho_hat_even;

and I'm not able to figure in my head if that is guaranteed to give the same answer. I can't remember, but I assume I had a reason to have it outside that earlier loop and in the place where I had it.

  1. I (and Andrew) don't like num_samples. It should be either num_draws, num_total_draws, or sample_size. The best would be to have in the beginning
 const Eigen::Index num_chains = chains.cols();
 const Eigen::Index num_iterations = chains.rows();

and then later

double num_draws = num_chains * num_iterations;

@mitzimorris
Copy link
Member Author

mitzimorris commented Oct 18, 2024

re point 2 - yes, caught that.

the differences between this implementation and posterior are that missing step:

  for (int chain = 0; chain < num_chains; ++chain)
    acov_s(chain) = acov(chain)(1);

and the use of stan::analyze::covariance instead of stan::math::covariance.

these have been fixed in the latest version of PR #3313, and unit tests added which verify that the old and new versions of ess compute the same answer.

I'm now going through the rank-normalized rhat and will add similar checks.

this raises the question of the why a different implementation of covariance? is one ESS specific?

@bob-carpenter
Copy link
Contributor

bob-carpenter commented Oct 18, 2024

I (and Andrew) don't like num_samples

Andrew instilled that distinction in me, and I try to stick to it, but I've given up trying to get other people to recognize the distinction. It's just too commonly used everywhere to fight. Maybe I should write another crabby linguist blog post :-)

On the other hand, I think we should stick to this distinction in our own writing about Stan, at least in our doc.

I created an issue to deal with the dozens of uses in our docs that violate the @andrewgelman style guide.

stan-dev/docs#823

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.

5 participants