| 1 | import json |
| 2 | from pathlib import Path |
| 3 | |
| 4 | import mlx.nn as nn |
| 5 | from mlx.utils import tree_flatten |
| 6 | |
| 7 | from .lora import LoRaLayer |
| 8 | |
| 9 | |
| 10 | def get_module_by_name(model, name): |
| 11 | parts = name.split(".") |
| 12 | module = model |
| 13 | for part in parts: |
| 14 | if part.isdigit(): |
| 15 | module = module[int(part)] |
| 16 | else: |
| 17 | module = getattr(module, part) |
| 18 | return module |
| 19 | |
| 20 | |
| 21 | def set_module_by_name(model, name, new_module): |
| 22 | parts = name.split(".") |
| 23 | module = model |
| 24 | for part in parts[:-1]: |
| 25 | if part.isdigit(): |
| 26 | module = module[int(part)] |
| 27 | else: |
| 28 | module = getattr(module, part) |
| 29 | if parts[-1].isdigit(): |
| 30 | module[int(parts[-1])] = new_module |
| 31 | else: |
| 32 | setattr(module, parts[-1], new_module) |
| 33 | |
| 34 | |
| 35 | def get_peft_model( |
| 36 | model, linear_layers, rank=10, alpha=0.1, dropout=0.1, freeze=True, verbose=True |
| 37 | ): |
| 38 | if freeze: |
| 39 | freeze_model(model) |
| 40 | |
| 41 | for name, module in model.language_model.named_modules(): |
| 42 | if isinstance(module, nn.Linear) or isinstance(module, nn.QuantizedLinear): |
| 43 | if name.split(".")[-1] in linear_layers: |
| 44 | lora_layer = LoRaLayer(module, rank, alpha, dropout) |
| 45 | set_module_by_name(model.language_model, name, lora_layer) |
| 46 | |
| 47 | model.config.lora = {} |
| 48 | model.config.lora["rank"] = rank |
| 49 | model.config.lora["alpha"] = alpha |
| 50 | model.config.lora["dropout"] = dropout |
| 51 | |
| 52 | if verbose: |
| 53 | print_trainable_parameters(model.language_model) |
| 54 | |
| 55 | return model |
| 56 | |
| 57 | |
| 58 | def freeze_model(model): |
| 59 | for name, module in model.named_modules(): |
| 60 | name = name.split(".")[0] |
| 61 | if name in [ |
| 62 | "language_model", |
| 63 | "vision_model", |
| 64 | "vision_tower", |
| 65 | "aligner", |
| 66 | "connector", |
| 67 | "multi_modal_projector", |
| 68 | "mm_projector", |
| 69 | ]: |
| 70 | model[f"{name}"].freeze() |
| 71 | |
| 72 | |
| 73 | def find_all_linear_names(model): |
| 74 | cls = nn.Linear |
| 75 | quantized_cls = nn.QuantizedLinear |
| 76 | lora_module_names = set() |
| 77 | multimodal_keywords = [ |
| 78 | "mm_projector", |
| 79 | "vision_tower", |
| 80 | "vision_resampler", |
| 81 | "aligner", |
| 82 | ] |
| 83 | for name, module in model.named_modules(): |
| 84 | if any(mm_keyword in name for mm_keyword in multimodal_keywords): |
| 85 | continue |
| 86 | if isinstance(module, cls) or isinstance(module, quantized_cls): |
| 87 | names = name.split(".") |
| 88 | lora_module_names.add(names[0] if len(names) == 1 else names[-1]) |
| 89 | |
| 90 | if "lm_head" in lora_module_names: # needed for 16-bit |
| 91 | lora_module_names.remove("lm_head") |
| 92 | return list(lora_module_names) |
| 93 | |
| 94 | |
| 95 | def count_parameters(model): |
| 96 | def nparams(m): |
| 97 | if isinstance(m, (nn.QuantizedLinear, nn.QuantizedEmbedding)): |
| 98 | return m.weight.size * (32 // m.bits) |
| 99 | return sum(v.size for _, v in tree_flatten(m.parameters())) |
| 100 | |
| 101 | leaf_modules = tree_flatten( |
| 102 | model.leaf_modules(), is_leaf=lambda m: isinstance(m, nn.Module) |
| 103 | ) |
| 104 | total_p = sum(nparams(m) for _, m in leaf_modules) / 10**6 |
| 105 | |
| 106 | return total_p |
| 107 | |
| 108 | |
| 109 | def print_trainable_parameters(model): |
| 110 | def nparams(m): |
| 111 | if isinstance(m, (nn.QuantizedLinear, nn.QuantizedEmbedding)): |
| 112 | return m.weight.size * (32 // m.bits) |
| 113 | return sum(v.size for _, v in tree_flatten(m.parameters())) |
| 114 | |
| 115 | leaf_modules = tree_flatten( |
| 116 | model.leaf_modules(), is_leaf=lambda m: isinstance(m, nn.Module) |
| 117 | ) |
| 118 | total_p = sum(nparams(m) for _, m in leaf_modules) / 10**6 |
| 119 | trainable_p = ( |
| 120 | sum(v.size for _, v in tree_flatten(model.trainable_parameters())) / 10**6 |
| 121 | ) |
| 122 | |
| 123 | print( |
| 124 | f"#trainable params: {trainable_p} M || all params: {total_p} M || trainable%: {(trainable_p * 100 / total_p):.3f}%" |
| 125 | ) |
| 126 | |
| 127 | |
| 128 | def apply_lora_layers(model: nn.Module, adapter_path: str) -> nn.Module: |
| 129 | """ |
| 130 | Apply LoRA layers to the model. |
| 131 | |
| 132 | Args: |
| 133 | model (nn.Module): The neural network model. |
| 134 | adapter_path (str): Path to the adapter configuration file. |
| 135 | |
| 136 | Returns: |
| 137 | nn.Module: The updated model with LoRA layers applied. |
| 138 | """ |
| 139 | adapter_path = Path(adapter_path) |
| 140 | |
| 141 | if not adapter_path.exists(): |
| 142 | raise FileNotFoundError(f"The adapter path does not exist: {adapter_path}") |
| 143 | |
| 144 | # Check if the adapter has lora params in the config (adapter_config.json) |
| 145 | with open(adapter_path / "adapter_config.json", "r") as f: |
| 146 | config = json.load(f) |
| 147 | if "rank" not in config: |
| 148 | raise ValueError("The adapter does not have lora params in the config") |
| 149 | |
| 150 | # TODO: add lora params to the config and load them here |
| 151 | list_of_modules = find_all_linear_names(model.language_model.model) |
| 152 | if config is not None: |
| 153 | model = get_peft_model(model, list_of_modules, **config) |
| 154 | else: |
| 155 | model = get_peft_model(model, list_of_modules) |
| 156 | |
| 157 | # TODO: Use custom adapter name |
| 158 | model.load_weights(str(adapter_path / "adapters.safetensors"), strict=False) |
| 159 | |
| 160 | return model |