|
| 1 | +// |
| 2 | +// DoRA+Layers.swift |
| 3 | +// mlx-libraries |
| 4 | +// |
| 5 | +// Created by Ivan Petrukha on 02.06.2025. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | +import MLX |
| 10 | +import MLXLinalg |
| 11 | +import MLXNN |
| 12 | +import MLXRandom |
| 13 | + |
| 14 | +/// Performs the forward pass for a DoRA linear layer. |
| 15 | +private func forward( |
| 16 | + x: MLXArray, y: MLXArray, |
| 17 | + weight: MLXArray, bias: MLXArray?, |
| 18 | + loraA: MLXArray, loraB: MLXArray, |
| 19 | + scale: Float, magnitude: MLXArray |
| 20 | +) -> MLXArray { |
| 21 | + let z = matmul(matmul(x, loraA), loraB) |
| 22 | + var out = y + (scale * z).asType(x.dtype) |
| 23 | + |
| 24 | + let adapted = weight + matmul(scale * loraB.T, loraA.T) |
| 25 | + let denom = norm(adapted, axis: 1) |
| 26 | + out *= (magnitude / denom).asType(x.dtype) |
| 27 | + |
| 28 | + return if let bias { |
| 29 | + out + bias |
| 30 | + } else { |
| 31 | + out |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/// Fuses the base weights with the DoRA parameters. |
| 36 | +private func fuse( |
| 37 | + weight: MLXArray, |
| 38 | + loraA: MLXArray, loraB: MLXArray, |
| 39 | + scale: Float, magnitude: MLXArray |
| 40 | +) -> MLXArray { |
| 41 | + let loraA = loraA.T.asType(weight.dtype) |
| 42 | + let loraB = (scale * loraB.T).asType(weight.dtype) |
| 43 | + |
| 44 | + var adapted = weight + matmul(loraB, loraA) |
| 45 | + let denom = norm(adapted, axis: 1) |
| 46 | + adapted *= (magnitude / denom).reshaped([-1, 1]) |
| 47 | + |
| 48 | + return adapted |
| 49 | +} |
| 50 | + |
| 51 | +/// Filters out DoRA-specific parameters from a list of module keys. |
| 52 | +private func filterFreezeKeys(from module: Module, keys: [String]?) -> [String] { |
| 53 | + return |
| 54 | + (keys |
| 55 | + ?? module.filterMap(filter: type(of: module).filterLocalParameters) |
| 56 | + .flattened() |
| 57 | + .map { $0.0 }) |
| 58 | + .filter { !["lora_a", "lora_b", "m"].contains($0) } |
| 59 | +} |
| 60 | + |
| 61 | +/// Implementation of DoRA `Linear` replacement layer. |
| 62 | +/// |
| 63 | +/// This layer implements DoRA (Weight-Decomposed Low-Rank Adaptation) for `Linear` layers. |
| 64 | +/// |
| 65 | +/// ``QDoRALinear`` is the equivalent class for `QuantizedLinear`. |
| 66 | +public class DoRALinear: Linear, LoRALayer { |
| 67 | + |
| 68 | + let scale: Float |
| 69 | + |
| 70 | + @ParameterInfo(key: "lora_a") var loraA: MLXArray |
| 71 | + @ParameterInfo(key: "lora_b") var loraB: MLXArray |
| 72 | + @ParameterInfo(key: "m") var magnitude: MLXArray |
| 73 | + |
| 74 | + required public init(linear: Linear, rank: Int = 8, scale: Float = 20.0) { |
| 75 | + let (outputDimensions, inputDimensions) = linear.shape |
| 76 | + let loraScale = 1 / sqrt(Float(inputDimensions)) |
| 77 | + |
| 78 | + self.scale = scale |
| 79 | + self._loraA.wrappedValue = MLXRandom.uniform( |
| 80 | + low: -loraScale, high: loraScale, [inputDimensions, rank]) |
| 81 | + self._loraB.wrappedValue = MLXArray.zeros([rank, outputDimensions]) |
| 82 | + self._magnitude.wrappedValue = MLXLinalg.norm(linear.weight, axis: 1) |
| 83 | + |
| 84 | + super.init(weight: linear.weight, bias: linear.bias) |
| 85 | + |
| 86 | + freeze() |
| 87 | + } |
| 88 | + |
| 89 | + public static func from(linear: Linear, rank: Int = 8, scale: Float = 20.0) -> LoRALayer { |
| 90 | + if let linear = linear as? QuantizedLinear { |
| 91 | + QDoRALinear(linear: linear, rank: rank, scale: scale) |
| 92 | + } else { |
| 93 | + DoRALinear(linear: linear, rank: rank, scale: scale) |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + public override func freeze(recursive: Bool = true, keys: [String]? = nil, strict: Bool = false) |
| 98 | + throws |
| 99 | + { |
| 100 | + let keys = filterFreezeKeys(from: self, keys: keys) |
| 101 | + try super.freeze(recursive: recursive, keys: keys, strict: strict) |
| 102 | + } |
| 103 | + |
| 104 | + public func fused() -> Module { |
| 105 | + Linear( |
| 106 | + weight: fuse( |
| 107 | + weight: weight, loraA: loraA, loraB: loraB, scale: scale, magnitude: magnitude), |
| 108 | + bias: bias |
| 109 | + ) |
| 110 | + } |
| 111 | + |
| 112 | + public override func callAsFunction(_ x: MLXArray) -> MLXArray { |
| 113 | + let y = matmul(x, weight.T) |
| 114 | + return forward( |
| 115 | + x: x, y: y, |
| 116 | + weight: weight, bias: bias, |
| 117 | + loraA: loraA, loraB: loraB, |
| 118 | + scale: scale, magnitude: magnitude |
| 119 | + ) |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +/// Implementation of DoRA `QuantizedLinear` replacement layer. |
| 124 | +/// |
| 125 | +/// See ``DoRALinear`` (equivalent class for `Linear` layers) for more information. |
| 126 | +/// |
| 127 | +/// ### See Also |
| 128 | +/// - ``DoRALinear`` |
| 129 | +public class QDoRALinear: QuantizedLinear, LoRALayer { |
| 130 | + |
| 131 | + let scale: Float |
| 132 | + |
| 133 | + @ParameterInfo(key: "lora_a") var loraA: MLXArray |
| 134 | + @ParameterInfo(key: "lora_b") var loraB: MLXArray |
| 135 | + @ParameterInfo(key: "m") var magnitude: MLXArray |
| 136 | + |
| 137 | + required public init(linear: QuantizedLinear, rank: Int = 8, scale: Float = 20.0) { |
| 138 | + let (outputDimensions, inputDimensions) = linear.shape |
| 139 | + let loraScale = 1 / sqrt(Float(inputDimensions)) |
| 140 | + |
| 141 | + self.scale = scale |
| 142 | + self._loraA.wrappedValue = MLXRandom.uniform( |
| 143 | + low: -loraScale, high: loraScale, [inputDimensions, rank]) |
| 144 | + self._loraB.wrappedValue = MLXArray.zeros([rank, outputDimensions]) |
| 145 | + self._magnitude.wrappedValue = MLXLinalg.norm(linear.dequantizedWeight, axis: 1) |
| 146 | + |
| 147 | + super.init( |
| 148 | + weight: linear.weight, bias: linear.bias, |
| 149 | + scales: linear.scales, biases: linear.biases, |
| 150 | + groupSize: linear.groupSize, bits: linear.bits |
| 151 | + ) |
| 152 | + |
| 153 | + freeze() |
| 154 | + } |
| 155 | + |
| 156 | + public override func freeze(recursive: Bool = true, keys: [String]? = nil, strict: Bool = false) |
| 157 | + throws |
| 158 | + { |
| 159 | + let keys = filterFreezeKeys(from: self, keys: keys) |
| 160 | + try super.freeze(recursive: recursive, keys: keys, strict: strict) |
| 161 | + } |
| 162 | + |
| 163 | + public func fused() -> Module { |
| 164 | + QuantizedLinear( |
| 165 | + weight: fuse( |
| 166 | + weight: dequantizedWeight, loraA: loraA, loraB: loraB, scale: scale, |
| 167 | + magnitude: magnitude), |
| 168 | + bias: bias, groupSize: groupSize, bits: bits |
| 169 | + ) |
| 170 | + } |
| 171 | + |
| 172 | + public override func callAsFunction(_ x: MLXArray) -> MLXArray { |
| 173 | + let y = quantizedMatmul( |
| 174 | + x, weight, scales: scales, biases: biases, groupSize: groupSize, bits: bits) |
| 175 | + return forward( |
| 176 | + x: x, y: y, |
| 177 | + weight: dequantizedWeight, bias: bias, |
| 178 | + loraA: loraA, loraB: loraB, |
| 179 | + scale: scale, magnitude: magnitude |
| 180 | + ) |
| 181 | + } |
| 182 | +} |
0 commit comments