|
| 1 | +from collections.abc import Callable |
| 2 | + |
| 3 | +from jaxtyping import PyTree |
| 4 | + |
| 5 | +from .._eval_shape import filter_eval_shape |
| 6 | +from .._module import Module |
| 7 | +from .._tree import tree_at, tree_equal |
| 8 | + |
| 9 | + |
| 10 | +class SharedNode: |
| 11 | + """Placeholder value for nodes that have been removed by `eqx.nn.Shared`.""" |
| 12 | + |
| 13 | + def __repr__(self): |
| 14 | + return "SharedNode" |
| 15 | + |
| 16 | + |
| 17 | +class Shared(Module): |
| 18 | + """Used to tie together multiple nodes across a PyTree. |
| 19 | +
|
| 20 | + Note that Equinox modules are Py**Trees** -- so the same layer, appearing in two |
| 21 | + difference parts of the tree, will be treated as two copies of this layer. For |
| 22 | + example, |
| 23 | + ```python |
| 24 | + class SubModel(eqx.Module): |
| 25 | + linear: eqx.nn.Linear |
| 26 | +
|
| 27 | + class Model(eqx.Module): |
| 28 | + linear: eqx.nn.Linear |
| 29 | + submodel: SubModel |
| 30 | +
|
| 31 | + def __init__(self): |
| 32 | + linear = eqx.nn.Linear(...) |
| 33 | + self.linear = linear |
| 34 | + self.submodel = SubModel(linear) |
| 35 | + ``` |
| 36 | + is used to declare `model.linear` and `model.submodel.linear` as two separate |
| 37 | + layers. They will start with the same initial parameter values, and then update |
| 38 | + independently during training. |
| 39 | +
|
| 40 | + For when we really do want to share layers or weights across different parts of a |
| 41 | + model, then `eqx.nn.Shared` exists as a way to easily express this in the PyTree |
| 42 | + paradigm. |
| 43 | +
|
| 44 | + !!! Example |
| 45 | +
|
| 46 | + It is common in many language models to have an initial embedding matrix at the |
| 47 | + start, and then to reuse this as the weight of the final linear transformation. |
| 48 | +
|
| 49 | + ```python |
| 50 | + import equinox as eqx |
| 51 | + import jax.numpy as jnp |
| 52 | + from jaxtyping import Array, Int |
| 53 | +
|
| 54 | + class LanguageModel(eqx.Module): |
| 55 | + shared: eqx.nn.Shared |
| 56 | +
|
| 57 | + def __init__(self): |
| 58 | + embedding = eqx.nn.Embedding(...) |
| 59 | + linear = eqx.nn.Linear(...) |
| 60 | + # These two weights will now be tied together. |
| 61 | + where = lambda embed_and_lin: embed_and_lin[1].weight |
| 62 | + get = lambda embed_and_lin: embed_and_lin[0].weight |
| 63 | + self.shared = eqx.nn.Shared((embedding, linear), where, get) |
| 64 | +
|
| 65 | + def __call__(self, tokens: Int[Array, "sequence"]): |
| 66 | + # Expand back out so we can evaluate these layers. |
| 67 | + embedding, linear = self.shared() |
| 68 | + assert embedding.weight is linear.weight # same parameter! |
| 69 | + # Now go ahead and evaluate your language model. |
| 70 | + values = jax.vmap(embedding)(tokens) |
| 71 | + ... # other layers, probably |
| 72 | + return jax.vmap(linear)(values) |
| 73 | + ``` |
| 74 | +
|
| 75 | + _(Side note: you will sometimes see some authors referring to transposing |
| 76 | + the embedding matrix prior to the final linear layer. This is because some |
| 77 | + other libraries store the weight matrices of linear layers the other way |
| 78 | + around. If that had been necessary here then we could have done it with |
| 79 | + `get = lambda embed_and_lin: jnp.transpose(embed_and_lin[0].weight)`.)_ |
| 80 | +
|
| 81 | + """ |
| 82 | + |
| 83 | + pytree: PyTree |
| 84 | + where: Callable |
| 85 | + get: Callable |
| 86 | + |
| 87 | + def __init__(self, pytree: PyTree, where: Callable, get: Callable): |
| 88 | + """**Arguments:** |
| 89 | +
|
| 90 | + - `pytree`: The PyTree to share some nodes across. |
| 91 | + - `where`: a function specifying either a single node, or a sequence of nodes, |
| 92 | + as with `eqx.tree_at(where, pytree, ...)`. |
| 93 | + - `get`: a function, which when evaluated on `pytree`, returns either a single |
| 94 | + value (if `where` does), or a sequence of values (if `where` does, and in |
| 95 | + this case this must be a sequence of the same length as `where`). |
| 96 | +
|
| 97 | + The node(s) of `get(pytree)` and the corresponding value(s) of `where(pytree)` |
| 98 | + will be tied together. |
| 99 | +
|
| 100 | + !!! info |
| 101 | +
|
| 102 | + To explain how this works. The implementation is just: |
| 103 | + ```python |
| 104 | + class Shared(eqx.Module): |
| 105 | + pytree: PyTree |
| 106 | + where: Callable |
| 107 | + get: Callable |
| 108 | +
|
| 109 | + def __init__(self, pytree, where, get): |
| 110 | + # `0` is just some dummy value |
| 111 | + self.pytree = eqx.tree_at(where, pytree, replace_fn=lambda _: 0) |
| 112 | + self.where = where |
| 113 | + self.get = get |
| 114 | +
|
| 115 | + def __call__(self): |
| 116 | + return eqx.tree_at(self.where, self.pytree, self.get(self.pytree)) |
| 117 | + ``` |
| 118 | + so that at `__init__` time, the duplicate nodes specified in `where` are |
| 119 | + removed from the PyTree. We no longer have a separate copy updating during |
| 120 | + training. |
| 121 | +
|
| 122 | + And then at `__call__` time, references to the values returned by |
| 123 | + `get(pytree)` are put in their place. We end up with a pytree of the same |
| 124 | + structure as what we started with, which we can now use (evaluate as a |
| 125 | + layer etc.) as normal. |
| 126 | +
|
| 127 | + !!! tip |
| 128 | +
|
| 129 | + If you need to apply any transform (e.g. transposing a matrix), then this |
| 130 | + can be done as part of `get`. For example, |
| 131 | + `get = lambda pair: jnp.transpose(pair[1].weight)`. |
| 132 | + """ |
| 133 | + |
| 134 | + source_struct = filter_eval_shape(get, pytree) |
| 135 | + dest_struct = filter_eval_shape(where, pytree) |
| 136 | + if tree_equal(source_struct, dest_struct) is not True: |
| 137 | + raise ValueError( |
| 138 | + "Every node being shared together must have the same pytree " |
| 139 | + "structure, shape+dtype of arrays, etc., as each other. Got:\n" |
| 140 | + f"{source_struct}\n" |
| 141 | + "and\n" |
| 142 | + f"{dest_struct}" |
| 143 | + ) |
| 144 | + self.pytree = tree_at(where, pytree, replace_fn=lambda _: SharedNode()) |
| 145 | + self.where = where |
| 146 | + self.get = get |
| 147 | + |
| 148 | + def __call__(self): |
| 149 | + """**Arguments:** |
| 150 | +
|
| 151 | + None. |
| 152 | +
|
| 153 | + **Returns:** |
| 154 | +
|
| 155 | + A PyTree of the same structure as the original `pytree`, with `get(pytree)` in |
| 156 | + the place of the nodes at `where(pytree)`. |
| 157 | + """ |
| 158 | + return tree_at(self.where, self.pytree, self.get(self.pytree)) |
0 commit comments