From 96c992d9aaf1dff76cc0a4af79a9d37c95304ab2 Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:21:57 -0500 Subject: [PATCH] Coerce infinite ADVI output values to finite before writing --- src/stan/variational/advi.hpp | 18 +++++++++++++++ .../variational/advi_infinite_output_test.cpp | 23 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/test/unit/variational/advi_infinite_output_test.cpp diff --git a/src/stan/variational/advi.hpp b/src/stan/variational/advi.hpp index 579e222b41d..a0e5c902986 100644 --- a/src/stan/variational/advi.hpp +++ b/src/stan/variational/advi.hpp @@ -489,6 +489,7 @@ class advi { // The first row of lp_, log_p, and log_g. values.insert(values.begin(), {0, 0, 0}); + coerce_infinite_to_max(values); parameter_writer(values); // Draw more from posterior and write on subsequent lines @@ -514,12 +515,29 @@ class advi { logger.info(msg2); // Write lp__, log_p, and log_g. values.insert(values.begin(), {0, log_p, log_g}); + coerce_infinite_to_max(values); parameter_writer(values); } logger.info("COMPLETED."); return stan::services::error_codes::OK; } + /** + * Replace infinite values with the largest finite double of the same + * sign. Infinite values cannot be read back from CSV output on Windows + * (they are written as "1.#INF"), so they are coerced to the nearest + * finite value before writing. + * + * @param[in,out] values values to be written + */ + static void coerce_infinite_to_max(std::vector& values) { + const double max_val = std::numeric_limits::max(); + for (double& v : values) { + if (std::isinf(v)) + v = (v > 0) ? max_val : -max_val; + } + } + // TODO(akucukelbir): move these things to stan math and test there /** diff --git a/src/test/unit/variational/advi_infinite_output_test.cpp b/src/test/unit/variational/advi_infinite_output_test.cpp new file mode 100644 index 00000000000..db1731f354e --- /dev/null +++ b/src/test/unit/variational/advi_infinite_output_test.cpp @@ -0,0 +1,23 @@ +#include +#include +#include +#include +#include +#include + +typedef stan::variational::advi + advi_meanfield_t; + +// Infinite values cannot be read back from CSV output (Windows writes them as +// "1.#INF"), so they must be coerced to the largest finite double. +TEST(AdviInfiniteOutput, InfinityCoercedToMaxDouble) { + const double max_val = std::numeric_limits::max(); + const double inf = std::numeric_limits::infinity(); + std::vector values{0, 1.5, inf, -inf}; + advi_meanfield_t::coerce_infinite_to_max(values); + EXPECT_EQ(0, values[0]); + EXPECT_EQ(1.5, values[1]); + EXPECT_EQ(max_val, values[2]); + EXPECT_EQ(-max_val, values[3]); +}