inference.py 14.9 KB
Newer Older
Chris Jewell's avatar
Chris Jewell committed
1
"""MCMC Test Rig for COVID-19 UK model"""
2
3
# pylint: disable=E402

4
5
import h5py
import pickle as pkl
6
from time import perf_counter
7
8
import tqdm
import yaml
9
import numpy as np
10
11
import tensorflow as tf
import tensorflow_probability as tfp
Chris Jewell's avatar
Chris Jewell committed
12

13
14
15
16
from tensorflow_probability.python.internal import unnest
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.experimental.stats import sample_stats

17
from gemlib.util import compute_state
Chris Jewell's avatar
Chris Jewell committed
18
from gemlib.mcmc import Posterior
19
20
21
22
23
from gemlib.mcmc import GibbsKernel
from covid.tasks.mcmc_kernel_factory import make_hmc_base_kernel
from covid.tasks.mcmc_kernel_factory import make_hmc_fast_adapt_kernel
from covid.tasks.mcmc_kernel_factory import make_hmc_slow_adapt_kernel
from covid.tasks.mcmc_kernel_factory import make_event_multiscan_gibbs_step
24

25
import covid.model_spec as model_spec
26

27
28
tfd = tfp.distributions
tfb = tfp.bijectors
29
DTYPE = model_spec.DTYPE
30
31


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def get_weighted_running_variance(draws):

    prev_mean, prev_var = tf.nn.moments(draws[-draws.shape[0] // 2 :], axes=[0])
    num_samples = tf.cast(
        draws.shape[0] / 2,
        dtype=dtype_util.common_dtype([prev_mean, prev_var], tf.float32),
    )
    weighted_running_variance = sample_stats.RunningVariance.from_stats(
        num_samples=num_samples, mean=prev_mean, variance=prev_var
    )
    return weighted_running_variance


@tf.function
def _fast_adapt_window(
    num_draws,
    joint_log_prob_fn,
    initial_position,
    hmc_kernel_kwargs,
    dual_averaging_kwargs,
    event_kernel_kwargs,
    trace_fn=None,
    seed=None,
):

    kernel_list = [
        (
            0,
            make_hmc_fast_adapt_kernel(
                hmc_kernel_kwargs=hmc_kernel_kwargs,
                dual_averaging_kwargs=dual_averaging_kwargs,
            ),
        ),
        (1, make_event_multiscan_gibbs_step(**event_kernel_kwargs)),
    ]

    kernel = GibbsKernel(
        target_log_prob_fn=joint_log_prob_fn,
        kernel_list=kernel_list,
        name="fast_adapt",
    )

    draws, trace, fkr = tfp.mcmc.sample_chain(
        num_draws,
        initial_position,
        kernel=kernel,
        return_final_kernel_results=True,
        trace_fn=trace_fn,
        seed=seed,
    )

    weighted_running_variance = get_weighted_running_variance(draws[0])
    step_size = unnest.get_outermost(fkr.inner_results[0], "step_size")
    return draws, trace, step_size, weighted_running_variance


@tf.function
def _slow_adapt_window(
    num_draws,
    joint_log_prob_fn,
    initial_position,
    initial_running_variance,
    hmc_kernel_kwargs,
    dual_averaging_kwargs,
    event_kernel_kwargs,
    trace_fn=None,
    seed=None,
):
    kernel_list = [
        (
            0,
            make_hmc_slow_adapt_kernel(
                initial_running_variance,
                hmc_kernel_kwargs,
                dual_averaging_kwargs,
            ),
        ),
        (1, make_event_multiscan_gibbs_step(**event_kernel_kwargs)),
    ]

    kernel = GibbsKernel(
        target_log_prob_fn=joint_log_prob_fn,
        kernel_list=kernel_list,
        name="slow_adapt",
    )

    draws, trace, fkr = tfp.mcmc.sample_chain(
        num_draws,
        current_state=initial_position,
        kernel=kernel,
        return_final_kernel_results=True,
        trace_fn=trace_fn,
    )

    step_size = unnest.get_outermost(fkr.inner_results[0], "step_size")
    momentum_distribution = unnest.get_outermost(
        fkr.inner_results[0], "momentum_distribution"
    )

    weighted_running_variance = get_weighted_running_variance(draws[0])

    return (
        draws,
        trace,
        step_size,
        weighted_running_variance,
        momentum_distribution,
    )


@tf.function  # (experimental_compile=True)
def _fixed_window(
    num_draws,
    joint_log_prob_fn,
    initial_position,
    hmc_kernel_kwargs,
    event_kernel_kwargs,
    trace_fn=None,
    seed=None,
):
    """Fixed step size HMC.

    :returns: (draws, trace, final_kernel_results)
    """
    kernel_list = [
        (0, make_hmc_base_kernel(**hmc_kernel_kwargs)),
        (1, make_event_multiscan_gibbs_step(**event_kernel_kwargs)),
    ]

    kernel = GibbsKernel(
        target_log_prob_fn=joint_log_prob_fn,
        kernel_list=kernel_list,
        name="fixed",
    )

    return tfp.mcmc.sample_chain(
        num_draws,
        current_state=initial_position,
        kernel=kernel,
        return_final_kernel_results=True,
        trace_fn=trace_fn,
        seed=seed,
    )


def trace_results_fn(_, results):
    """Packs results into a dictionary"""
    results_dict = {}
    root_results = results.inner_results

    results_dict["hmc"] = {
        "is_accepted": unnest.get_innermost(root_results[0], "is_accepted"),
        "target_log_prob": unnest.get_innermost(
            root_results[0], "target_log_prob"
        ),
    }

    def get_move_results(results):
        return {
            "is_accepted": results.is_accepted,
            "target_log_prob": results.accepted_results.target_log_prob,
            "proposed_delta": tf.stack(
                [
                    results.accepted_results.m,
                    results.accepted_results.t,
                    results.accepted_results.delta_t,
                    results.accepted_results.x_star,
                ]
            ),
        }

    res1 = root_results[1].inner_results
    results_dict["move/S->E"] = get_move_results(res1[0])
    results_dict["move/E->I"] = get_move_results(res1[1])
    results_dict["occult/S->E"] = get_move_results(res1[2])
    results_dict["occult/E->I"] = get_move_results(res1[3])

    return results_dict


def draws_to_dict(draws):
    return {
        "beta2": draws[0][:, 0],
        "gamma0": draws[0][:, 1],
        "gamma1": draws[0][:, 2],
        "sigma": draws[0][:, 3],
        "beta3": tf.zeros([1, 5], dtype=DTYPE),
        "beta1": draws[0][:, 4],
        "xi": draws[0][:, 5:],
        "events": draws[1],
    }


def run_mcmc(
    joint_log_prob_fn, current_state, initial_conditions, config, output_file
):

    num_draws = config["num_bursts"] * config["num_burst_samples"]
    fast_window_size = 75
    slow_window_size = 25
    num_slow_windows = 4

    hmc_kernel_kwargs = {
        "step_size": 0.00001,
        "num_leapfrog_steps": 4,
        "momentum_distribution": None,
    }
    dual_averaging_kwargs = {
        "num_adaptation_steps": fast_window_size,
        "target_accept_prob": 0.75,
    }
    event_kernel_kwargs = {
        "initial_state": initial_conditions,
        "t_range": [
            current_state[1].shape[-2] - 21,
            current_state[1].shape[-2],
        ],
        "config": config,
    }

    # Set up posterior
    draws, trace, _ = _fixed_window(
        num_draws=1,
        joint_log_prob_fn=joint_log_prob_fn,
        initial_position=current_state,
        hmc_kernel_kwargs=hmc_kernel_kwargs,
        event_kernel_kwargs=event_kernel_kwargs,
        trace_fn=trace_results_fn,
    )
    posterior = Posterior(
        output_file,
        sample_dict=draws_to_dict(draws),
        results_dict=trace,
        num_samples=5000 + 75 + 25 + 50 + 100 + 200 + 75,
    )
    offset = 0

    # Fast adaptation sampling
    print(f"Fast window {fast_window_size}")
    draws, trace, step_size, running_variance = _fast_adapt_window(
        num_draws=fast_window_size,
        joint_log_prob_fn=joint_log_prob_fn,
        initial_position=current_state,
        hmc_kernel_kwargs=hmc_kernel_kwargs,
        dual_averaging_kwargs=dual_averaging_kwargs,
        event_kernel_kwargs=event_kernel_kwargs,
        trace_fn=trace_results_fn,
    )
    posterior.write_samples(
        draws_to_dict(draws),
        first_dim_offset=offset,
    )
    posterior.write_results(trace, first_dim_offset=offset)
    offset += fast_window_size
    current_state = [s[-1] for s in draws]

    # Slow adaptation sampling
    hmc_kernel_kwargs["step_size"] = step_size
    for slow_window_idx in range(num_slow_windows):
        window_num_draws = slow_window_size * (2 ** slow_window_idx)
        print(f"Slow window {window_num_draws}")
        (
            draws,
            trace,
            step_size,
            running_variance,
            momentum_distribution,
        ) = _slow_adapt_window(
            num_draws=window_num_draws,
            joint_log_prob_fn=joint_log_prob_fn,
            initial_position=current_state,
            initial_running_variance=running_variance,
            hmc_kernel_kwargs=hmc_kernel_kwargs,
            dual_averaging_kwargs=dual_averaging_kwargs,
            event_kernel_kwargs=event_kernel_kwargs,
            trace_fn=trace_results_fn,
        )
        hmc_kernel_kwargs["step_size"] = step_size
        hmc_kernel_kwargs["momentum_distribution"] = momentum_distribution
        current_state = [s[-1] for s in draws]
        posterior.write_samples(
            draws_to_dict(draws),
            first_dim_offset=offset,
        )
        posterior.write_results(trace, first_dim_offset=offset)
        offset += window_num_draws

    # Fast adaptation sampling
    print(f"Fast window {fast_window_size}")
    draws, trace, step_size, weighted_running_variance = _fast_adapt_window(
        num_draws=fast_window_size,
        joint_log_prob_fn=joint_log_prob_fn,
        initial_position=current_state,
        hmc_kernel_kwargs=hmc_kernel_kwargs,
        dual_averaging_kwargs=dual_averaging_kwargs,
        event_kernel_kwargs=event_kernel_kwargs,
        trace_fn=trace_results_fn,
    )
    current_state = [s[-1] for s in draws]
    posterior.write_samples(
        draws_to_dict(draws),
        first_dim_offset=offset,
    )
    posterior.write_results(trace, first_dim_offset=offset)
    offset += fast_window_size

    # Fixed window sampling
    print("Sampling...")
    hmc_kernel_kwargs["step_size"] = step_size
    for i in tqdm.tqdm(range(config["num_bursts"])):
        draws, trace, _ = _fixed_window(
            num_draws=config["num_burst_samples"],
            joint_log_prob_fn=joint_log_prob_fn,
            initial_position=current_state,
            hmc_kernel_kwargs=hmc_kernel_kwargs,
            event_kernel_kwargs=event_kernel_kwargs,
            trace_fn=trace_results_fn,
        )
        current_state = [state_part[-1] for state_part in draws]
        posterior.write_samples(
            draws_to_dict(draws),
            first_dim_offset=offset,
        )
        posterior.write_results(
            trace,
            first_dim_offset=offset,
        )
        offset += config["num_burst_samples"]

    return posterior


364
def mcmc(data_file, output_file, config, use_autograph=False, use_xla=True):
365
    """Constructs and runs the MCMC"""
366

367
368
369
370
    if tf.test.gpu_device_name():
        print("Using GPU")
    else:
        print("Using CPU")
371

372
373
    with open(data_file, "rb") as f:
        data = pkl.load(f)
374
375
376
377

    # We load in cases and impute missing infections first, since this sets the
    # time epoch which we are analysing.
    # Impute censored events, return cases
378
    events = model_spec.impute_censored_events(data["cases"].astype(DTYPE))
379
380
381
382
383
384
385
386
387

    # Initial conditions are calculated by calculating the state
    # at the beginning of the inference period
    #
    # Imputed censored events that pre-date the first I-R events
    # in the cases dataset are discarded.  They are only used to
    # to set up a sensible initial state.
    state = compute_state(
        initial_state=tf.concat(
388
            [data["N"][:, tf.newaxis], tf.zeros_like(events[:, 0, :])],
389
            axis=-1,
390
        ),
391
        events=events,
392
        stoichiometry=model_spec.STOICHIOMETRY,
393
    )
394
    start_time = state.shape[1] - data["cases"].shape[1]
395
396
397
398
    initial_state = state[:, start_time, :]
    events = events[:, start_time:, :]

    ########################################################
399
    # Construct the MCMC kernels #
400
401
    ########################################################
    model = model_spec.CovidUK(
402
        covariates=data,
403
404
405
        initial_state=initial_state,
        initial_step=0,
        num_steps=events.shape[1],
406
    )
407

408
409
410
411
412
413
414
415
416
417
    def joint_log_prob(unconstrained_params, events):
        bij = tfb.Invert(  # Forward transform unconstrains params
            tfb.Blockwise(
                [
                    tfb.Softplus(low=dtype_util.eps(DTYPE)),
                    tfb.Identity(),
                    tfb.Softplus(low=dtype_util.eps(DTYPE)),
                    tfb.Identity(),
                ],
                block_sizes=[1, 2, 1, unconstrained_params.shape[-1] - 4],
Chris Jewell's avatar
Chris Jewell committed
418
            )
419
        )
420
421
422
423
424
425
426
427
428
429
430
431
        params = bij.inverse(unconstrained_params)
        return (
            model.log_prob(
                dict(
                    beta2=params[0],
                    gamma0=params[1],
                    gamma1=params[2],
                    sigma=params[3],
                    beta1=params[4],
                    xi=params[5:],
                    seir=events,
                )
432
            )
433
            + bij.inverse_log_det_jacobian(unconstrained_params, event_ndims=1)
434
435
        )

436
    # MCMC tracing functions
437
438
439
    ###############################
    # Construct bursted MCMC loop #
    ###############################
440
441
442
443
444
445
446
447
448
449
    current_chain_state = [
        tf.concat(
            [
                np.array([0.6, 0.0, 0.0, 0.1], dtype=DTYPE),
                np.zeros(
                    model.model["xi"](0.0, 0.1).event_shape[-1] + 1,
                    dtype=DTYPE,
                ),
            ],
            axis=0,
450
        ),
451
452
        events,
    ]
453
    print("Initial logpi:", joint_log_prob(*current_chain_state))
454

Chris Jewell's avatar
Chris Jewell committed
455
    # Output file
456
457
458
459
460
461
    posterior = run_mcmc(
        joint_log_prob_fn=joint_log_prob,
        current_state=current_chain_state,
        initial_conditions=initial_state,
        config=config,
        output_file=output_file,
462
    )
Chris Jewell's avatar
Chris Jewell committed
463
    posterior._file.create_dataset("initial_state", data=initial_state)
464
465
    posterior._file.create_dataset(
        "date_range",
466
467
468
        data=np.array(data["date_range"])
        .astype(str)
        .astype(h5py.string_dtype()),
469
    )
470

471
    print(f"Acceptance theta: {posterior['results/hmc/is_accepted'][:].mean()}")
Chris Jewell's avatar
Chris Jewell committed
472
473
474
475
476
477
478
479
480
481
482
483
    print(
        f"Acceptance move S->E: {posterior['results/move/S->E/is_accepted'][:].mean()}"
    )
    print(
        f"Acceptance move E->I: {posterior['results/move/E->I/is_accepted'][:].mean()}"
    )
    print(
        f"Acceptance occult S->E: {posterior['results/occult/S->E/is_accepted'][:].mean()}"
    )
    print(
        f"Acceptance occult E->I: {posterior['results/occult/E->I/is_accepted'][:].mean()}"
    )
Chris Jewell's avatar
Chris Jewell committed
484

Chris Jewell's avatar
Chris Jewell committed
485
    del posterior
486
487
488
489


if __name__ == "__main__":

490
491
492
493
494
495
496
497
498
499
    from argparse import ArgumentParser

    parser = ArgumentParser(description="Run MCMC inference algorithm")
    parser.add_argument(
        "-c", "--config", type=str, help="Config file", required=True
    )
    parser.add_argument(
        "-o", "--output", type=str, help="Output file", required=True
    )
    parser.add_argument(
500
501
502
        "data_file",
        type=str,
        help="Data pickle file",
503
504
    )
    args = parser.parse_args()
505
506
507
508

    with open(args.config, "r") as f:
        config = yaml.load(f, Loader=yaml.FullLoader)

509
    mcmc(args.data_file, args.output, config["Mcmc"])