model_lora.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. # 标准 LoRA 的 alpha/r 缩放;lora_alpha=None 表示 alpha=rank(scaling=1),保持历史行为
  9. scaling = (rank if lora_alpha is None else lora_alpha) / rank
  10. self.register_buffer("scaling", torch.tensor(scaling, dtype=torch.float32))
  11. self.A = nn.Linear(in_features, rank, bias=False) # 低秩矩阵A
  12. self.B = nn.Linear(rank, out_features, bias=False) # 低秩矩阵B
  13. # 矩阵A高斯初始化
  14. self.A.weight.data.normal_(mean=0.0, std=0.02)
  15. # 矩阵B全0初始化
  16. self.B.weight.data.zero_()
  17. def forward(self, x):
  18. return self.B(self.A(x)) * self.scaling
  19. def apply_lora(model, rank=16, lora_alpha=None):
  20. for name, module in model.named_modules():
  21. if isinstance(module, nn.Linear) and module.in_features == module.out_features:
  22. lora = LoRA(module.in_features, module.out_features, rank=rank, lora_alpha=lora_alpha).to(model.device)
  23. setattr(module, "lora", lora)
  24. original_forward = module.forward
  25. # 显式绑定
  26. def forward_with_lora(x, layer1=original_forward, layer2=lora):
  27. return layer1(x) + layer2(x)
  28. module.forward = forward_with_lora
  29. def load_lora(model, path):
  30. state_dict = torch.load(path, map_location=model.device)
  31. state_dict = {(k[7:] if k.startswith('module.') else k): v for k, v in state_dict.items()}
  32. for name, module in model.named_modules():
  33. if hasattr(module, 'lora'):
  34. lora_state = {k.replace(f'{name}.lora.', ''): v for k, v in state_dict.items() if f'{name}.lora.' in k}
  35. # 兼容旧 checkpoint:旧版本没有 scaling buffer(等价于 scaling=1),缺失时保留默认值
  36. module.lora.load_state_dict(lora_state, strict=False)
  37. def save_lora(model, path):
  38. raw_model = getattr(model, '_orig_mod', model)
  39. state_dict = {}
  40. for name, module in raw_model.named_modules():
  41. if hasattr(module, 'lora'):
  42. clean_name = name[7:] if name.startswith("module.") else name
  43. lora_state = {}
  44. for k, v in module.lora.state_dict().items():
  45. # 权重保持 half 以维持文件体积;scaling 等 buffer 用 float32,避免精度损失
  46. v = v.cpu().half() if k.endswith('.weight') else v.cpu().float()
  47. lora_state[f'{clean_name}.lora.{k}'] = v
  48. state_dict.update(lora_state)
  49. torch.save(state_dict, path)
  50. def merge_lora(model, lora_path, save_path):
  51. load_lora(model, lora_path)
  52. raw_model = getattr(model, '_orig_mod', model)
  53. state_dict = {k: v.cpu().half() for k, v in raw_model.state_dict().items() if '.lora.' not in k}
  54. for name, module in raw_model.named_modules():
  55. if isinstance(module, nn.Linear) and '.lora.' not in name:
  56. state_dict[f'{name}.weight'] = module.weight.data.clone().cpu().half()
  57. if hasattr(module, 'lora'):
  58. delta = module.lora.B.weight.data @ module.lora.A.weight.data
  59. delta = (delta * module.lora.scaling.to(delta.device)).cpu().half()
  60. state_dict[f'{name}.weight'] += delta
  61. torch.save(state_dict, save_path)