model_lora.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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):
  6. super().__init__()
  7. self.rank = rank # LoRA的秩(rank),控制低秩矩阵的大小
  8. self.A = nn.Linear(in_features, rank, bias=False) # 低秩矩阵A
  9. self.B = nn.Linear(rank, out_features, bias=False) # 低秩矩阵B
  10. # 矩阵A高斯初始化
  11. self.A.weight.data.normal_(mean=0.0, std=0.02)
  12. # 矩阵B全0初始化
  13. self.B.weight.data.zero_()
  14. def forward(self, x):
  15. return self.B(self.A(x))
  16. def apply_lora(model, rank=16):
  17. for name, module in model.named_modules():
  18. if isinstance(module, nn.Linear) and module.in_features == module.out_features:
  19. lora = LoRA(module.in_features, module.out_features, rank=rank).to(model.device)
  20. setattr(module, "lora", lora)
  21. original_forward = module.forward
  22. # 显式绑定
  23. def forward_with_lora(x, layer1=original_forward, layer2=lora):
  24. return layer1(x) + layer2(x)
  25. module.forward = forward_with_lora
  26. def load_lora(model, path):
  27. state_dict = torch.load(path, map_location=model.device)
  28. state_dict = {(k[7:] if k.startswith('module.') else k): v for k, v in state_dict.items()}
  29. for name, module in model.named_modules():
  30. if hasattr(module, 'lora'):
  31. lora_state = {k.replace(f'{name}.lora.', ''): v for k, v in state_dict.items() if f'{name}.lora.' in k}
  32. module.lora.load_state_dict(lora_state)
  33. def save_lora(model, path):
  34. raw_model = getattr(model, '_orig_mod', model)
  35. state_dict = {}
  36. for name, module in raw_model.named_modules():
  37. if hasattr(module, 'lora'):
  38. clean_name = name[7:] if name.startswith("module.") else name
  39. lora_state = {f'{clean_name}.lora.{k}': v.cpu().half() for k, v in module.lora.state_dict().items()}
  40. state_dict.update(lora_state)
  41. torch.save(state_dict, path)
  42. def merge_lora(model, lora_path, save_path):
  43. load_lora(model, lora_path)
  44. raw_model = getattr(model, '_orig_mod', model)
  45. state_dict = {k: v.cpu().half() for k, v in raw_model.state_dict().items() if '.lora.' not in k}
  46. for name, module in raw_model.named_modules():
  47. if isinstance(module, nn.Linear) and '.lora.' not in name:
  48. state_dict[f'{name}.weight'] = module.weight.data.clone().cpu().half()
  49. if hasattr(module, 'lora'):
  50. state_dict[f'{name}.weight'] += (module.lora.B.weight.data @ module.lora.A.weight.data).cpu().half()
  51. torch.save(state_dict, save_path)