Per-expert linear layer using mlx::gather_mm / mlx::gather_qmm. Stores expert weights as nn.ModuleList of nn.Linear, so quantize_model_() naturally quantizes them. After quantization (or without it), call pack() to stack weights into 3D buffers for the MLX gather custom ops. Args:
| 54 | |
| 55 | |
| 56 | class SwitchLinear(nn.Module): |
| 57 | """Per-expert linear layer using mlx::gather_mm / mlx::gather_qmm. |
| 58 | |
| 59 | Stores expert weights as nn.ModuleList of nn.Linear, so quantize_model_() |
| 60 | naturally quantizes them. After quantization (or without it), call pack() |
| 61 | to stack weights into 3D buffers for the MLX gather custom ops. |
| 62 | |
| 63 | Args: |
| 64 | input_dims: Input feature dimension |
| 65 | output_dims: Output feature dimension |
| 66 | num_experts: Number of experts |
| 67 | bias: Whether to use bias (default: False) |
| 68 | """ |
| 69 | |
| 70 | def __init__( |
| 71 | self, |
| 72 | input_dims: int, |
| 73 | output_dims: int, |
| 74 | num_experts: int, |
| 75 | bias: bool = False, |
| 76 | ): |
| 77 | super().__init__() |
| 78 | self.input_dims = input_dims |
| 79 | self.output_dims = output_dims |
| 80 | self.num_experts = num_experts |
| 81 | self._packed = False |
| 82 | self._is_quantized = False |
| 83 | |
| 84 | self.experts = nn.ModuleList( |
| 85 | [nn.Linear(input_dims, output_dims, bias=bias) for _ in range(num_experts)] |
| 86 | ) |
| 87 | |
| 88 | def pack(self): |
| 89 | """Stack per-expert weights into 3D buffers and delete the ModuleList. |
| 90 | |
| 91 | Must be called after quantization (if any) and before forward/export. |
| 92 | |
| 93 | - Quantized: extracts inner tensors (qdata, scale, zero_point), |
| 94 | stacks into [E, out, in_packed] buffers. Weight layout matches |
| 95 | mlx::gather_qmm's expectations (transpose=True handles transposition). |
| 96 | - Unquantized: stacks weight.data into [E, out, in], then pretransposes |
| 97 | to [E, in, out] so gather_mm receives the correct layout directly |
| 98 | (no runtime transpose needed). |
| 99 | """ |
| 100 | if self._packed: |
| 101 | return |
| 102 | |
| 103 | w0 = self.experts[0].weight |
| 104 | self._is_quantized = hasattr(w0, "qdata") |
| 105 | |
| 106 | if self._is_quantized: |
| 107 | _, metadata = w0.__tensor_flatten__() |
| 108 | self.group_size = metadata["block_size"][-1] |
| 109 | |
| 110 | self.register_buffer( |
| 111 | "qdata", |
| 112 | torch.stack([e.weight.qdata for e in self.experts]), |
| 113 | ) |