import mlx.core as mx import mlx.nn as nn import math class RelPositionalEncoding(nn.Module): """ Relative positional encoding for Transformer-XL """ def __init__(self, d_model, max_len=5000): super().__init__() self.d_model = d_model def __call__(self, x): # x is (batch, time, d_model) # return positional embeddings for length `time * 2 - 1` # Transformer-XL relative positions b, t, d = x.shape # Positions go from t - 1 down to -t + 1, matching PyTorch's: # positions = torch.arange(length - 1, -length, -1) positions = mx.arange(t - 1, -t, -1, dtype=mx.float32)[:, None] div_term = mx.exp(mx.arange(0, self.d_model, 2, dtype=mx.float32) * -(math.log(10000.0) / self.d_model)) sin_part = mx.sin(positions * div_term) cos_part = mx.cos(positions * div_term) # Interleave sin and cos pe = mx.stack([sin_part, cos_part], axis=-1).reshape(2 * t - 1, self.d_model) pos_emb = mx.expand_dims(pe, axis=0) return x, pos_emb class RelPositionMultiHeadAttention(nn.Module): """ MLX Translation of NVIDIA NeMo RelPositionMultiHeadAttention """ def __init__(self, n_head, n_feat, dropout_rate=0.0): super().__init__() assert n_feat % n_head == 0 self.n_head = n_head self.d_k = n_feat // n_head self.s_d_k = math.sqrt(self.d_k) self.linear_q = nn.Linear(n_feat, n_feat) self.linear_k = nn.Linear(n_feat, n_feat) self.linear_v = nn.Linear(n_feat, n_feat) self.linear_out = nn.Linear(n_feat, n_feat) self.linear_pos = nn.Linear(n_feat, n_feat, bias=False) # Learnable biases self.pos_bias_u = mx.zeros((self.n_head, self.d_k)) self.pos_bias_v = mx.zeros((self.n_head, self.d_k)) self.dropout = nn.Dropout(dropout_rate) def rel_shift(self, x): """ x: (batch, n_head, time1, time2) where time2 = 2 * time1 - 1 """ b, h, t1, t2 = x.shape # Pad left by 1 column x = mx.pad(x, ((0, 0), (0, 0), (0, 0), (1, 0))) x = mx.reshape(x, (b, h, t2 + 1, t1)) # Drop first row x = x[:, :, 1:, :] x = mx.reshape(x, (b, h, t1, t2)) return x def __call__(self, query, key, value, mask=None, pos_emb=None): """ query: (batch, time1, d_model) key: (batch, time2, d_model) value: (batch, time2, d_model) pos_emb: (1, time2 * 2 - 1, d_model) """ b = query.shape[0] q = mx.reshape(self.linear_q(query), (b, -1, self.n_head, self.d_k)).transpose(0, 2, 1, 3) k = mx.reshape(self.linear_k(key), (b, -1, self.n_head, self.d_k)).transpose(0, 2, 1, 3) v = mx.reshape(self.linear_v(value), (b, -1, self.n_head, self.d_k)).transpose(0, 2, 1, 3) # Positional encodings if pos_emb is None: raise ValueError("pos_emb must be provided for RelPositionMultiHeadAttention") p = mx.reshape(self.linear_pos(pos_emb), (pos_emb.shape[0], -1, self.n_head, self.d_k)).transpose(0, 2, 1, 3) q_with_bias_u = q + mx.expand_dims(self.pos_bias_u, axis=(0, 2)) q_with_bias_v = q + mx.expand_dims(self.pos_bias_v, axis=(0, 2)) # Matrix AC: query dot key # (b, head, time1, d_k) x (b, head, d_k, time2) -> (b, head, time1, time2) matrix_ac = mx.matmul(q_with_bias_u, k.transpose(0, 1, 3, 2)) # Matrix BD: query dot pos_emb matrix_bd = mx.matmul(q_with_bias_v, p.transpose(0, 1, 3, 2)) matrix_bd = self.rel_shift(matrix_bd) # Drop extra elements matrix_bd = matrix_bd[:, :, :, :matrix_ac.shape[-1]] scores = (matrix_ac + matrix_bd) / self.s_d_k if mask is not None: # Mask should be (b, 1, time1, time2) scores = mx.where(mask, -1e9, scores) attn = mx.softmax(scores, axis=-1) attn = self.dropout(attn) x = mx.matmul(attn, v) # (b, head, time1, d_k) x = x.transpose(0, 2, 1, 3).reshape(b, -1, self.n_head * self.d_k) return self.linear_out(x)