model_lora.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import torch
  2. from torch import optim, nn
  3. # 定义Lora网络结构
  4. class LoRA(nn.Module):
  5. def __init__(self, in_features, out_features, rank, lora_alpha=None):
  6. super().__init__()
  7. self.rank = rank # LoRA的秩(rank),控制低秩矩阵的大小
  8. scaling = (rank if lora_alpha is None else lora_alpha) / rank
  9. self.register_buffer("scaling", torch.tensor(scaling, dtype=torch.float32))
  10. self.A = nn.Linear(in_features, rank, bias=False) # 低秩矩阵A
  11. self.B = nn.Linear(rank, out_features, bias=False) # 低秩矩阵B
  12. # 矩阵A高斯初始化
  13. self.A.weight.data.normal_(mean=0.0, std=0.02)
  14. # 矩阵B全0初始化
  15. self.B.weight.data.zero_()
  16. def forward(self, x):
  17. return self.B(self.A(x)) * self.scaling
  18. def apply_lora(model, rank=16, lora_alpha=None):
  19. for name, module in model.named_modules():
  20. if isinstance(module, nn.Linear) and module.in_features == module.out_features:
  21. lora = LoRA(module.in_features, module.out_features, rank=rank, lora_alpha=lora_alpha).to(model.device)
  22. setattr(module, "lora", lora)
  23. original_forward = module.forward
  24. # 显式绑定
  25. def forward_with_lora(x, layer1=original_forward, layer2=lora):
  26. return layer1(x) + layer2(x)
  27. module.forward = forward_with_lora
  28. def load_lora(model, path):
  29. state_dict = torch.load(path, map_location=model.device)
  30. state_dict = {(k[7:] if k.startswith('module.') else k): v for k, v in state_dict.items()}
  31. for name, module in model.named_modules():
  32. if hasattr(module, 'lora'):
  33. lora_state = {k.replace(f'{name}.lora.', ''): v for k, v in state_dict.items() if f'{name}.lora.' in k}
  34. module.lora.load_state_dict(lora_state, strict=False)
  35. def save_lora(model, path):
  36. raw_model = getattr(model, '_orig_mod', model)
  37. state_dict = {}
  38. for name, module in raw_model.named_modules():
  39. if hasattr(module, 'lora'):
  40. clean_name = name[7:] if name.startswith("module.") else name
  41. lora_state = {f'{clean_name}.lora.{k}': v.cpu().half() if k.endswith('.weight') else v.cpu().float()
  42. for k, v in module.lora.state_dict().items()}
  43. state_dict.update(lora_state)
  44. torch.save(state_dict, path)
  45. def merge_lora(model, lora_path, save_path):
  46. load_lora(model, lora_path)
  47. raw_model = getattr(model, '_orig_mod', model)
  48. state_dict = {k: v.cpu().half() for k, v in raw_model.state_dict().items() if '.lora.' not in k}
  49. for name, module in raw_model.named_modules():
  50. if isinstance(module, nn.Linear) and '.lora.' not in name:
  51. state_dict[f'{name}.weight'] = module.weight.data.clone().cpu().float()
  52. if hasattr(module, 'lora'):
  53. delta = (module.lora.B.weight.data.float() @ module.lora.A.weight.data.float()) * module.lora.scaling.float()
  54. state_dict[f'{name}.weight'] += delta.cpu()
  55. state_dict[f'{name}.weight'] = state_dict[f'{name}.weight'].half()
  56. torch.save(state_dict, save_path)