|
| 1 | +import pytensor.tensor as pt |
| 2 | + |
| 3 | +from pytensor_ml.activations import GELU, Activation |
| 4 | +from pytensor_ml.attention import MultiheadAttention |
| 5 | +from pytensor_ml.layers import Dropout, Layer, LayerNorm, Linear |
| 6 | + |
| 7 | + |
| 8 | +def _identity(x: pt.TensorVariable) -> pt.TensorVariable: |
| 9 | + return x |
| 10 | + |
| 11 | + |
| 12 | +class FeedForward(Layer): |
| 13 | + r""" |
| 14 | + Position-wise feed-forward network. |
| 15 | +
|
| 16 | + Apply two linear layers with an activation between them, expanding to a wider hidden dimension and |
| 17 | + projecting back: |
| 18 | +
|
| 19 | + .. math:: |
| 20 | +
|
| 21 | + \mathrm{FFN}(x) = \phi(x W_1 + b_1) W_2 + b_2, |
| 22 | +
|
| 23 | + where :math:`\phi` is the activation. This is the per-token MLP used in transformer blocks, but it is |
| 24 | + a standalone layer usable anywhere a widening-then-narrowing MLP is wanted. |
| 25 | +
|
| 26 | + Parameters |
| 27 | + ---------- |
| 28 | + name : str or None |
| 29 | + Name prefix for the layer's parameters. Defaults to "FeedForward" when None. |
| 30 | + d_model : int |
| 31 | + Input and output dimension. |
| 32 | + hidden_dim : int, optional |
| 33 | + Width of the hidden layer. Overrides ``mlp_ratio`` when given; otherwise computed as |
| 34 | + ``mlp_ratio * d_model``. |
| 35 | + mlp_ratio : int, optional |
| 36 | + Hidden-to-model dimension ratio used when ``hidden_dim`` is not given. Default is 4. |
| 37 | + activation : Activation, optional |
| 38 | + Activation applied to the hidden layer. Default is :class:`GELU`. |
| 39 | + bias : bool, optional |
| 40 | + Include bias terms in both linear layers. Default is True. |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__( |
| 44 | + self, |
| 45 | + name: str | None, |
| 46 | + d_model: int, |
| 47 | + hidden_dim: int | None = None, |
| 48 | + mlp_ratio: int = 4, |
| 49 | + activation: Activation | None = None, |
| 50 | + bias: bool = True, |
| 51 | + ): |
| 52 | + self.name = name if name else "FeedForward" |
| 53 | + self.d_model = d_model |
| 54 | + self.hidden_dim = hidden_dim if hidden_dim is not None else mlp_ratio * d_model |
| 55 | + self.activation = activation if activation is not None else GELU() |
| 56 | + |
| 57 | + self.fc_in = Linear(f"{self.name}_fc_in", d_model, self.hidden_dim, bias) |
| 58 | + self.fc_out = Linear(f"{self.name}_fc_out", self.hidden_dim, d_model, bias) |
| 59 | + |
| 60 | + def __call__(self, x: pt.TensorLike) -> pt.TensorVariable: |
| 61 | + x = pt.as_tensor(x) |
| 62 | + hidden = self.activation(self.fc_in(x)) |
| 63 | + out = self.fc_out(hidden) |
| 64 | + out.name = f"{self.name}_output" |
| 65 | + return out |
| 66 | + |
| 67 | + |
| 68 | +class TransformerBlock(Layer): |
| 69 | + r""" |
| 70 | + A transformer block: multi-head self-attention and a feed-forward network, each wrapped in a |
| 71 | + residual connection around a layer-normalized sublayer. |
| 72 | +
|
| 73 | + With ``norm_first=True`` (pre-norm, the modern default) the block computes |
| 74 | +
|
| 75 | + .. math:: |
| 76 | +
|
| 77 | + x &= x + \mathrm{Attn}(\mathrm{LN}_1(x)) \\ |
| 78 | + x &= x + \mathrm{FFN}(\mathrm{LN}_2(x)), |
| 79 | +
|
| 80 | + and with ``norm_first=False`` (post-norm, the original formulation) the normalization is applied to |
| 81 | + the residual sum instead. Set ``is_causal=True`` for a decoder block, leave it False for an encoder |
| 82 | + block; ``n_kv_head`` enables grouped-query attention. |
| 83 | +
|
| 84 | + Parameters |
| 85 | + ---------- |
| 86 | + name : str or None |
| 87 | + Name prefix for the block's parameters. Defaults to "TransformerBlock" when None. |
| 88 | + d_model : int |
| 89 | + Model dimension of the input and output. |
| 90 | + n_head : int |
| 91 | + Number of attention heads. Must divide ``d_model`` evenly. |
| 92 | + mlp_ratio : int, optional |
| 93 | + Feed-forward hidden-to-model dimension ratio. Default is 4. |
| 94 | + activation : Activation, optional |
| 95 | + Activation used in the feed-forward network. Default is :class:`GELU`. |
| 96 | + norm_first : bool, optional |
| 97 | + Normalize each sublayer's input (pre-norm) rather than its residual sum (post-norm). Default is |
| 98 | + True. |
| 99 | + dropout : float, optional |
| 100 | + Dropout probability applied to each sublayer's output before the residual add. Dropout is omitted |
| 101 | + from the graph entirely when 0. Default is 0.0. |
| 102 | + bias : bool, optional |
| 103 | + Include bias terms in the attention and feed-forward projections. Default is True. |
| 104 | + is_causal : bool, optional |
| 105 | + Apply a causal mask in the self-attention. Default is False. |
| 106 | + n_kv_head : int, optional |
| 107 | + Number of key/value heads for grouped-query attention. Defaults to ``n_head``. |
| 108 | + epsilon : float, optional |
| 109 | + Constant added to the layer-norm variance for numerical stability. Default is 1e-5. |
| 110 | + """ |
| 111 | + |
| 112 | + def __init__( |
| 113 | + self, |
| 114 | + name: str | None, |
| 115 | + d_model: int, |
| 116 | + n_head: int, |
| 117 | + *, |
| 118 | + mlp_ratio: int = 4, |
| 119 | + activation: Activation | None = None, |
| 120 | + norm_first: bool = True, |
| 121 | + dropout: float = 0.0, |
| 122 | + bias: bool = True, |
| 123 | + is_causal: bool = False, |
| 124 | + n_kv_head: int | None = None, |
| 125 | + epsilon: float = 1e-5, |
| 126 | + ): |
| 127 | + self.name = name if name else "TransformerBlock" |
| 128 | + self.d_model = d_model |
| 129 | + self.norm_first = norm_first |
| 130 | + |
| 131 | + self.norm1 = LayerNorm(f"{self.name}_norm1", n_in=d_model, epsilon=epsilon) |
| 132 | + self.norm2 = LayerNorm(f"{self.name}_norm2", n_in=d_model, epsilon=epsilon) |
| 133 | + self.attn = MultiheadAttention( |
| 134 | + f"{self.name}_attn", |
| 135 | + d_model, |
| 136 | + n_head, |
| 137 | + n_kv_head=n_kv_head, |
| 138 | + bias=bias, |
| 139 | + is_causal=is_causal, |
| 140 | + ) |
| 141 | + self.ff = FeedForward( |
| 142 | + f"{self.name}_ff", d_model, mlp_ratio=mlp_ratio, activation=activation, bias=bias |
| 143 | + ) |
| 144 | + self.attn_dropout = ( |
| 145 | + Dropout(f"{self.name}_attn_dropout", p=dropout) if dropout > 0 else _identity |
| 146 | + ) |
| 147 | + self.ff_dropout = ( |
| 148 | + Dropout(f"{self.name}_ff_dropout", p=dropout) if dropout > 0 else _identity |
| 149 | + ) |
| 150 | + |
| 151 | + def __call__(self, x: pt.TensorLike, mask: pt.TensorLike | None = None) -> pt.TensorVariable: |
| 152 | + x = pt.as_tensor(x) |
| 153 | + if mask is not None: |
| 154 | + mask = pt.as_tensor(mask) |
| 155 | + |
| 156 | + if self.norm_first: |
| 157 | + x = x + self.attn_dropout(self.attn(self.norm1(x), mask=mask)) |
| 158 | + x = x + self.ff_dropout(self.ff(self.norm2(x))) |
| 159 | + else: |
| 160 | + x = self.norm1(x + self.attn_dropout(self.attn(x, mask=mask))) |
| 161 | + x = self.norm2(x + self.ff_dropout(self.ff(x))) |
| 162 | + |
| 163 | + x.name = f"{self.name}_output" # type: ignore[union-attr] |
| 164 | + return x # type: ignore[return-value] |
| 165 | + |
| 166 | + |
| 167 | +__all__ = [ |
| 168 | + "FeedForward", |
| 169 | + "TransformerBlock", |
| 170 | +] |
0 commit comments