|
| 1 | +import logging |
| 2 | +from dataclasses import dataclass |
| 3 | +from pathlib import Path |
| 4 | +from typing import Dict, NamedTuple, Union |
| 5 | + |
| 6 | +import safetensors.torch |
| 7 | +import torch |
| 8 | +import torch.nn as nn |
| 9 | +from simple_parsing.helpers import Serializable |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class LoraArgs(Serializable): |
| 14 | + rank: int |
| 15 | + scaling: float |
| 16 | + |
| 17 | + def __post_init__(self): |
| 18 | + assert self.rank > 0 |
| 19 | + assert self.scaling > 0.0 |
| 20 | + |
| 21 | + |
| 22 | +class LoRALinear(nn.Module): |
| 23 | + """ |
| 24 | + Implementation of: |
| 25 | + - LoRA: https://arxiv.org/abs/2106.09685 |
| 26 | +
|
| 27 | + Notes: |
| 28 | + - Freezing is handled at network level, not layer level. |
| 29 | + - Scaling factor controls relative importance of LoRA skip |
| 30 | + connection versus original frozen weight. General guidance is |
| 31 | + to keep it to 2.0 and sweep over learning rate when changing |
| 32 | + the rank. |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + in_features: int, |
| 38 | + out_features: int, |
| 39 | + rank: int, |
| 40 | + scaling: float, |
| 41 | + bias: bool = False, |
| 42 | + ): |
| 43 | + super().__init__() |
| 44 | + |
| 45 | + self.in_features = in_features |
| 46 | + self.out_features = out_features |
| 47 | + assert not bias |
| 48 | + self.bias = bias |
| 49 | + self.rank = rank |
| 50 | + self.scaling = scaling |
| 51 | + |
| 52 | + self.lora_A = nn.Linear( |
| 53 | + self.in_features, |
| 54 | + self.rank, |
| 55 | + bias=self.bias, |
| 56 | + ) |
| 57 | + self.lora_B = nn.Linear( |
| 58 | + self.rank, |
| 59 | + self.out_features, |
| 60 | + bias=self.bias, |
| 61 | + ) |
| 62 | + |
| 63 | + self.linear = nn.Linear(self.in_features, self.out_features, bias=self.bias) |
| 64 | + |
| 65 | + # make sure no LoRA weights are marked as "missing" in load_state_dict |
| 66 | + def ignore_missing_keys(m: nn.Module, incompatible_keys: NamedTuple): |
| 67 | + incompatible_keys.missing_keys[:] = [] # type: ignore |
| 68 | + |
| 69 | + self.register_load_state_dict_post_hook(ignore_missing_keys) |
| 70 | + |
| 71 | + def forward(self, x: torch.Tensor): |
| 72 | + lora = self.lora_B(self.lora_A(x)) |
| 73 | + return self.linear(x) + lora * self.scaling |
| 74 | + |
| 75 | + def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs): |
| 76 | + key_name = prefix + "weight" |
| 77 | + |
| 78 | + # full checkpoint |
| 79 | + if key_name in state_dict: |
| 80 | + w_ref = state_dict[key_name] |
| 81 | + |
| 82 | + # load frozen weights |
| 83 | + state_dict = { |
| 84 | + "linear.weight": w_ref, |
| 85 | + "lora_A.weight": torch.zeros_like( |
| 86 | + self.lora_A.weight, device=w_ref.device, dtype=w_ref.dtype |
| 87 | + ), |
| 88 | + "lora_B.weight": torch.zeros_like( |
| 89 | + self.lora_B.weight, device=w_ref.device, dtype=w_ref.dtype |
| 90 | + ), |
| 91 | + } |
| 92 | + self.load_state_dict(state_dict, assign=True, strict=True) |
| 93 | + |
| 94 | + |
| 95 | +class LoRALoaderMixin: |
| 96 | + def load_lora(self, lora_path: Union[Path, str], scaling: float = 2.0): |
| 97 | + """Loads LoRA checkpoint""" |
| 98 | + |
| 99 | + lora_path = Path(lora_path) |
| 100 | + assert lora_path.is_file(), f"{lora_path} does not exist or is not a file" |
| 101 | + |
| 102 | + state_dict = safetensors.torch.load_file(lora_path) |
| 103 | + |
| 104 | + self._load_lora_state_dict(state_dict, scaling=scaling) |
| 105 | + |
| 106 | + def _load_lora_state_dict( |
| 107 | + self, lora_state_dict: Dict[str, torch.Tensor], scaling: float = 2.0 |
| 108 | + ): |
| 109 | + """Loads LoRA state_dict""" |
| 110 | + |
| 111 | + lora_dtypes = set([p.dtype for p in lora_state_dict.values()]) |
| 112 | + assert ( |
| 113 | + len(lora_dtypes) == 1 |
| 114 | + ), f"LoRA weights have multipe different dtypes {lora_dtypes}. All weights need to have the same dtype" |
| 115 | + lora_dtype = lora_dtypes.pop() |
| 116 | + assert ( |
| 117 | + lora_dtype == self.dtype |
| 118 | + ), f"LoRA weights dtype differs from model's dtype {lora_dtype} != {self.dtype}" |
| 119 | + assert all("lora" in key for key in lora_state_dict.keys()) |
| 120 | + |
| 121 | + # move tensors to device |
| 122 | + lora_state_dict = {k: v.to(self.device) for k, v in lora_state_dict.items()} |
| 123 | + |
| 124 | + state_dict = self.state_dict() |
| 125 | + |
| 126 | + if self.args.lora is None: |
| 127 | + logging.info("Loading and merging LoRA weights...") |
| 128 | + |
| 129 | + # replace every nn.Linear with a LoRALinear with 'meta' device except the output layer |
| 130 | + named_modules = dict(self.named_modules()) |
| 131 | + for name, module in named_modules.items(): |
| 132 | + if isinstance(module, nn.Linear) and name != "output": |
| 133 | + layer_id = name.split(".")[1] |
| 134 | + if layer_id not in self.layers: |
| 135 | + logging.debug( |
| 136 | + "Skipping parameter %s at pipeline rank %d", |
| 137 | + name, |
| 138 | + self.pipeline_rank, |
| 139 | + ) |
| 140 | + else: |
| 141 | + weight = ( |
| 142 | + module.weight |
| 143 | + + ( |
| 144 | + lora_state_dict[name + ".lora_B.weight"] |
| 145 | + @ lora_state_dict[name + ".lora_A.weight"] |
| 146 | + ) |
| 147 | + * scaling |
| 148 | + ) |
| 149 | + |
| 150 | + state_dict[name + ".weight"] = weight |
| 151 | + else: |
| 152 | + logging.info("Loading LoRA weights...") |
| 153 | + for k, v in lora_state_dict.items(): |
| 154 | + state_dict.update(lora_state_dict) |
| 155 | + |
| 156 | + layer_id = k.split(".")[1] |
| 157 | + if layer_id in self.layers: |
| 158 | + state_dict[k] = v |
| 159 | + else: |
| 160 | + logging.debug( |
| 161 | + "Skipping parameter %s at pipeline rank %d", |
| 162 | + k, |
| 163 | + self.pipeline_rank, |
| 164 | + ) |
| 165 | + |
| 166 | + self.load_state_dict(state_dict, strict=True) |
0 commit comments