model_lora.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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=8):
  17. for name, module in model.named_modules():
  18. if isinstance(module, nn.Linear) and module.weight.shape[0] == module.weight.shape[1]:
  19. lora = LoRA(module.weight.shape[0], module.weight.shape[1], 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. state_dict = {}
  35. for name, module in model.named_modules():
  36. if hasattr(module, 'lora'):
  37. clean_name = name[7:] if name.startswith("module.") else name
  38. lora_state = {f'{clean_name}.lora.{k}': v for k, v in module.lora.state_dict().items()}
  39. state_dict.update(lora_state)
  40. torch.save(state_dict, path)