2024-01-26 10:59:32 +08:00
|
|
|
import os
|
2024-03-12 22:37:40 +08:00
|
|
|
from typing import Dict
|
2024-01-26 10:59:32 +08:00
|
|
|
|
2024-01-24 00:44:37 +08:00
|
|
|
import mlx.core as mx
|
2024-01-24 11:47:39 +08:00
|
|
|
import mlx.nn as nn
|
2024-01-24 00:44:37 +08:00
|
|
|
from mlx.utils import tree_unflatten
|
|
|
|
|
|
|
|
from .lora import LoRALinear
|
|
|
|
|
|
|
|
|
2024-03-12 22:37:40 +08:00
|
|
|
def linear_to_lora_layers(
|
|
|
|
model: nn.Module,
|
|
|
|
num_lora_layers: int,
|
|
|
|
config: Dict,
|
|
|
|
):
|
2024-02-13 02:51:02 +08:00
|
|
|
"""
|
|
|
|
Convert some of the models linear layers to lora layers.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (nn.Module): The neural network model.
|
|
|
|
num_lora_layers (int): The number of blocks to convert to lora layers
|
|
|
|
starting from the last layer.
|
2024-03-12 22:37:40 +08:00
|
|
|
config (dict): More configuration parameters for LoRA, including the
|
|
|
|
rank, alpha, scale, and optional layer keys.
|
2024-02-13 02:51:02 +08:00
|
|
|
"""
|
2024-02-13 22:56:27 +08:00
|
|
|
|
2024-03-12 22:37:40 +08:00
|
|
|
num_layers = len(model.layers)
|
|
|
|
if num_lora_layers > num_layers:
|
|
|
|
raise ValueError(
|
|
|
|
f"Requested {num_lora_layers} LoRA layers "
|
|
|
|
f"but the model only has {num_layers} layers."
|
|
|
|
)
|
2024-02-13 22:56:27 +08:00
|
|
|
|
2024-03-12 22:37:40 +08:00
|
|
|
to_lora = lambda lin: LoRALinear.from_linear(
|
2024-03-20 23:44:40 +08:00
|
|
|
lin,
|
|
|
|
r=config["rank"],
|
|
|
|
alpha=config["alpha"],
|
|
|
|
scale=config["scale"],
|
|
|
|
dropout=config["dropout"],
|
2024-03-12 22:37:40 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
keys = config.get("keys", None)
|
|
|
|
if keys is not None:
|
|
|
|
keys = set(keys)
|
|
|
|
elif model.model_type in [
|
2024-02-13 02:51:02 +08:00
|
|
|
"mistral",
|
|
|
|
"llama",
|
|
|
|
"phi",
|
|
|
|
"mixtral",
|
2024-03-02 01:53:38 +08:00
|
|
|
"stablelm",
|
2024-02-13 02:51:02 +08:00
|
|
|
"qwen2",
|
2024-02-22 00:47:13 +08:00
|
|
|
"gemma",
|
2024-03-03 11:39:23 +08:00
|
|
|
"starcoder2",
|
2024-03-14 01:09:36 +08:00
|
|
|
"cohere",
|
2024-02-13 02:51:02 +08:00
|
|
|
]:
|
2024-03-12 22:37:40 +08:00
|
|
|
keys = set(["self_attn.q_proj", "self_attn.v_proj"])
|
|
|
|
if model.model_type == "mixtral":
|
2024-03-13 11:02:03 +08:00
|
|
|
keys.add("block_sparse_moe.gate")
|
2024-02-13 02:51:02 +08:00
|
|
|
elif model.model_type == "olmo":
|
2024-03-12 22:37:40 +08:00
|
|
|
keys = set(["att_proj"])
|
2024-02-13 02:51:02 +08:00
|
|
|
elif model.model_type == "phi-msft":
|
2024-03-12 22:37:40 +08:00
|
|
|
keys = set(["mixer.Wqkv", "moe.gate"])
|
2024-03-29 12:03:53 +08:00
|
|
|
elif model.model_type == "dbrx":
|
|
|
|
keys = set(["norm_attn_norm.attn.Wqkv", "ffn.router.layer"])
|
2024-02-13 02:51:02 +08:00
|
|
|
else:
|
|
|
|
raise ValueError(f"Lora does not support {model.model_type}")
|
|
|
|
|
2024-03-12 22:37:40 +08:00
|
|
|
for l in model.layers[num_layers - num_lora_layers :]:
|
|
|
|
modules = l.named_modules()
|
|
|
|
lora_layers = [(k, to_lora(m)) for k, m in l.named_modules() if k in keys]
|
|
|
|
l.update_modules(tree_unflatten(lora_layers))
|
|
|
|
|
2024-02-13 02:51:02 +08:00
|
|
|
|
2024-01-24 11:47:39 +08:00
|
|
|
def apply_lora_layers(model: nn.Module, adapter_file: str) -> nn.Module:
|
2024-01-26 10:59:32 +08:00
|
|
|
"""
|
|
|
|
Apply LoRA layers to the model.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (nn.Module): The neural network model.
|
|
|
|
adapter_file (str): Path to the adapter configuration file.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
nn.Module: The updated model with LoRA layers applied.
|
|
|
|
"""
|
|
|
|
if not os.path.exists(adapter_file):
|
|
|
|
raise FileNotFoundError(f"The adapter file does not exist: {adapter_file}")
|
|
|
|
|
2024-01-24 00:44:37 +08:00
|
|
|
adapters = list(mx.load(adapter_file).items())
|
2024-01-26 10:59:32 +08:00
|
|
|
|
|
|
|
linear_replacements = []
|
2024-01-24 00:44:37 +08:00
|
|
|
lora_layers = set(
|
|
|
|
[name.replace(".lora_a", "").replace(".lora_b", "") for name, _ in adapters]
|
|
|
|
)
|
|
|
|
for name, module in model.named_modules():
|
|
|
|
if name in lora_layers:
|
|
|
|
replacement_module = LoRALinear.from_linear(module)
|
2024-01-26 10:59:32 +08:00
|
|
|
linear_replacements.append((name, replacement_module))
|
|
|
|
|
|
|
|
model.update_modules(tree_unflatten(linear_replacements))
|
2024-02-01 03:51:26 +08:00
|
|
|
|
|
|
|
model.update(tree_unflatten(adapters))
|
|
|
|
|
2024-01-26 10:59:32 +08:00
|
|
|
return model
|
|
|
|
|
|
|
|
|
|
|
|
def dequantize(model: nn.Module) -> nn.Module:
|
|
|
|
"""
|
|
|
|
Dequantize the quantized linear layers in the model.
|
2024-01-24 00:44:37 +08:00
|
|
|
|
2024-01-26 10:59:32 +08:00
|
|
|
Args:
|
|
|
|
model (nn.Module): The model with quantized linear layers.
|
2024-01-24 00:44:37 +08:00
|
|
|
|
2024-01-26 10:59:32 +08:00
|
|
|
Returns:
|
|
|
|
nn.Module: The model with dequantized layers.
|
|
|
|
"""
|
|
|
|
de_quantize_layers = []
|
2024-01-30 12:54:49 +08:00
|
|
|
for name, module in model.named_modules():
|
|
|
|
if isinstance(module, nn.QuantizedLinear):
|
|
|
|
bias = "bias" in module
|
|
|
|
weight = module.weight
|
2024-01-26 10:59:32 +08:00
|
|
|
weight = mx.dequantize(
|
|
|
|
weight,
|
2024-01-30 12:54:49 +08:00
|
|
|
module.scales,
|
|
|
|
module.biases,
|
|
|
|
module.group_size,
|
|
|
|
module.bits,
|
2024-01-26 10:59:32 +08:00
|
|
|
).astype(mx.float16)
|
|
|
|
output_dims, input_dims = weight.shape
|
|
|
|
linear = nn.Linear(input_dims, output_dims, bias=bias)
|
|
|
|
linear.weight = weight
|
|
|
|
if bias:
|
2024-01-30 12:54:49 +08:00
|
|
|
linear.bias = module.bias
|
|
|
|
de_quantize_layers.append((name, linear))
|
2024-01-26 10:59:32 +08:00
|
|
|
if len(de_quantize_layers) > 0:
|
|
|
|
model.update_modules(tree_unflatten(de_quantize_layers))
|
2024-01-24 00:44:37 +08:00
|
|
|
return model
|
2024-01-30 12:54:49 +08:00
|
|
|
|
|
|
|
|
|
|
|
def remove_lora_layers(model: nn.Module) -> nn.Module:
|
|
|
|
"""
|
|
|
|
Remove the LoRA layers from the model.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
model (nn.Module): The model with LoRA layers.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
nn.Module: The model without LoRA layers.
|
|
|
|
"""
|
|
|
|
reset_layers = []
|
|
|
|
for name, module in model.named_modules():
|
|
|
|
if isinstance(module, LoRALinear):
|
|
|
|
reset_layers.append((name, module.linear))
|
|
|
|
if len(reset_layers) > 0:
|
|
|
|
model.update_modules(tree_unflatten(reset_layers))
|
|
|
|
return model
|