HayrettinIscan commited on
Commit
513c56b
·
verified ·
1 Parent(s): 9c8b230

Upload code/faz3_v6/meshai_train/lora_inject.py with huggingface_hub

Browse files
code/faz3_v6/meshai_train/lora_inject.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Inject FrozenLinearLoRA into nn.Linear modules of a loaded model/pipeline."""
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Iterable
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ from meshai_train.base_weights import FrozenLinearLoRA
11
+
12
+
13
+ def iter_named_linears(root: nn.Module) -> list[tuple[str, nn.Linear]]:
14
+ out: list[tuple[str, nn.Linear]] = []
15
+ for name, mod in root.named_modules():
16
+ if isinstance(mod, nn.Linear):
17
+ out.append((name, mod))
18
+ return out
19
+
20
+
21
+ def _set_module_by_name(root: nn.Module, dotted: str, new_mod: nn.Module) -> None:
22
+ parts = dotted.split(".")
23
+ parent = root
24
+ for p in parts[:-1]:
25
+ parent = getattr(parent, p)
26
+ setattr(parent, parts[-1], new_mod)
27
+
28
+
29
+ def inject_lora_into_linears(
30
+ root: nn.Module,
31
+ *,
32
+ rank: int = 8,
33
+ max_layers: int = 16,
34
+ min_features: int = 64,
35
+ name_substr: tuple[str, ...] = (),
36
+ log_fn: Any = print,
37
+ ) -> list[str]:
38
+ """
39
+ Replace selected nn.Linear with FrozenLinearLoRA (W frozen, A/B trainable).
40
+ Returns dotted names that were replaced.
41
+ """
42
+ cands = iter_named_linears(root)
43
+ if name_substr:
44
+ cands = [c for c in cands if any(s in c[0].lower() for s in name_substr)]
45
+ # Prefer larger mats
46
+ cands.sort(key=lambda x: x[1].in_features * x[1].out_features, reverse=True)
47
+ picked: list[tuple[str, nn.Linear]] = []
48
+ for name, lin in cands:
49
+ if lin.in_features < min_features or lin.out_features < 16:
50
+ continue
51
+ picked.append((name, lin))
52
+ if len(picked) >= max_layers:
53
+ break
54
+ replaced: list[str] = []
55
+ for name, lin in picked:
56
+ w = lin.weight.detach().float().cpu()
57
+ lora = FrozenLinearLoRA(w, rank=rank, name=name)
58
+ # match device/dtype later via .to()
59
+ _set_module_by_name(root, name, lora)
60
+ replaced.append(name)
61
+ log_fn(f"[faz3-lora] injected {len(replaced)} LoRA layers (rank={rank})")
62
+ for n in replaced[:8]:
63
+ log_fn(f" - {n}")
64
+ if len(replaced) > 8:
65
+ log_fn(f" ... +{len(replaced) - 8} more")
66
+ return replaced
67
+
68
+
69
+ def lora_parameters(root: nn.Module) -> list[nn.Parameter]:
70
+ params: list[nn.Parameter] = []
71
+ for m in root.modules():
72
+ if isinstance(m, FrozenLinearLoRA):
73
+ params.extend([m.lora_A, m.lora_B])
74
+ return params
75
+
76
+
77
+ def merge_lora_into_linears(root: nn.Module) -> int:
78
+ """Bake LoRA into dense Linear weights (inference). Returns merge count."""
79
+ n = 0
80
+ for name, mod in list(root.named_modules()):
81
+ if not isinstance(mod, FrozenLinearLoRA):
82
+ continue
83
+ with torch.no_grad():
84
+ delta = (mod.lora_B @ mod.lora_A) * mod.scale
85
+ merged = mod.weight + delta.to(dtype=mod.weight.dtype, device=mod.weight.device)
86
+ lin = nn.Linear(mod.in_features, mod.out_features, bias=False)
87
+ lin.weight = nn.Parameter(merged.clone())
88
+ _set_module_by_name(root, name, lin)
89
+ n += 1
90
+ return n