| 1 | import math |
| 2 | from typing import Union |
| 3 | |
| 4 | import mlx.core as mx |
| 5 | import mlx.nn as nn |
| 6 | |
| 7 | |
| 8 | class LoRaLayer(nn.Module): |
| 9 | def __init__( |
| 10 | self, |
| 11 | linear: Union[nn.Linear, nn.QuantizedLinear], |
| 12 | rank: int, |
| 13 | alpha: float = 0.1, |
| 14 | dropout: float = 0.0, |
| 15 | ): |
| 16 | super().__init__() |
| 17 | |
| 18 | self.original_layer = linear |
| 19 | |
| 20 | self.dropout = nn.Dropout(p=dropout) |
| 21 | |
| 22 | output_dims, input_dims = linear.weight.shape |
| 23 | if isinstance(linear, nn.QuantizedLinear): |
| 24 | input_dims *= 32 // linear.bits |
| 25 | |
| 26 | std_dev = 1 / math.sqrt(rank) |
| 27 | |
| 28 | self.A = mx.random.uniform( |
| 29 | low=-std_dev, |
| 30 | high=std_dev, |
| 31 | shape=(input_dims, rank), |
| 32 | ) |
| 33 | self.B = mx.zeros((rank, output_dims)) |
| 34 | self.alpha = alpha |
| 35 | |
| 36 | def __call__(self, x): |
| 37 | y = self.original_layer(x) |
| 38 | lora_update = (self.dropout(x) @ self.A) @ self.B |
| 39 | return y + (self.alpha * lora_update).astype(x.dtype) |
| 40 | |
| 41 | |
| 42 | def replace_lora_with_linear(model): |
| 43 | for i, layer in enumerate(model.layers): |
| 44 | if isinstance(layer, LoRaLayer): |
| 45 | # Compute the final merged weight |
| 46 | lora_update = layer.alpha * (layer.A @ layer.B) |
| 47 | updated_weight = layer.original_layer.weight + lora_update |
| 48 | use_bias = layer.original_layer.bias is not None |
| 49 | |
| 50 | updated_bias = layer.original_layer.bias |
| 51 | |
| 52 | # Create a new Linear layer with the updated parameters |
| 53 | new_linear_layer = nn.Linear( |
| 54 | updated_weight.size(1), updated_weight.size(0), bias=use_bias |
| 55 | ) |
| 56 | |
| 57 | new_linear_layer.weight = updated_weight |
| 58 | |
| 59 | if use_bias: |
| 60 | new_linear_layer.bias = updated_bias |
| 61 | |
| 62 | if isinstance(layer.original_layer, nn.QuantizedLinear): |
| 63 | new_linear_layer = nn.QuantizedLinear.from_linear( |
| 64 | new_linear_layer, |
| 65 | new_linear_layer.group_size, |
| 66 | new_linear_layer.bits, |
| 67 | ) |
| 68 | |
| 69 | # Replace the LoRaLayer with the new Linear layer in the model |
| 70 | model.layers[i] = new_linear_layer |