|
|
@@ -7,7 +7,6 @@ class LoRA(nn.Module):
|
|
|
def __init__(self, in_features, out_features, rank, lora_alpha=None):
|
|
|
super().__init__()
|
|
|
self.rank = rank # LoRA的秩(rank),控制低秩矩阵的大小
|
|
|
- # 标准 LoRA 的 alpha/r 缩放;lora_alpha=None 表示 alpha=rank(scaling=1),保持历史行为
|
|
|
scaling = (rank if lora_alpha is None else lora_alpha) / rank
|
|
|
self.register_buffer("scaling", torch.tensor(scaling, dtype=torch.float32))
|
|
|
self.A = nn.Linear(in_features, rank, bias=False) # 低秩矩阵A
|
|
|
@@ -42,7 +41,6 @@ def load_lora(model, path):
|
|
|
for name, module in model.named_modules():
|
|
|
if hasattr(module, 'lora'):
|
|
|
lora_state = {k.replace(f'{name}.lora.', ''): v for k, v in state_dict.items() if f'{name}.lora.' in k}
|
|
|
- # 兼容旧 checkpoint:旧版本没有 scaling buffer(等价于 scaling=1),缺失时保留默认值
|
|
|
module.lora.load_state_dict(lora_state, strict=False)
|
|
|
|
|
|
|
|
|
@@ -52,11 +50,8 @@ def save_lora(model, path):
|
|
|
for name, module in raw_model.named_modules():
|
|
|
if hasattr(module, 'lora'):
|
|
|
clean_name = name[7:] if name.startswith("module.") else name
|
|
|
- lora_state = {}
|
|
|
- for k, v in module.lora.state_dict().items():
|
|
|
- # 权重保持 half 以维持文件体积;scaling 等 buffer 用 float32,避免精度损失
|
|
|
- v = v.cpu().half() if k.endswith('.weight') else v.cpu().float()
|
|
|
- lora_state[f'{clean_name}.lora.{k}'] = v
|
|
|
+ lora_state = {f'{clean_name}.lora.{k}': v.cpu().half() if k.endswith('.weight') else v.cpu().float()
|
|
|
+ for k, v in module.lora.state_dict().items()}
|
|
|
state_dict.update(lora_state)
|
|
|
torch.save(state_dict, path)
|
|
|
|
|
|
@@ -69,7 +64,6 @@ def merge_lora(model, lora_path, save_path):
|
|
|
if isinstance(module, nn.Linear) and '.lora.' not in name:
|
|
|
state_dict[f'{name}.weight'] = module.weight.data.clone().cpu().half()
|
|
|
if hasattr(module, 'lora'):
|
|
|
- delta = module.lora.B.weight.data @ module.lora.A.weight.data
|
|
|
- delta = (delta * module.lora.scaling.to(delta.device)).cpu().half()
|
|
|
- state_dict[f'{name}.weight'] += delta
|
|
|
+ delta = (module.lora.B.weight.data @ module.lora.A.weight.data) * module.lora.scaling
|
|
|
+ state_dict[f'{name}.weight'] += delta.cpu().half()
|
|
|
torch.save(state_dict, save_path)
|