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

Fix: make importance resampling robust to importance samples with weight log(0) #68

Merged
merged 2 commits into from
Apr 10, 2024
Merged
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
11 changes: 8 additions & 3 deletions src/gen/inference/importance.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
(+ (math/log nr) x)
(recur rst nr (double x)))))))

(defn- neg-inf?
[v]
(= v ##-Inf))

(defn resampling [gf args observations n-samples]
;; https://github.com/probcomp/Gen.jl/blob/master/src/inference/importance.jl#L77...L95
(let [result (gf/generate gf args observations)
Expand All @@ -31,9 +35,10 @@
(let [candidate (gf/generate gf args observations)
candidate-model-trace (:trace candidate)
log-weight (:weight candidate)]
(vswap! log-total-weight #(logsumexp [log-weight %]))
(when (dist/bernoulli (math/exp (- log-weight @log-total-weight)))
(vreset! model-trace candidate-model-trace))))
(when-not (neg-inf? log-weight)
(vswap! log-total-weight #(logsumexp [log-weight %]))
(when (dist/bernoulli (math/exp (- log-weight @log-total-weight)))
(vreset! model-trace candidate-model-trace)))))
(let [log-ml-estimate (- @log-total-weight (math/log n-samples))]
{:trace @model-trace
:weight log-ml-estimate})))
23 changes: 23 additions & 0 deletions test/gen/inference/importance_test.cljc
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
(ns gen.inference.importance-test
(:require [clojure.test :refer [deftest is testing]]
[gen.choicemap :as choicemap :refer [choicemap get-value]]
[gen.distribution.kixi :as dist]
[gen.dynamic :as dynamic :refer [gen]]
[gen.inference.importance :as importance]
[gen.trace :as trace]))

(def model-causing-rejection-sampling
(gen
[]
(if (dynamic/trace! :foo dist/bernoulli 0.5)
(dynamic/trace! :bar dist/bernoulli 1.0)
(dynamic/trace! :bar dist/bernoulli 0.0))))

(deftest rejection
(testing "Robustness in the presence of importance samples with weight log(0)."
(is {:foo true :bar true}
;; Needs a couple of samples to trigger previous bug here.
(-> (importance/resampling model-causing-rejection-sampling [] (choicemap {:bar true}) 10)
(:trace)
(trace/get-choices)
(get-value)))))
Loading