Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/stan/variational/advi.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<double>& values) {
const double max_val = std::numeric_limits<double>::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

/**
Expand Down
23 changes: 23 additions & 0 deletions src/test/unit/variational/advi_infinite_output_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#include <test/test-models/good/variational/univariate_no_constraint.hpp>
#include <stan/variational/advi.hpp>
#include <stan/services/util/create_rng.hpp>
#include <gtest/gtest.h>
#include <limits>
#include <vector>

typedef stan::variational::advi<stan_model, stan::variational::normal_meanfield,
stan::rng_t>
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<double>::max();
const double inf = std::numeric_limits<double>::infinity();
std::vector<double> 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]);
}
Loading