Skip to content

Global tuning

GlobalTuning ¤

Bases: Strategy

Source code in flowMC/strategy/global_tuning.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 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
class GlobalTuning(Strategy):

    optim: optax.GradientTransformation
    optim_state: optax.OptState

    n_dim: int
    n_chains: int
    n_local_steps: int
    n_global_steps: int
    n_loop: int
    output_thinning: int
    train_thinning: int

    n_epochs: int
    batch_size: int
    n_max_examples: int
    verbose: bool

    @property
    def __name__(self):
        return "GlobalTuning"

    def __init__(
        self,
        **kwargs,
    ):
        class_keys = list(self.__class__.__annotations__.keys())
        for key, value in kwargs.items():
            if key in class_keys:
                if not key.startswith("__"):
                    setattr(self, key, value)

    def __call__(
        self,
        rng_key: PRNGKeyArray,
        local_sampler: ProposalBase,
        global_sampler: NFProposal,
        initial_position: Float[Array, "n_chains n_dim"],
        data: dict,
    ) -> tuple[
        PRNGKeyArray,
        Float[Array, "n_chains n_dim"],
        ProposalBase,
        NFProposal,
        PyTree,
    ]:
        """
        One sampling loop that iterate through the local sampler
        and potentially the global sampler.
        If training is set to True, the loop will also train the normalizing flow model.

        Args:
            initial_position (jnp.array): Initial position. Shape (n_chains, n_dim)
            training (bool, optional):
            Whether to train the normalizing flow model. Defaults to False.

        Returns:
            chains (jnp.array):
            Samples from the posterior. Shape (n_chains, n_local_steps + n_global_steps, n_dim)
        """

        summary = {}
        summary["chains"] = jnp.empty((self.n_chains, 0, self.n_dim))
        summary["log_prob"] = jnp.empty((self.n_chains, 0))
        summary["local_accs"] = jnp.empty((self.n_chains, 0))
        summary["global_accs"] = jnp.empty((self.n_chains, 0))
        summary["loss_vals"] = jnp.empty((0, self.n_epochs))
        current_position = initial_position
        for _ in tqdm(
            range(self.n_loop),
            desc="Global Tuning",
        ):
            rng_key, rng_keys_mcmc = jax.random.split(rng_key)
            rng_keys_mcmc = jax.random.split(rng_keys_mcmc, self.n_chains)
            (
                rng_keys_mcmc,
                positions,
                log_prob,
                local_acceptance,
            ) = local_sampler.sample(
                rng_keys_mcmc,
                self.n_local_steps,
                current_position,
                data,
                verbose=self.verbose,
            )

            summary["chains"] = jnp.append(
                summary["chains"],
                positions[:, :: self.output_thinning],
                axis=1,
            )
            summary["log_prob"] = jnp.append(
                summary["log_prob"],
                log_prob[:, :: self.output_thinning],
                axis=1,
            )

            summary["local_accs"] = jnp.append(
                summary["local_accs"],
                local_acceptance[:, 1 :: self.output_thinning],
                axis=1,
            )

            current_position = summary["chains"][:, -1]

            rng_key, rng_keys_nf = jax.random.split(rng_key)
            positions = summary["chains"][:, :: self.train_thinning]
            chain_size = positions.shape[0] * positions.shape[1]
            if chain_size > self.n_max_examples:
                flat_chain = positions[
                    :, -int(self.n_max_examples / self.n_chains) :
                ].reshape(-1, self.n_dim)
            else:
                flat_chain = positions.reshape(-1, self.n_dim)

            if flat_chain.shape[0] < self.n_max_examples:
                # This is to pad the training data to avoid recompilation.
                flat_chain = jnp.repeat(
                    flat_chain,
                    (self.n_max_examples // flat_chain.shape[0]) + 1,
                    axis=0,
                )
                flat_chain = flat_chain[: self.n_max_examples]

            data_mean = jnp.mean(flat_chain, axis=0)
            data_cov = jnp.cov(flat_chain.T)
            global_sampler.model = eqx.tree_at(
                lambda m: m._data_mean, global_sampler.model, data_mean
            )
            global_sampler.model = eqx.tree_at(
                lambda m: m._data_cov, global_sampler.model, data_cov
            )

            (
                rng_keys_nf,
                model,
                optim_state,
                loss_values,
            ) = global_sampler.model.train(
                rng_keys_nf,
                flat_chain,
                self.optim,
                self.optim_state,
                self.n_epochs,
                self.batch_size,
                self.verbose,
            )
            global_sampler.model = model
            self.optim_state = optim_state
            summary["loss_vals"] = jnp.append(
                summary["loss_vals"],
                loss_values.reshape(1, -1),
                axis=0,
            )

            (
                rng_keys_nf,
                nf_chain,
                log_prob,
                global_acceptance,
            ) = global_sampler.sample(
                rng_keys_nf,
                self.n_global_steps,
                current_position,
                data,
                verbose=self.verbose,
            )

            summary["chains"] = jnp.append(
                summary["chains"],
                nf_chain[:, :: self.output_thinning],
                axis=1,
            )
            summary["log_prob"] = jnp.append(
                summary["log_prob"],
                log_prob[:, :: self.output_thinning],
                axis=1,
            )

            summary["global_accs"] = jnp.append(
                summary["global_accs"],
                global_acceptance[:, 1 :: self.output_thinning],
                axis=1,
            )

            current_position = summary["chains"][:, -1]

        return rng_key, current_position, local_sampler, global_sampler, summary

__call__(rng_key, local_sampler, global_sampler, initial_position, data) ¤

One sampling loop that iterate through the local sampler and potentially the global sampler. If training is set to True, the loop will also train the normalizing flow model.

Parameters:

Name Type Description Default
initial_position array

Initial position. Shape (n_chains, n_dim)

required
training bool
required

Returns:

Name Type Description
chains array
Float[Array, 'n_chains n_dim']

Samples from the posterior. Shape (n_chains, n_local_steps + n_global_steps, n_dim)

Source code in flowMC/strategy/global_tuning.py
 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
def __call__(
    self,
    rng_key: PRNGKeyArray,
    local_sampler: ProposalBase,
    global_sampler: NFProposal,
    initial_position: Float[Array, "n_chains n_dim"],
    data: dict,
) -> tuple[
    PRNGKeyArray,
    Float[Array, "n_chains n_dim"],
    ProposalBase,
    NFProposal,
    PyTree,
]:
    """
    One sampling loop that iterate through the local sampler
    and potentially the global sampler.
    If training is set to True, the loop will also train the normalizing flow model.

    Args:
        initial_position (jnp.array): Initial position. Shape (n_chains, n_dim)
        training (bool, optional):
        Whether to train the normalizing flow model. Defaults to False.

    Returns:
        chains (jnp.array):
        Samples from the posterior. Shape (n_chains, n_local_steps + n_global_steps, n_dim)
    """

    summary = {}
    summary["chains"] = jnp.empty((self.n_chains, 0, self.n_dim))
    summary["log_prob"] = jnp.empty((self.n_chains, 0))
    summary["local_accs"] = jnp.empty((self.n_chains, 0))
    summary["global_accs"] = jnp.empty((self.n_chains, 0))
    summary["loss_vals"] = jnp.empty((0, self.n_epochs))
    current_position = initial_position
    for _ in tqdm(
        range(self.n_loop),
        desc="Global Tuning",
    ):
        rng_key, rng_keys_mcmc = jax.random.split(rng_key)
        rng_keys_mcmc = jax.random.split(rng_keys_mcmc, self.n_chains)
        (
            rng_keys_mcmc,
            positions,
            log_prob,
            local_acceptance,
        ) = local_sampler.sample(
            rng_keys_mcmc,
            self.n_local_steps,
            current_position,
            data,
            verbose=self.verbose,
        )

        summary["chains"] = jnp.append(
            summary["chains"],
            positions[:, :: self.output_thinning],
            axis=1,
        )
        summary["log_prob"] = jnp.append(
            summary["log_prob"],
            log_prob[:, :: self.output_thinning],
            axis=1,
        )

        summary["local_accs"] = jnp.append(
            summary["local_accs"],
            local_acceptance[:, 1 :: self.output_thinning],
            axis=1,
        )

        current_position = summary["chains"][:, -1]

        rng_key, rng_keys_nf = jax.random.split(rng_key)
        positions = summary["chains"][:, :: self.train_thinning]
        chain_size = positions.shape[0] * positions.shape[1]
        if chain_size > self.n_max_examples:
            flat_chain = positions[
                :, -int(self.n_max_examples / self.n_chains) :
            ].reshape(-1, self.n_dim)
        else:
            flat_chain = positions.reshape(-1, self.n_dim)

        if flat_chain.shape[0] < self.n_max_examples:
            # This is to pad the training data to avoid recompilation.
            flat_chain = jnp.repeat(
                flat_chain,
                (self.n_max_examples // flat_chain.shape[0]) + 1,
                axis=0,
            )
            flat_chain = flat_chain[: self.n_max_examples]

        data_mean = jnp.mean(flat_chain, axis=0)
        data_cov = jnp.cov(flat_chain.T)
        global_sampler.model = eqx.tree_at(
            lambda m: m._data_mean, global_sampler.model, data_mean
        )
        global_sampler.model = eqx.tree_at(
            lambda m: m._data_cov, global_sampler.model, data_cov
        )

        (
            rng_keys_nf,
            model,
            optim_state,
            loss_values,
        ) = global_sampler.model.train(
            rng_keys_nf,
            flat_chain,
            self.optim,
            self.optim_state,
            self.n_epochs,
            self.batch_size,
            self.verbose,
        )
        global_sampler.model = model
        self.optim_state = optim_state
        summary["loss_vals"] = jnp.append(
            summary["loss_vals"],
            loss_values.reshape(1, -1),
            axis=0,
        )

        (
            rng_keys_nf,
            nf_chain,
            log_prob,
            global_acceptance,
        ) = global_sampler.sample(
            rng_keys_nf,
            self.n_global_steps,
            current_position,
            data,
            verbose=self.verbose,
        )

        summary["chains"] = jnp.append(
            summary["chains"],
            nf_chain[:, :: self.output_thinning],
            axis=1,
        )
        summary["log_prob"] = jnp.append(
            summary["log_prob"],
            log_prob[:, :: self.output_thinning],
            axis=1,
        )

        summary["global_accs"] = jnp.append(
            summary["global_accs"],
            global_acceptance[:, 1 :: self.output_thinning],
            axis=1,
        )

        current_position = summary["chains"][:, -1]

    return rng_key, current_position, local_sampler, global_sampler, summary