Text Classification
Transformers
lora
fine-tuning
adaptive
research
nested-lora
synaptic-plasticity
rank-adaptation
Instructions to use Simo76/Unified-LoRA with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Simo76/Unified-LoRA with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="Simo76/Unified-LoRA")# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Simo76/Unified-LoRA", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add Unified-LoRA controller implementation
Browse filesThis file implements a Unified-LoRA controller for adaptive per-layer rank control during LoRA fine-tuning. It includes the LoRALinear class, methods to inject LoRA into models, and setup functions for training.
- unified_lora.py +175 -0
unified_lora.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unified-LoRA Controller
|
| 3 |
+
========================
|
| 4 |
+
Adaptive per-layer rank controller for LoRA fine-tuning.
|
| 5 |
+
Drop-in module — works with any model that uses LoRA adapters.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
from unified_lora import LoRALinear, get_lora_modules
|
| 9 |
+
|
| 10 |
+
# Replace linear layers with adaptive LoRA
|
| 11 |
+
layer.q_proj = LoRALinear(layer.q_proj, max_r=16)
|
| 12 |
+
|
| 13 |
+
# In training loop, after loss.backward():
|
| 14 |
+
for m in get_lora_modules(model):
|
| 15 |
+
m.update_rank()
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import copy
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class LoRALinear(nn.Module):
|
| 24 |
+
"""
|
| 25 |
+
LoRA adapter with per-layer adaptive rank.
|
| 26 |
+
|
| 27 |
+
The rank adjusts based on gradient stress:
|
| 28 |
+
- Gradient stress increasing → rank goes up (more capacity)
|
| 29 |
+
- Gradient stress decreasing → rank goes down (less capacity)
|
| 30 |
+
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
base : nn.Linear
|
| 34 |
+
The original linear layer to wrap.
|
| 35 |
+
max_r : int
|
| 36 |
+
Maximum rank (default 16).
|
| 37 |
+
min_r : int
|
| 38 |
+
Minimum rank (default 4).
|
| 39 |
+
alpha : float
|
| 40 |
+
Scaling factor for LoRA output. Uses alpha/active_r scaling.
|
| 41 |
+
layer_name : str
|
| 42 |
+
Optional name for logging.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self, base, max_r=16, min_r=4, alpha=16.0, layer_name=""):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.base = copy.deepcopy(base)
|
| 48 |
+
for p in self.base.parameters():
|
| 49 |
+
p.requires_grad = False
|
| 50 |
+
|
| 51 |
+
self.max_r = max_r
|
| 52 |
+
self.min_r = min_r
|
| 53 |
+
self.alpha = alpha
|
| 54 |
+
self.layer_name = layer_name
|
| 55 |
+
|
| 56 |
+
self.A = nn.Parameter(torch.randn(max_r, base.in_features) * 0.01)
|
| 57 |
+
self.B = nn.Parameter(torch.zeros(base.out_features, max_r))
|
| 58 |
+
self.active_r = min_r
|
| 59 |
+
|
| 60 |
+
# Stress tracking
|
| 61 |
+
self.grad_ema = None
|
| 62 |
+
self.prev_grad_ema = None
|
| 63 |
+
|
| 64 |
+
def set_rank(self, r):
|
| 65 |
+
self.active_r = max(self.min_r, min(r, self.max_r))
|
| 66 |
+
|
| 67 |
+
def update_rank(self):
|
| 68 |
+
"""Call after loss.backward(), before optimizer.step()."""
|
| 69 |
+
if self.A.grad is None:
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
grad_norm = self.A.grad[:self.active_r].norm().item()
|
| 73 |
+
|
| 74 |
+
if self.grad_ema is None:
|
| 75 |
+
self.grad_ema = grad_norm
|
| 76 |
+
self.prev_grad_ema = grad_norm
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
self.prev_grad_ema = self.grad_ema
|
| 80 |
+
self.grad_ema = 0.9 * self.grad_ema + 0.1 * grad_norm
|
| 81 |
+
|
| 82 |
+
delta = self.grad_ema - self.prev_grad_ema
|
| 83 |
+
threshold = 0.01 * self.grad_ema if self.grad_ema > 0 else 0.01
|
| 84 |
+
|
| 85 |
+
if delta > threshold:
|
| 86 |
+
self.active_r = min(self.max_r, self.active_r + 2)
|
| 87 |
+
elif delta < -threshold:
|
| 88 |
+
self.active_r = max(self.min_r, self.active_r - 2)
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
base_out = self.base(x)
|
| 92 |
+
A = self.A[:self.active_r]
|
| 93 |
+
B = self.B[:, :self.active_r]
|
| 94 |
+
lora_out = x @ A.t() @ B.t()
|
| 95 |
+
scale = self.alpha / self.active_r
|
| 96 |
+
return base_out + scale * lora_out
|
| 97 |
+
|
| 98 |
+
def extra_repr(self):
|
| 99 |
+
return (f"in={self.base.in_features}, out={self.base.out_features}, "
|
| 100 |
+
f"max_r={self.max_r}, min_r={self.min_r}, alpha={self.alpha}, "
|
| 101 |
+
f"active_r={self.active_r}, name={self.layer_name}")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def get_lora_modules(model):
|
| 105 |
+
"""Return all LoRALinear modules in a model."""
|
| 106 |
+
return [m for m in model.modules() if isinstance(m, LoRALinear)]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def inject_lora(model, target_modules, max_r=16, min_r=4, alpha=16.0):
|
| 110 |
+
"""
|
| 111 |
+
Replace target linear layers with LoRALinear adapters.
|
| 112 |
+
|
| 113 |
+
Parameters
|
| 114 |
+
----------
|
| 115 |
+
model : nn.Module
|
| 116 |
+
The model to modify.
|
| 117 |
+
target_modules : list of str
|
| 118 |
+
Names of linear layers to replace (e.g. ["q_proj", "v_proj"]).
|
| 119 |
+
max_r, min_r, alpha : passed to LoRALinear.
|
| 120 |
+
|
| 121 |
+
Returns
|
| 122 |
+
-------
|
| 123 |
+
model : nn.Module
|
| 124 |
+
Modified model with LoRA adapters.
|
| 125 |
+
|
| 126 |
+
Example
|
| 127 |
+
-------
|
| 128 |
+
# DistilBERT
|
| 129 |
+
inject_lora(model, ["q_lin", "v_lin"])
|
| 130 |
+
|
| 131 |
+
# Llama / Mistral
|
| 132 |
+
inject_lora(model, ["q_proj", "v_proj"])
|
| 133 |
+
|
| 134 |
+
# All attention projections
|
| 135 |
+
inject_lora(model, ["q_proj", "k_proj", "v_proj", "o_proj"])
|
| 136 |
+
"""
|
| 137 |
+
replace_list = []
|
| 138 |
+
for name, module in model.named_modules():
|
| 139 |
+
if isinstance(module, nn.Linear):
|
| 140 |
+
if any(name.endswith(t) for t in target_modules):
|
| 141 |
+
replace_list.append(name)
|
| 142 |
+
|
| 143 |
+
for name in replace_list:
|
| 144 |
+
parts = name.split(".")
|
| 145 |
+
parent = model
|
| 146 |
+
for p in parts[:-1]:
|
| 147 |
+
parent = getattr(parent, p)
|
| 148 |
+
original = getattr(parent, parts[-1])
|
| 149 |
+
setattr(parent, parts[-1], LoRALinear(
|
| 150 |
+
original, max_r=max_r, min_r=min_r, alpha=alpha, layer_name=name
|
| 151 |
+
))
|
| 152 |
+
|
| 153 |
+
print(f"Injected LoRA into {len(replace_list)} layers: {replace_list}")
|
| 154 |
+
return model
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def setup_trainable(model):
|
| 158 |
+
"""Freeze base model, unfreeze LoRA params and classifier."""
|
| 159 |
+
for p in model.parameters():
|
| 160 |
+
p.requires_grad = False
|
| 161 |
+
|
| 162 |
+
for m in get_lora_modules(model):
|
| 163 |
+
m.A.requires_grad = True
|
| 164 |
+
m.B.requires_grad = True
|
| 165 |
+
|
| 166 |
+
# Unfreeze common classifier head names
|
| 167 |
+
for n, p in model.named_parameters():
|
| 168 |
+
if any(k in n for k in ["classifier", "pre_classifier", "score", "lm_head"]):
|
| 169 |
+
p.requires_grad = True
|
| 170 |
+
|
| 171 |
+
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 172 |
+
total = sum(p.numel() for p in model.parameters())
|
| 173 |
+
print(f"Trainable: {trainable:,} / {total:,} ({100*trainable/total:.2f}%)")
|
| 174 |
+
|
| 175 |
+
return model
|