Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Sources/BasaltInference/Adapters/PHMAdapterApplicator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ extension PHMAdapterApplicator {
) throws(BasaltError) -> [(String, Module)] {
switch method {
case .lora(let rank, let scale):
if let reason = targets.lazy.compactMap({ MLXInferenceEngine.microscaledLoRARefusal($0.linear, path: $0.fullPath) }).first {
throw .invalidRequestStructure(details: "adapter: \(reason)")
}
return targets.map { target in
(target.fullPath, LoRALinear.from(linear: target.linear, rank: rank, scale: scale))
}
Expand Down
10 changes: 9 additions & 1 deletion Sources/BasaltInference/MLXInferenceEngine+LabGate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ extension MLXInferenceEngine {
guard let linear = model.namedModules().first(where: { $0.0 == path })?.1 as? Linear, restorable(linear) else {
throw refused("not a plain Linear or QuantizedLinear layer without an adapter; model_tensors lists the layers (the tensor name without .weight)")
}
if let reason = microscaledLoRARefusal(linear, path: path) { throw refused(reason) }
let (outputs, inputs) = linear.shape
guard input.count == inputs, output.count == outputs else {
throw refused("input needs \(inputs) values and output \(outputs), got \(input.count) and \(output.count)")
Expand Down Expand Up @@ -257,9 +258,11 @@ extension MLXInferenceEngine {
let modules = Dictionary(model.namedModules(), uniquingKeysWith: { first, _ in first })
let rank = adapter.configuration.loraParameters.rank
for (key, value) in adapter.parameters.flattened() {
guard let linear = modules[key.split(separator: ".").dropLast().joined(separator: ".")] as? Linear else {
let path = key.split(separator: ".").dropLast().joined(separator: ".")
guard let linear = modules[path] as? Linear else {
throw refused("\(key) belongs to no linear layer of this model")
}
if let reason = microscaledLoRARefusal(linear, path: path) { throw refused(reason) }
let (outputs, inputs) = linear.shape
let expected = key.hasSuffix(".lora_a") ? [inputs, rank] : key.hasSuffix(".lora_b") ? [rank, outputs] : value.shape
guard value.shape == expected else { throw refused("\(key) has shape \(value.shape), the layer needs \(expected)") }
Expand Down Expand Up @@ -292,6 +295,11 @@ extension MLXInferenceEngine {
}
}

static func microscaledLoRARefusal(_ module: Module, path: String) -> String? {
guard let quantized = module as? QuantizedLinear, !quantized.scales.dtype.isFloatingPoint else { return nil }
return "\(path) is a \(quantized.mode) layer with \(quantized.scales.dtype) scales; LoRA on it computes in integers until the mlx-swift-lm fork fix (#746), so it is refused"
}

static func restorable(_ module: Module) -> Bool {
guard (module as? QuantizedLinear)?.globalScale == nil else { return false }
return [ObjectIdentifier(Linear.self), ObjectIdentifier(QuantizedLinear.self)].contains(ObjectIdentifier(type(of: module)))
Expand Down
4 changes: 4 additions & 0 deletions Sources/BasaltInference/MLXInferenceEngine+LabTrain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,10 @@ extension MLXInferenceEngine {
for index in indices where blocks.indices.contains(index) {
let update: [(String, Module)] = blocks[index].namedModules().compactMap { key, module -> (String, Module)? in
guard keys.contains(key), let linear = module as? Linear, restorable(linear) else { return nil }
if fineTuneType == .lora, let reason = microscaledLoRARefusal(linear, path: key) {
BasaltLogger(module: "MLXInferenceEngine").warn("LoRA training skips \(reason)")
return nil
}
let replacement: Module = switch fineTuneType {
case .lora: LoRALinear.from(linear: linear, rank: parameters.rank, scale: parameters.scale, dropout: parameters.dropout)
case .dora: DoRALinear.from(linear: linear, rank: parameters.rank, scale: parameters.scale, dropout: parameters.dropout)
Expand Down
52 changes: 52 additions & 0 deletions Tests/BasaltTests/MicroscaledLoRARefusalTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Foundation
import MLX
import MLXLMCommon
import MLXNN
import Testing
@testable import BasaltCore
@testable import BasaltInference

@Suite("LoRA on microscaled layers (mxfp4) is refused with the mode named, until the fork computes it in float; affine layers still take it (#746)", .serialized)
struct MicroscaledLoRARefusalTests {
static func quantized(_ mode: QuantizationMode) throws -> (any LanguageModel, [PEFTAdapterTests.Pair]) {
let model = try TinyModel.make(.qwen35)
let pairs = PEFTAdapterTests.pairs(model, family: .qwen35)
quantize(model: model, groupSize: 32, bits: 4, mode: mode) { path, module in
module is Linear && pairs.contains { $0.path == path }
}
return (model, pairs)
}

static func loraPaths(_ model: any LanguageModel) -> [String] {
model.namedModules().filter { $0.1 is LoRALayer }.map(\.0)
}

@Test("A PEFT adapter and a rank-1 adapter_apply on mxfp4 layers are refused naming mxfp4 and #746, and leave the model without LoRA layers")
func mxfp4IsRefused() throws {
let (model, pairs) = try Self.quantized(.mxfp4)
let directory = try PEFTAdapterTests.directory(pairs, config: PEFTAdapterTests.config())
defer { try? FileManager.default.removeItem(at: directory) }
let peft = #expect(throws: BasaltError.self) { try MLXInferenceEngine.attachAnyAdapterDirectory(directory, to: model) }
#expect("\(String(describing: peft))".contains("mxfp4"))
#expect("\(String(describing: peft))".contains("#746"))
#expect(Self.loraPaths(model).isEmpty)

let target = try #require(pairs.first)
let (outputs, inputs) = try #require(model.namedModules().first { $0.0 == target.path }?.1 as? Linear).shape
let rankOne = #expect(throws: BasaltError.self) {
try MLXInferenceEngine.attachRankOne(
target.path, input: Array(repeating: 0.1, count: inputs), output: Array(repeating: 0.1, count: outputs), scale: 1, to: model)
}
#expect("\(String(describing: rankOne))".contains("mxfp4"))
#expect(Self.loraPaths(model).isEmpty)
}

@Test("The same PEFT adapter on affine 4-bit layers still attaches to every target")
func affineStillAttaches() throws {
let (model, pairs) = try Self.quantized(.affine)
let directory = try PEFTAdapterTests.directory(pairs, config: PEFTAdapterTests.config())
defer { try? FileManager.default.removeItem(at: directory) }
let wrapped = try MLXInferenceEngine.attachAnyAdapterDirectory(directory, to: model)
#expect(Set(wrapped) == Set(pairs.map(\.path)))
}
}