model_lora.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. # 兼容DDP训练保存的权重(带有module.前缀),去除前缀以匹配当前模型
  29. new_state_dict = {}
  30. for k, v in state_dict.items():
  31. if k.startswith('module.'):
  32. new_state_dict[k[7:]] = v
  33. else:
  34. new_state_dict[k] = v
  35. state_dict = new_state_dict
  36. for name, module in model.named_modules():
  37. if hasattr(module, 'lora'):
  38. lora_state = {k.replace(f'{name}.lora.', ''): v for k, v in state_dict.items() if f'{name}.lora.' in k}
  39. module.lora.load_state_dict(lora_state)
  40. def save_lora(model, path):
  41. state_dict = {}
  42. for name, module in model.named_modules():
  43. if hasattr(module, 'lora'):
  44. lora_state = {f'{name}.lora.{k}': v for k, v in module.lora.state_dict().items()}
  45. state_dict.update(lora_state)
  46. torch.save(state_dict, path)