-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructures.py
executable file
·46 lines (35 loc) · 1.11 KB
/
structures.py
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
import jax.numpy as jnp
import numpy as np
def pack(d: dict) -> jnp.array:
"""
It packs dictionary into a 1-dimensional JAX array.
Parameters
----------
d: dict
Dictionary to pack.
Returns
-------
a: jnp.array
1-dimensional JAX array corresponding to `d`.
"""
return jnp.concatenate([jnp.ravel(v) for v in d.values()])
def unpack(a: jnp.array, d: dict) -> dict:
"""
It unpacks a 1-dimensional JAX array into a dictionary with keys and value shapes like in `d`.
Parameters
----------
a: jnp.array
Array to unpack.
d: dict
The unpacked version of `a` should have the same keys and value shapes as this dictionary.
Returns
-------
unpacked: dict
Dictionary corresponding to `d`-like unpacked version of `a`.
"""
keys, values = [], []
for k, v in d.items():
keys.append(k), values.append(v)
shapes = [v.shape for v in values]
cum_sizes = np.cumsum([0] + [v.size for v in values]).tolist()
return {keys[i]: a[cum_sizes[i]:cum_sizes[i+1]].reshape(shapes[i]) for i in range(len(d))}