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/s4op.py at main · PARCO-LAB/S4oP

Expand file tree

/

s4op.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
329 lines (277 loc) · 12.3 KB
/

s4op.py

Copy path

File metadata and controls

329 lines (277 loc) · 12.3 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
import argparse
import os
import random
import torch
import gc
import time
if torch.cuda.is_available() and not torch.cuda.is_initialized():
torch.cuda.current_device()
from src.model import FineTuning, ModelTest
from src.model.utils import set_benchmark, set_seed, get_device
from src.model.net import NetFactory, PRUNED_MODES, mixers_of, checkpoint_kind, checkpoint_pruned_mode
from pruning_config import *
from models_config import *
def pretty_time(time_s):
time_s = int(round(time_s))
if time_s < 60:
return f"{time_s} sec"
elif time_s < 3600:
minutes = time_s // 60
seconds = time_s % 60
return f"{minutes} min {seconds} sec"
else:
hours = time_s // 3600
minutes = (time_s % 3600) // 60
seconds = time_s % 60
return f"{hours} hr {minutes} min {seconds} sec"
def get_pruning_idx_exponential(perc, n_layers, H):
N_target = int(round(perc * H * n_layers))
tot_pruned = [0] * n_layers
remaining_target = N_target
remaining_layers = list(range(1, n_layers))
while remaining_layers and remaining_target > 0:
weights = [2**i for i in remaining_layers]
Z = sum(weights)
weights = [w / Z for w in weights]
new_remaining_layers = []
for idx, w in zip(remaining_layers, weights):
alloc = int(round(w * remaining_target))
if tot_pruned[idx] + alloc >= H - 1:
tot_pruned[idx] = H - 1
else:
tot_pruned[idx] += alloc
new_remaining_layers.append(idx)
used = sum(tot_pruned)
remaining_target = N_target - used
remaining_layers = new_remaining_layers
# Se tutti i layer sono saturi, abilitiamo il layer 0
if not remaining_layers and tot_pruned[0] < H - 1 and remaining_target > 0:
remaining_layers = [0]
return tot_pruned
def transplant(src_model, dst_model):
"""
Copia i pesi da src_model (con piu' unita') a dst_model (potato).
Embedding, norme e testa si copiano direttamente. Ogni layer SSM copia i
propri pesi con load_pruned_from (definito nei layer, src/model/net/), che
seleziona le unita' usando gli indici GLOBALI, riferiti al modello denso:
funziona con qualunque sorgente che abbia almeno le unita' attive nella
destinazione, nei due pruned_mode.
"""
known = {"embedding", "norms", "dropouts", "norm_f", "fc", "match",
"s4d_layers", "s4_layers", "mamba_layers"}
extra = {n for n, _ in dst_model.named_children()} - known
assert not extra, f"moduli non gestiti da transplant: {sorted(extra)}"
dst_model.embedding.load_state_dict(src_model.embedding.state_dict())
for nm, ns in zip(src_model.norms, dst_model.norms):
ns.load_state_dict(nm.state_dict())
# norma finale (Mamba) e testa: fc, oppure match per i dataset a due sequenze
for name in ("norm_f", "fc", "match"):
if hasattr(dst_model, name) and hasattr(src_model, name):
getattr(dst_model, name).load_state_dict(getattr(src_model, name).state_dict())
for ls, ld in zip(mixers_of(src_model), mixers_of(dst_model)):
ld.load_pruned_from(ls)
def build_pruned_model(model_name, dataset_name, dataset, prev_model, active_idx, pruned_mode):
"""
Costruisce il modello con le unita' active_idx (pruned_mode indicato) e ci
copia i pesi di prev_model con transplant.
"""
assert pruned_mode in PRUNED_MODES, f"pruned_mode {pruned_mode} non valido: {PRUNED_MODES}"
c = MODELS_CONFIG[model_name][dataset_name]
model = NetFactory(
model_name=model_name,
dataset_name=dataset_name,
vocab_size=dataset.vocab_size,
input_size=dataset.input_size,
d_model=c["features"],
d_state=c["d_state"],
depth=c["depth"],
dropout=c["dropout"],
num_classes=dataset.num_classes,
norm=c["norm"],
pre_norm=c["pre-norm"],
active_idx_layers=active_idx,
dual_stream=dataset.dual_stream,
pool=getattr(dataset, "pool", "mean"),
pruned_mode=pruned_mode,
).get_net()
model.name = model_name
transplant(prev_model, model)
return model
def check_pruned_mode(ckpt, mode, model_name, path):
"""
I checkpoint di un modo non si caricano con i layer dell'altro, e non sono
la stessa funzione: non si riprende da un checkpoint potato nell'altro modo.
Un checkpoint denso (tutte le unita' attive) va bene per entrambi.
"""
if checkpoint_kind(ckpt, model_name) == "dense":
return
other = checkpoint_pruned_mode(ckpt, model_name, path)
if other != mode:
raise SystemExit(f"{path} e' stato potato con pruned_mode {other}, ma pruning_config.py "
f"chiede {mode} per questo metodo: usa un'altra cartella di uscita")
def prune_and_finetune(model_name, dataset_name, base_model_folder, checkpoint_folder):
config = MODELS_CONFIG
pc = finetune_params("s4op", model_name, dataset_name)
pc2 = PRUNING_CONFIG
mode = pc2["s4op"]["pruned_mode"]
assert mode in PRUNED_MODES, f"pruned_mode {mode} non valido: {PRUNED_MODES}"
print(f"Unita' spente: pruned_mode {mode}")
os.makedirs(checkpoint_folder, exist_ok=True)
last = None
pred = None
for perc in pc2["perc"]:
path = os.path.join(f"./{checkpoint_folder}", f"{model_name}_{dataset_name}_pruned_{int(perc*100)}%.pth")
if not os.path.exists(path):
last = perc
break
pred = perc
if last is None:
raise ValueError(f"Il pruning è già stato effettuato per le % selezionate.")
# Si parte dal modello base, oppure dal checkpoint dell'ultima % completata
if pred is None:
model_checkpoint = f"./{base_model_folder}/{model_name}_{dataset_name}_best.pth"
else:
model_checkpoint = os.path.join(f"./{checkpoint_folder}", f"{model_name}_{dataset_name}_pruned_{int(pred*100)}%.pth")
print(f"\nRipresa dal pruning {int(last*100)}% (partendo da {model_checkpoint})")
H = config[model_name][dataset_name]["features"]
if model_name == "mamba":
H = 2 * H # d_inner = expand * d_model (expand=2)
elif model_name == "mamba2":
H = (2 * H) // config[f"{model_name}"][f"{dataset_name}"]["headdim"]
n_layers = config[model_name][dataset_name]["depth"]
accuracies = {}
best_seeds = {}
timers = {}
# Solo le % non ancora completate
for perc in pc2["perc"][pc2["perc"].index(last):]:
print(f"\n=== PRUNING {perc*100}% ===")
best_acc = -1
best_val_acc = -1
best_seed = None
best_checkpoint = None
timers[perc] = {}
# Unita' attive del modello di partenza (e controllo del modo, prima di caricare i dati)
ckpt = torch.load(model_checkpoint, map_location="cpu")
check_pruned_mode(ckpt, mode, model_name, model_checkpoint)
prev_active = ckpt.get("active_idx_layers") or [list(range(H)) for _ in range(n_layers)]
prev_active = [[int(g) for g in idx] for idx in prev_active]
del ckpt
prev_model = ModelTest.from_pth(
model_path=model_checkpoint,
batch_size=config[model_name][dataset_name]["batch_size"],
valsplit=config["val_split"],
num_workers=config["num_workers"],
d_model=config[model_name][dataset_name]["features"],
d_state=config[model_name][dataset_name]["d_state"],
depth=config[model_name][dataset_name]["depth"],
dropout=config[model_name][dataset_name]["dropout"],
norm=config[model_name][dataset_name]["norm"],
pre_norm=config[model_name][dataset_name]["pre-norm"]
)
for seed in pc2["seeds"]:
t1 = time.time()
print(f"\n--- SEED {seed} ---")
set_seed(seed)
set_benchmark(False)
# Pruning incrementale
n_pruned_perc = get_pruning_idx_exponential(perc, n_layers, H)
n_pruned = [max(0, n_pruned_perc[i] - (H - len(prev_active[i]))) for i in range(n_layers)]
active_idx = [[] for _ in range(n_layers)]
for i in range(n_layers):
available = prev_active[i]
idx_to_prune = random.sample(available, n_pruned[i])
new_active = sorted(set(available) - set(idx_to_prune))
active_idx[i] = new_active
print(f"[Layer {i}]: teste rimanenti {len(active_idx[i])}/{H}")
# Modello potato, con i pesi delle unita' rimaste copiati dal precedente
model = build_pruned_model(model_name, dataset_name, prev_model.dataset,
prev_model.model, active_idx, mode)
model_test = ModelTest(model=model, dataset=prev_model.dataset)
model = model_test.model
dataset = model_test.dataset
# Fine-tuning
trainer = FineTuning(
model=model,
dataset=dataset,
epochs=pc["finetune_epochs"],
lr=pc["lr"],
weight_decay=pc["weight_decay"],
checkpoint_folder=os.path.join(f"./{checkpoint_folder}", f"{model_name}_{dataset_name}_seed{seed}_pruned_{int(perc*100)}%.pth"),
patience=pc["early_stopping"]
)
val_acc = trainer.run()
acc = model_test.run()
if val_acc > best_val_acc:
best_acc = acc
best_seed = seed
best_val_acc = val_acc
best_checkpoint = os.path.join(f"./{checkpoint_folder}", f"{model_name}_{dataset_name}_pruned_{int(perc*100)}%.pth")
torch.save(
{
"model_state_dict": model.state_dict(),
"active_idx_layers": active_idx,
"pruned_mode": mode
},
best_checkpoint + ".tmp"
)
t2 = time.time()
timers[perc][seed] = t2 - t1
# Pulizia memoria
del trainer
del model
del model_test
del dataset
gc.collect()
torch.cuda.empty_cache()
torch.cuda.synchronize()
# Tutti i seed finiti: il checkpoint diventa definitivo
os.replace(best_checkpoint + ".tmp", best_checkpoint)
# Aggiorna stato globale
accuracies[perc] = best_acc
best_seeds[perc] = best_seed
model_checkpoint = best_checkpoint
# Rimuovi checkpoint intermedi
seed_folder = os.path.join(f"./{checkpoint_folder}")
prefix = f"{model_name}_{dataset_name}_seed"
suffix = f"_pruned_{int(perc*100)}%.pth"
for filename in os.listdir(seed_folder):
if filename.startswith(prefix) and filename.endswith(suffix):
os.remove(os.path.join(seed_folder, filename))
print(f"\n=== ACCURACY MIGLIORI PER OGNI STEP ===")
for perc, acc in accuracies.items():
print(f" - Pruning {int(perc*100)}%: {acc:.2f}%. Best seed: {best_seeds[perc]}")
print(f"\n=== TEMPI DI ESECUZIONE ===")
for perc, seed_times in timers.items():
tot = sum(seed_times.values())
print(f"= Pruning {int(perc*100)}% =")
print(f"Tempo totale: {pretty_time(tot)}")
print(f"Tempo medio: {pretty_time(tot / len(seed_times))}")
for seed, t in seed_times.items():
print(f" - Seed {seed}: {pretty_time(t)}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run")
parser.add_argument(
"--model", "-m",
dest="model_name",
required=True,
help="Model name")
parser.add_argument(
"--dataset", "-d",
dest="dataset_name",
required=True,
help="Dataset name")
parser.add_argument(
"--checkpoint_folder", "-c",
dest="checkpoint_folder",
required=True,
help="Nome cartella dove salvare i checkpoint dei modelli prunati")
parser.add_argument(
"--base_model_folder", "-b",
dest="base_model_folder",
required=True,
help="Nome cartella da dove caricare i modelli base")
args = parser.parse_args()
t1 = time.time()
prune_and_finetune(args.model_name, args.dataset_name, args.base_model_folder, args.checkpoint_folder)
t2 = time.time()
print(f"\nTempo totale di esecuzione: {pretty_time(t2 - t1)}")
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.