GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — S4oP/unstructured_pruning.py at main · PARCO-LAB/S4oP

Expand file tree

/

unstructured_pruning.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
476 lines (411 loc) · 21.1 KB
/

unstructured_pruning.py

Copy path

File metadata and controls

476 lines (411 loc) · 21.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import os
import argparse
import torch
from src.model import ModelTrain, ModelTest
from models_config import *
from pruning_config import *
# Schedule cubico della sparsità
def cubic_sparsity(step, t0, t_end, s_final):
"""Schedule cubico del paper (Eq. 2, con s0 = 0), in iterazioni di training:
- fino a t0 -> 0 (nessun pruning)
- da t0 a t_end -> sale come s_final * (1 - (1 - (t - t0)/(t_end - t0))^3)
- da t_end -> s_final (solo fine-tuning alla sparsita' finale)
"""
if step <= t0:
return 0.0
if step >= t_end:
return s_final
r = 1.0 - (step - t0) / (t_end - t0)
return s_final * (1.0 - r ** 3)
def ssm_rows_in_proj(model):
"""Mamba2: in_proj produce [z | x | B | C | dt]. Le righe di B, C e dt
(l'equivalente di x_proj/dt_proj in Mamba1) partono da 2*d_inner.
Restituisce {nome_parametro_in_proj: prima_riga_ssm}. Vuoto per Mamba1."""
out = {}
for mname, mod in model.named_modules():
if type(mod).__name__ == "Mamba2Simple":
prefix = f"{mname}." if mname else ""
out[f"{prefix}in_proj.weight"] = 2 * mod.d_inner
return out
def mixer_param_names(model):
"""Nomi di TUTTI i parametri dei mixer Mamba (Mamba1 e Mamba2), cioe' dei moduli
che hanno un parametro A_log, di qualunque dimensione: in_proj, conv1d (peso e bias),
x_proj, dt_proj, A_log, D, dt_bias, norm interna, out_proj."""
names = set()
for mname, mod in model.named_modules():
if isinstance(getattr(mod, "A_log", None), torch.nn.Parameter):
for pname, _ in mod.named_parameters(prefix=mname):
names.add(pname)
return names
def ssm_param_names(model):
"""S4 e S4D: parametri del kernel SSM e skip D di ogni layer, cioe' dei moduli che
hanno un sottomodulo `kernel` e un parametro `D` (FFTConv in S4, LayerS4D in S4D).
E' quello che S4OP rimuove quando spegne un canale (dt, A, B, C, P, D del canale).
output_linear, norme, embedding e testa restano fuori: S4OP non li tocca."""
names = set()
for mname, mod in model.named_modules():
kernel = getattr(mod, "kernel", None)
D = getattr(mod, "D", None)
if isinstance(kernel, torch.nn.Module) and isinstance(D, torch.nn.Parameter):
prefix = f"{mname}." if mname else ""
names.add(f"{prefix}D")
for pname, _ in kernel.named_parameters(prefix=f"{prefix}kernel"):
names.add(pname)
return names
# Pruner
class MambaPruner:
"""Maschere binarie (1 = tengo il peso, 0 = lo pruno)."""
def __init__(self, model, alpha=1.0, scope="mixer"):
self.model = model
self.alpha = alpha
self.weights = {} # prunabili
self.masks = {} # nome -> maschera
self.ssm_rows = ssm_rows_in_proj(model) # solo Mamba2
# Perimetro del pool (cosa il criterio globale puo' scegliere di azzerare):
# - "mixer": i parametri su cui agisce S4OP, di qualunque dimensione.
# Mamba/Mamba2: tutti i parametri dei mixer (A_log, D, dt_bias, bias della conv
# e norm interna compresi): rimuovendo una head/canale S4OP ne elimina anche questi.
# S4/S4D: kernel SSM (dt, A, B, C, P) e skip D; output_linear resta fuori.
# Embedding, encoder, testa e norme residue restano sempre fuori, come in S4OP.
# - "all": tutti i parametri del modello, embedding compresi (configurazione del
# paper: Alg. 1, Fig. 10).
# Nota: azzerare un parametro in scala logaritmica (A_log, log_dt, log_A_real) non
# lo "spegne" (exp(0) = 1), ma e' comunque un parametro che non va memorizzato.
if scope == "mixer":
perimeter = mixer_param_names(model) | ssm_param_names(model)
if not perimeter:
raise RuntimeError("Nessun layer SSM trovato (ne' mixer Mamba ne' kernel S4/S4D)")
elif scope == "all":
perimeter = {n for n, _ in model.named_parameters()}
else:
raise ValueError(f"scope sconosciuto: {scope}")
for name, p in model.named_parameters():
if p.requires_grad and name in perimeter:
self.weights[name] = p
self.masks[name] = torch.ones_like(p)
# Sparsita' definita come nel paper: frazione di TUTTI i parametri del modello
# Tutto cio' che e' fuori dal pool (embedding, encoder, testa, ...) non viene
# mai potato ma conta nel denominatore.
self.total_numel = sum(p.numel() for p in model.parameters())
pool_numel = sum(p.numel() for p in self.weights.values())
self.protected_numel = self.total_numel - pool_numel
print(f"[INFO] parametri totali: {self.total_numel/1e6:.3f}M | nel pool potabile: "
f"{pool_numel/1e6:.3f}M ({pool_numel/self.total_numel:.1%})")
# Gradienti raccolti dai passi di training per calcolare l'importanza
# (somma dei gradienti di `importance_batches` passi, come prima ma senza
# forward/backward aggiuntivi)
self.grad_acc = {n: torch.zeros_like(p) for n, p in self.weights.items()}
self.collecting = False
self.n_collected = 0
# Hook sui gradienti: azzera il gradiente dei pesi potati, cosi' optimizer/weight-decay
# non li resuscitano. Quando `collecting` e' attivo accumula anche il gradiente
# (prima del gradient clipping, che avviene dopo il backward).
for name, p in self.weights.items():
p.register_hook(lambda g, n=name: self._hook(n, g))
def _hook(self, name, g):
g = g * self.masks[name]
if self.collecting:
self.grad_acc[name] += g.detach()
return g
@torch.no_grad()
def reset_collect(self):
for acc in self.grad_acc.values():
acc.zero_()
self.n_collected = 0
@torch.no_grad()
def enforce(self):
"""Forza a zero i pesi potati. Da chiamare dopo OGNI optimizer.step()."""
for name, p in self.weights.items():
p.mul_(self.masks[name])
@torch.no_grad()
def current_sparsity(self):
"""Frazione di parametri potati sul totale del modello (definizione del paper)."""
zeros = sum((m == 0).sum().item() for m in self.masks.values())
return zeros / max(1, self.total_numel)
@torch.no_grad()
def remaining_params(self):
"""Parametri non nulli rimasti: la colonna 'Params (M)' della Tab. 1 del paper."""
zeros = sum((m == 0).sum().item() for m in self.masks.values())
return self.total_numel - zeros
@torch.no_grad()
def prune_from_collected(self, target_sparsity):
"""Importanza S(w)=|w|*|somma dei gradienti raccolti|^alpha e maschera globale
per arrivare a `target_sparsity`. Restituisce False se non c'erano gradienti."""
if self.n_collected == 0:
print("[WARN] nessun gradiente raccolto: maschera non aggiornata")
return False
scores = {n: p.detach().abs() * self.grad_acc[n].abs().pow(self.alpha)
for n, p in self.weights.items()}
# Classifica globale -> soglia di taglio
flat = torch.cat([s.flatten().cpu() for s in scores.values()])
# Numero di pesi da azzerare: target * |theta| (tutto il modello), presi solo dal pool
prunable_total = flat.numel()
k_global = int(round(target_sparsity * self.total_numel))
k = max(1, min(k_global, prunable_total - 1))
if k_global > prunable_total - 1:
print(f"[WARN] {target_sparsity:.0%} irraggiungibile: i parametri fuori dal pool "
f"sono {self.protected_numel/self.total_numel:.1%} del modello")
device = next(iter(scores.values())).device
threshold = torch.kthvalue(flat, k).values.to(device) # k-esimo valore piu' piccolo
for name in self.weights:
self.masks[name] = (scores[name] > threshold).to(self.masks[name].dtype)
self.enforce()
return True
@torch.no_grad()
def sparsity_per_group(self):
"""Quota potata dentro ciascun gruppo, sui soli pesi del pool
(dove il criterio globale ha tagliato, come in Fig. 13 del paper).
In S4/S4D il pool contiene solo parametri SSM, quindi 'linear' resta a 0."""
groups = {"ssm": [0, 0], "linear": [0, 0]}
ssm_tags = ("x_proj", "dt_proj", "conv1d", "A_log", "dt_bias", ".kernel.")
for name, m in self.masks.items():
if name in self.ssm_rows:
# Mamba2: in_proj misto -> z, x in "linear"; B, C, dt in "ssm"
s = self.ssm_rows[name]
parts = (("linear", m[:s]), ("ssm", m[s:]))
else:
is_ssm = any(t in name for t in ssm_tags) or name.split(".")[-1] == "D"
key = "ssm" if is_ssm else "linear"
parts = ((key, m),)
for key, mm in parts:
groups[key][0] += (mm == 0).sum().item()
groups[key][1] += mm.numel()
return {k: v[0] / max(1, v[1]) for k, v in groups.items()}
# FINE-TUNER
class PruningFineTuning:
def __init__(self, model, dataset, epochs, s_final,
lr, lr_min, weight_decay, checkpoint_path,
alpha=1.0, prune_start=0.25, prune_end=0.75, importance_batches=5,
n_updates=20, patience=None, scope="mixer"):
self.mt = ModelTrain(model, dataset)
self.pruner = MambaPruner(model, alpha=alpha, scope=scope)
self.epochs = epochs
self.s_final = s_final
self.lr = lr
self.lr_min = lr_min
self.weight_decay = weight_decay
self.checkpoint_path = checkpoint_path
self.prune_start = prune_start
self.prune_end = prune_end
self.importance_batches = importance_batches
self.n_updates = n_updates
self.patience = patience
def run(self):
is_ecg = self.mt.dataset.multilabel
base_criterion = torch.nn.BCEWithLogitsLoss() if is_ecg else torch.nn.CrossEntropyLoss()
metric_name = self.mt.metric
print(f"[Selezione del checkpoint potato su: val_{metric_name}]")
# Stessa logica di ModelTrain.save: Mamba2 tiene la struttura in active_heads_layers,
# Mamba, S4 e S4D in active_idx_layers
model = self.mt.model
active_layers = (model.active_heads_layers if self.mt.model_name == "mamba2" else model.active_idx_layers)
# Optimizer/scheduler interni, come Table 8: AdamW + decay lineare lr->lr_min
optimizer = torch.optim.AdamW(model.parameters(), lr=self.lr, weight_decay=self.weight_decay)
scheduler = torch.optim.lr_scheduler.LinearLR(
optimizer, start_factor=1.0,
end_factor=max(self.lr_min / self.lr, 1e-6), total_iters=self.epochs)
# Hook: riazzera i pesi potati dopo ogni optimizer.step()
optimizer.register_step_post_hook(lambda *a, **k: self.pruner.enforce())
# Rampa misurata in iterazioni di training (un'iterazione = un batch), come nel paper:
# il pruning parte al `prune_start` del training e finisce al `prune_end`;
# dopo, solo fine-tuning alla sparsita' finale.
# La maschera si aggiorna `n_updates` volte a intervalli regolari nella rampa,
# qualunque sia la dimensione del dataset o il batch size.
iters_per_epoch = len(self.mt.trainloader)
total_iters = self.epochs * iters_per_epoch
t0 = int(round(self.prune_start * total_iters))
t_end = max(t0 + 1, int(round(self.prune_end * total_iters)))
update_every = max(1, (t_end - t0) // self.n_updates)
update_steps = sorted(set(range(t0 + update_every, t_end + 1, update_every)) | {t_end})
print(f"[INFO] {iters_per_epoch} iterazioni/epoca, {total_iters} totali | pruning dalla {t0} "
f"alla {t_end} | {len(update_steps)} aggiornamenti della maschera (ogni {update_every} iterazioni)")
K = self.importance_batches
def window_start(u):
# primo passo i cui gradienti contano per l'aggiornamento al passo u
return max(1, u - K + 1)
st = {"step": 0, "next": 0, "applied": 0.0}
self.pruner.reset_collect()
self.pruner.collecting = window_start(update_steps[0]) <= 1
def on_step():
# chiamata da train_step dopo ogni optimizer.step()
st["step"] += 1
s = st["step"]
if self.pruner.collecting:
self.pruner.n_collected += 1
if st["next"] < len(update_steps) and s == update_steps[st["next"]]:
t = cubic_sparsity(s, t0, t_end, self.s_final)
if t > st["applied"] and self.pruner.prune_from_collected(t):
st["applied"] = t
self.pruner.reset_collect()
st["next"] += 1
# il backward del prossimo passo va raccolto?
if st["next"] < len(update_steps):
self.pruner.collecting = (s + 1) >= window_start(update_steps[st["next"]])
else:
self.pruner.collecting = False
best = -float("inf")
saved = False
bad_epochs = 0
for epoch in range(self.epochs):
self.mt.train_step(epoch, optimizer, base_criterion, step_callback=on_step)
target = st["applied"]
sp = self.pruner.current_sparsity()
val_metrics = self.mt.val_step(base_criterion)
metric = val_metrics.get(metric_name, float("nan"))
if metric != metric: # nan
raise ValueError(f"metrica '{metric_name}' non disponibile (metriche calcolate: {sorted(val_metrics)})")
scheduler.step()
grp = self.pruner.sparsity_per_group()
print(f"[Epoch {epoch+1}] val_loss: {val_metrics['loss']:.4f} | val_{metric_name}: {metric:.3f} "
f"| target: {target:.4f} | sparsity: {sp:.4f} (ssm {grp['ssm']:.2f} / lin {grp['linear']:.2f}) "
f"| params: {self.pruner.remaining_params():,}")
# considera il salvataggio solo quando sei alla sparsità target.
at_target = target >= self.s_final
if at_target and sp < self.s_final - 0.01:
print(f"[WARN] sparsita' raggiunta {sp:.3f} sotto il target {self.s_final:.3f}")
if at_target and metric > best:
best = metric
saved = True
bad_epochs = 0
torch.save({
"model_state_dict": model.state_dict(),
"active_idx_layers": active_layers, # chiavi lette da ModelTest.from_pth
"pruned_mode": model.pruned_mode, # modello denso: i due modi coincidono
"pruning_masks": self.pruner.masks,
"sparsity": sp, # sul totale del modello, come nel paper
"remaining_params": self.pruner.remaining_params(),
}, self.checkpoint_path)
elif at_target:
# early stopping come nel fine-tuning di S4OP, ma contato solo dopo aver
# raggiunto la sparsita' finale (durante la rampa la metrica cala per forza)
bad_epochs += 1
if self.patience is not None and bad_epochs >= self.patience:
print(f"Early stopping all'epoca {epoch+1}: nessun miglioramento di val_{metric_name} "
f"per {self.patience} epoche alla sparsita' target")
break
if not saved:
raise RuntimeError(f"Nessun checkpoint salvato: la sparsita' target {self.s_final} "
f"non e' mai stata raggiunta entro {self.epochs} epoche.")
print(f"\nMigliore val_{metric_name}: {best:.3f} | salvato in {self.checkpoint_path}")
return best
# MAIN
def build_args():
parser = argparse.ArgumentParser(description="Run")
parser.add_argument(
"--model", "-m",
dest="model_name",
choices=["mamba", "mamba2", "s4", "s4d"],
default="mamba",
help="Architettura: decide i nomi dei file e le chiavi di config")
parser.add_argument(
"--dataset", "-d",
dest="dataset_name",
required=True,
help="Dataset name")
parser.add_argument(
"--checkpoint", "-c",
dest="checkpoint",
required=True,
help="Nome cartella da dove caricare i modelli base")
parser.add_argument(
"--output", "-o",
dest="output",
required=True,
help="Dove salvare il modello prunato (default: stessa cartella)")
parser.add_argument("--prune_start", type=float, default=0.0,
help="Frazione del training in cui inizia il pruning")
parser.add_argument("--prune_end", type=float, default=0.5,
help="Frazione del training in cui si raggiunge la sparsita' finale")
parser.add_argument("--alpha", type=float, default=1.0)
parser.add_argument("--importance_batches", type=int, default=5,
help="Passi di training i cui gradienti vengono sommati prima di ogni aggiornamento della maschera")
parser.add_argument("--n_updates", type=int, default=20,
help="Quante volte aggiornare la maschera durante la rampa (a intervalli regolari di iterazioni)")
parser.add_argument("--early_stopping", action=argparse.BooleanOptionalAction, default=True,
help="Usa la patience 'early_stopping'")
parser.add_argument("--scope", choices=["mixer", "all"], default="mixer",
help="mixer: solo i parametri su cui agisce S4OP (mixer Mamba; kernel SSM + D in S4/S4D); "
"all: tutto il modello, embedding compresi (configurazione del paper)")
parser.add_argument("--test", action=argparse.BooleanOptionalAction, default=True, help="Testa il modello potato a fine pruning")
return parser.parse_args()
def load_model(model_path, args, config):
c = config[args.model_name][args.dataset_name]
return ModelTest.from_pth(
model_path=model_path,
batch_size=c["batch_size"],
valsplit=config["val_split"],
num_workers=config["num_workers"],
d_model=c["features"],
d_state=c["d_state"],
depth=c["depth"],
dropout=c["dropout"],
norm=c["norm"],
pre_norm=c["pre-norm"],
)
def main():
config = MODELS_CONFIG
pruning_config = PRUNING_CONFIG
perc = pruning_config["perc"]
results = {}
args = build_args()
m = args.model_name
os.makedirs(args.output, exist_ok=True)
for i, p in enumerate(perc):
print(f"===== PRUNING {100*p}% =====")
suffix = "" if args.scope == "mixer" else f"_{args.scope}"
if (m == "s4d" or m == "s4") and (args.dataset_name == "imdb"):
path = os.path.join(f"./{args.output}", f"{m}_{args.dataset_name}_pruned_{p*100:.2f}%{suffix}.pth")
else:
path = os.path.join(f"./{args.output}", f"{m}_{args.dataset_name}_pruned_{int(p*100)}%{suffix}.pth")
if os.path.exists(path):
print(f"[SKIP] esiste già: {path}")
continue
model_checkpoint = f"./{args.checkpoint}/{m}_{args.dataset_name}_best.pth"
# Carico baseline (modello + dataset)
model = load_model(model_checkpoint, args, config)
model, dataset = model.model, model.dataset
# Setup iperparametri di pruning
# epoche e patience crescono col livello (grow_with_level in pruning_config.py)
ft = finetune_params("unstructured", m, dataset.name, level=i)
lr = ft["lr"]
lr_min = lr * 0.01
weight_decay = ft["weight_decay"]
epochs = ft["finetune_epochs"]
patience = ft["early_stopping"] if args.early_stopping else None
print(f"Pruning parameters: model={m}, scope={args.scope}, lr={lr}, lr_min={lr_min}, weight_decay={weight_decay}, "
f"epochs={epochs}, patience={patience}, prune_start={args.prune_start}, prune_end={args.prune_end}, "
f"n_updates={args.n_updates}, alpha={args.alpha}, importance_batches={args.importance_batches}")
job = PruningFineTuning(
model=model,
dataset=dataset,
epochs=epochs,
s_final=p,
lr=lr,
lr_min=lr_min,
weight_decay=weight_decay,
checkpoint_path=path,
alpha=args.alpha,
prune_start=args.prune_start,
prune_end=args.prune_end,
importance_batches=args.importance_batches,
n_updates=args.n_updates,
patience=patience,
scope=args.scope,
)
job.run()
metric_name = job.mt.metric
del job, model, dataset
torch.cuda.empty_cache()
if args.test:
print("\n--- TEST modello potato ---")
res = load_model(path, args, config).run()
score = res.get(metric_name, float("nan")) if isinstance(res, dict) else res
results[p] = (metric_name, score)
print(f"\n=== RISULTATI DI TEST PER OGNI STEP ===")
for per, (name, score) in results.items():
if (m == "s4d" or m == "s4") and (args.dataset_name == "imdb"):
print(f" - Pruning {per*100:.2f}%: test_{name} {score:.2f}")
else:
print(f" - Pruning {int(per*100)}%: test_{name} {score:.2f}")
if __name__ == "__main__":
main()
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.