File size: 2,545 Bytes
e9a2b5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Minimal mixture-of-experts SwiGLU (SwitchGLU) on mx.gather_mm / gather_qmm.

Vendored instead of importing mlx_lm, because ``import mlx_lm`` pulls in
transformers -> torch, and inference must stay torch-free. Parameter names
match mlx-lm (switch_mlp.{gate,up,down}_proj.weight with shape [E, out, in]).
"""
from __future__ import annotations

import mlx.core as mx
import mlx.nn as nn


class SwitchLinear(nn.Module):
    def __init__(self, in_dims, out_dims, num_experts):
        super().__init__()
        self.weight = mx.zeros((num_experts, out_dims, in_dims))

    def __call__(self, x, idx, sorted_indices=False):
        return mx.gather_mm(x, self.weight.swapaxes(-1, -2), rhs_indices=idx, sorted_indices=sorted_indices)

    def to_quantized(self, group_size=64, bits=4, mode="affine"):
        q = QuantizedSwitchLinear.__new__(QuantizedSwitchLinear)
        nn.Module.__init__(q)
        q.group_size, q.bits = group_size, bits
        q.weight, q.scales, q.biases = mx.quantize(self.weight, group_size, bits)
        return q


class QuantizedSwitchLinear(nn.Module):
    def __init__(self, in_dims, out_dims, num_experts, group_size=64, bits=4):
        super().__init__()
        self.group_size, self.bits = group_size, bits
        w = mx.zeros((num_experts, out_dims, in_dims))
        self.weight, self.scales, self.biases = mx.quantize(w, group_size, bits)

    def __call__(self, x, idx, sorted_indices=False):
        return mx.gather_qmm(x, self.weight, self.scales, self.biases, rhs_indices=idx, transpose=True,
                             group_size=self.group_size, bits=self.bits, sorted_indices=sorted_indices)


class SwitchGLU(nn.Module):
    def __init__(self, input_dims, hidden_dims, num_experts):
        super().__init__()
        self.gate_proj = SwitchLinear(input_dims, hidden_dims, num_experts)
        self.up_proj = SwitchLinear(input_dims, hidden_dims, num_experts)
        self.down_proj = SwitchLinear(hidden_dims, input_dims, num_experts)

    def __call__(self, x, indices):
        """x: [N, D]; indices: [N, k] -> [N, k, D]."""
        N, k = indices.shape
        # sort token-expert pairs by expert for contiguous weight access
        flat = indices.flatten()
        order = mx.argsort(flat)
        inv = mx.argsort(order)
        xs = mx.expand_dims(x, -2)[order // k]  # [N*k, 1, D]
        idx = flat[order]
        h = nn.silu(self.gate_proj(xs, idx, True)) * self.up_proj(xs, idx, True)
        y = self.down_proj(h, idx, True)  # [N*k, 1, D]
        return y[inv].reshape(N, k, -1)