File size: 14,049 Bytes
d18db74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
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
import functools
import gc
import glob
import json
import os
import pickle
import time
from typing import Any, Dict, Mapping, Sequence

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
import numpy as np
import optax

nonpytree_field = functools.partial(flax.struct.field, pytree_node=False)


class ModuleDict(nn.Module):
    """A dictionary of modules.

    This allows sharing parameters between modules and provides a convenient way to access them.

    Attributes:
        modules: Dictionary of modules.
    """

    modules: Dict[str, nn.Module]

    @nn.compact
    def __call__(self, *args, name=None, **kwargs):
        """Forward pass.

        For initialization, call with `name=None` and provide the arguments for each module in `kwargs`.
        Otherwise, call with `name=<module_name>` and provide the arguments for that module.
        """
        if name is None:
            if kwargs.keys() != self.modules.keys():
                raise ValueError(
                    f'When `name` is not specified, kwargs must contain the arguments for each module. '
                    f'Got kwargs keys {kwargs.keys()} but module keys {self.modules.keys()}'
                )
            out = {}
            for key, value in kwargs.items():
                if isinstance(value, Mapping):
                    out[key] = self.modules[key](**value)
                elif isinstance(value, Sequence):
                    out[key] = self.modules[key](*value)
                else:
                    out[key] = self.modules[key](value)
            return out

        return self.modules[name](*args, **kwargs)


class TrainState(flax.struct.PyTreeNode):
    """Custom train state for models.

    Attributes:
        step: Counter to keep track of the training steps. It is incremented by 1 after each `apply_gradients` call.
        apply_fn: Apply function of the model.
        model_def: Model definition.
        params: Parameters of the model.
        tx: optax optimizer.
        opt_state: Optimizer state.
    """

    step: int
    apply_fn: Any = nonpytree_field()
    model_def: Any = nonpytree_field()
    params: Any
    tx: Any = nonpytree_field()
    opt_state: Any

    @classmethod
    def create(cls, model_def, params, tx=None, **kwargs):
        """Create a new train state."""
        if tx is not None:
            opt_state = tx.init(params)
        else:
            opt_state = None

        return cls(
            step=1,
            apply_fn=model_def.apply,
            model_def=model_def,
            params=params,
            tx=tx,
            opt_state=opt_state,
            **kwargs,
        )

    def __call__(self, *args, params=None, method=None, **kwargs):
        """Forward pass.

        When `params` is not provided, it uses the stored parameters.

        The typical use case is to set `params` to `None` when you want to *stop* the gradients, and to pass the current
        traced parameters when you want to flow the gradients. In other words, the default behavior is to stop the
        gradients, and you need to explicitly provide the parameters to flow the gradients.

        Args:
            *args: Arguments to pass to the model.
            params: Parameters to use for the forward pass. If `None`, it uses the stored parameters, without flowing
                the gradients.
            method: Method to call in the model. If `None`, it uses the default `apply` method.
            **kwargs: Keyword arguments to pass to the model.
        """
        if params is None:
            params = self.params
        variables = {'params': params}
        if method is not None:
            method_name = getattr(self.model_def, method)
        else:
            method_name = None

        return self.apply_fn(variables, *args, method=method_name, **kwargs)

    def select(self, name):
        """Helper function to select a module from a `ModuleDict`."""
        return functools.partial(self, name=name)

    def apply_gradients(self, grads, **kwargs):
        """Apply the gradients and return the updated state."""
        updates, new_opt_state = self.tx.update(grads, self.opt_state, self.params)
        new_params = optax.apply_updates(self.params, updates)

        return self.replace(
            step=self.step + 1,
            params=new_params,
            opt_state=new_opt_state,
            **kwargs,
        )

    def apply_loss_fn(self, loss_fn):
        """Apply the loss function and return the updated state and info.

        It additionally computes the gradient statistics and adds them to the dictionary.
        """
        grads, info = jax.grad(loss_fn, has_aux=True)(self.params)

        grad_max = jax.tree_util.tree_map(jnp.max, grads)
        grad_min = jax.tree_util.tree_map(jnp.min, grads)
        grad_norm = jax.tree_util.tree_map(jnp.linalg.norm, grads)

        grad_max_flat = jnp.concatenate([jnp.reshape(x, -1) for x in jax.tree_util.tree_leaves(grad_max)], axis=0)
        grad_min_flat = jnp.concatenate([jnp.reshape(x, -1) for x in jax.tree_util.tree_leaves(grad_min)], axis=0)
        grad_norm_flat = jnp.concatenate([jnp.reshape(x, -1) for x in jax.tree_util.tree_leaves(grad_norm)], axis=0)

        final_grad_max = jnp.max(grad_max_flat)
        final_grad_min = jnp.min(grad_min_flat)
        final_grad_norm = jnp.linalg.norm(grad_norm_flat, ord=1)

        info.update(
            {
                'grad/max': final_grad_max,
                'grad/min': final_grad_min,
                'grad/norm': final_grad_norm,
            }
        )

        return self.apply_gradients(grads=grads), info


def save_agent(agent, save_dir, epoch, name=None):
    """Save the agent to a file, atomically.

    Args:
        agent: Agent.
        save_dir: Directory to save the agent.
        epoch: Epoch number.
        name: Override the file name (used for the rolling resume checkpoint).

    The write goes to a temporary file that is then renamed. A checkpoint is multiple GB and jobs on this
    cluster are killed mid-write; a half-written params_*.pkl is the worst possible failure, because resume
    picks the newest checkpoint and would then crash on every relaunch.
    """

    save_dict = dict(
        agent=flax.serialization.to_state_dict(agent),
    )
    save_path = os.path.join(save_dir, name if name is not None else f'params_{epoch}.pkl')
    tmp_path = f'{save_path}.tmp{os.getpid()}'
    with open(tmp_path, 'wb') as f:
        pickle.dump(save_dict, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp_path, save_path)

    print(f'Saved to {save_path}')


LATEST_PARAMS = 'params_latest.pkl'
RESUME_STATE = 'resume.json'


def save_resume_checkpoint(agent, save_dir, step):
    """Overwrite the rolling resume checkpoint (params_latest.pkl + resume.json).

    Archival checkpoints (params_<step>.pkl) exist to be re-evaluated later, so they sit on the evaluation
    grid and are kept. This one exists only so a killed job restarts near where it died, so it is written
    far more often and overwritten in place -- one file per run, not one per save.
    """
    save_agent(agent, save_dir, step, name=LATEST_PARAMS)
    tmp = os.path.join(save_dir, RESUME_STATE + '.tmp')
    with open(tmp, 'w') as f:
        json.dump(dict(step=int(step), time=time.time()), f)
    os.replace(tmp, os.path.join(save_dir, RESUME_STATE))


def _load_state_dict_host(path):
    """Unpickle a checkpoint's state dict into HOST memory, never the accelerator.

    ``jax.Array.__reduce__`` reconstructs through ``device_put(np_value)`` with no device, so a plain
    ``pickle.load`` stages every leaf on the default device. That is fatal on resume: the freshly
    initialised agent is already resident, so a 4096x4 arm asks the card for a second ~3 GB copy of
    itself and dies with RESOURCE_EXHAUSTED inside ``pickle.load`` (the packed waves run two workers
    per card at mem_frac 0.45). Pinning the default device to CPU for the unpickle keeps the
    checkpoint in host RAM; the caller then frees the template's buffers before copying it back, so
    peak device memory over the whole restore is one copy of the model instead of two.
    """
    with jax.default_device(jax.devices('cpu')[0]):
        with open(path, 'rb') as f:
            load_dict = pickle.load(f)
    # Uncommitted CPU arrays would be re-transferred on every jitted call; hand back plain numpy so the
    # tree is unambiguously host-side until we put it back deliberately.
    return jax.tree_util.tree_map(np.asarray, load_dict['agent'])


def _reset_opt_state(agent, state_dict):
    """Replace every saved ``opt_state`` subtree with the TARGET's freshly-initialized one.

    A fork onto a DIFFERENT optax structure cannot restore the saved optimizer state. Concretely:
    a parent trained with `occ_lr_mult == actor_lr_mult == 1.0` takes rsm.py's single
    `optax.adam` branch, whose state serializes as a plain 2-tuple ({'0','1'}); a child that
    sets `occ_lr_mult != 1.0` trips the `actor_knobs` test and builds `optax.multi_transform`,
    whose state is `MultiTransformState(inner_states=...)`. `from_state_dict` then raises

        ValueError: The field names of the state dict and the named tuple do not match,
                    got {'0', '1'} and {'inner_states'} at path ./network/opt_state

    and the arm dies at restore having trained ZERO steps (this killed all 10 arms of wave ocOL).
    The PARAMS are unaffected -- only Adam's accumulators are structurally incompatible.

    Dropping them gives a COLD Adam restart (m = v = 0), which is NOT free: with zero
    accumulators the first bias-corrected update is ~lr * sign(g) on every parameter, a full-size
    kick on an otherwise converged network. That transient is real, so every arm in a wave that
    uses this path -- INCLUDING its control -- must take the same path, or the transient is
    attributed to whatever else the arms differ in.
    """
    fresh = flax.serialization.to_state_dict(agent)

    def walk(loaded, tgt):
        for k, v in loaded.items():
            if k == 'opt_state' and k in tgt:
                loaded[k] = tgt[k]
            elif isinstance(v, dict) and isinstance(tgt.get(k), dict):
                walk(v, tgt[k])

    walk(state_dict, fresh)
    return state_dict


def _fill_missing_opt_state(agent, state_dict):
    """Re-insert any ``opt_state`` subtree the checkpoint does NOT carry, from the fresh target.

    ``tools/strip_opt_state.py`` rewrites archival ``params_<step>.pkl`` without their Adam
    accumulators: ``opt_state`` is two thirds of every checkpoint (2.02 GB of a 3.03 GB file) and is
    read only when RESUMING training. A re-scored grid point is only ever rolled out, so for
    ``tools/final_eval.py`` / ``tools/eval_checkpoint.py`` the accumulators are dead weight.

    ``flax.serialization.from_state_dict`` matches key sets exactly, so a stripped file otherwise dies
    with ``ValueError: target dict contains keys {'opt_state'} which are not present in state dict``.
    This differs from ``_reset_opt_state``, which handles a key that is PRESENT but structurally
    incompatible; here the key is ABSENT. Both end at the same place -- the target's freshly
    initialised accumulators -- so a stripped checkpoint restores as a COLD Adam start. That is
    exactly why the stripper refuses to touch a seed's highest-step checkpoint: resuming from a
    stripped file would be a real behaviour change, while re-evaluating one cannot be.

    Returns the state dict unchanged when nothing is missing, so the 8000+ unstripped checkpoints
    take a byte-identical path through the loader.
    """
    fresh = flax.serialization.to_state_dict(agent)

    def walk(loaded, tgt):
        if not isinstance(loaded, dict) or not isinstance(tgt, dict):
            return
        for k, v in tgt.items():
            if k not in loaded:
                if k == 'opt_state':
                    loaded[k] = v
                continue
            walk(loaded[k], v)

    walk(state_dict, fresh)
    return state_dict


def _merge_state_dict(agent, state_dict, path):
    """Load a host-side state dict into ``agent`` and return it on the default device."""
    # OC_RESTORE_PARAMS_ONLY=1 keeps the target's own fresh opt_state instead of the saved one.
    # Required for any fork that changes occ_lr_mult / actor_lr_mult / actor_grad_clip /
    # actor_adam_b2 away from the parent's, because those switch the optimizer STRUCTURE.
    if os.environ.get('OC_RESTORE_PARAMS_ONLY', '') not in ('', '0'):
        state_dict = _reset_opt_state(agent, state_dict)
        print('OC_RESTORE_PARAMS_ONLY: kept fresh opt_state (COLD Adam restart)', flush=True)
    # A stripped archival checkpoint carries params but no opt_state; refill it so the key sets match.
    state_dict = _fill_missing_opt_state(agent, state_dict)
    agent = flax.serialization.from_state_dict(agent, state_dict)  # numpy leaves; template buffers now dead
    del state_dict
    gc.collect()  # actually release the template's device buffers before allocating the restored ones
    agent = jax.tree_util.tree_map(lambda x: jax.device_put(x) if isinstance(x, np.ndarray) else x, agent)
    print(f'Restored from {path}', flush=True)
    return agent


def restore_agent_file(agent, path):
    """Restore the agent from an exact .pkl path (used by the resume launcher, which picks the file)."""
    return _merge_state_dict(agent, _load_state_dict_host(path), path)


def restore_agent(agent, restore_path, restore_epoch):
    """Restore the agent from a file.

    Args:
        agent: Agent.
        restore_path: Path to the directory containing the saved agent.
        restore_epoch: Epoch number.
    """
    candidates = glob.glob(restore_path)

    assert len(candidates) == 1, f'Found {len(candidates)} candidates: {candidates}'

    restore_path = candidates[0] + f'/params_{restore_epoch}.pkl'

    return _merge_state_dict(agent, _load_state_dict_host(restore_path), restore_path)