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

Expand file tree

/

starting_model.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
218 lines (194 loc) · 10.5 KB
/

starting_model.py

Copy path

File metadata and controls

218 lines (194 loc) · 10.5 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
import os
import argparse
import torch
if torch.cuda.is_available() and not torch.cuda.is_initialized():
torch.cuda.current_device()
from models_config import *
from src.model import ModelTrain, ModelTest, ModelInfo, ModelProfile
from src.model.utils import set_benchmark, set_seed, setup_optimizer
set_seed(42)
set_benchmark(False)
def main(model_name, dataset_name, checkpoints_folder, pruned_model_name):
# Caricamento configurazione
config = MODELS_CONFIG
# Creazione path modello
if pruned_model_name is None:
model_path = os.path.join(f"./{checkpoints_folder}", f"{model_name}_{dataset_name}_best.pth")
else:
model_path = os.path.join(f"./{checkpoints_folder}", f"{pruned_model_name}.pth")
# d_model
H = config[f"{model_name}"][f"{dataset_name}"]["features"]
d_model = H
if model_name == "mamba":
H = int(round(2 * H))
elif model_name == "mamba2":
H = int(round(2 * H)) // config[f"{model_name}"][f"{dataset_name}"]["headdim"]
# Se il modello non esiste, lo alleno
if (not os.path.exists(model_path)) and (pruned_model_name is None):
# Creazione modello
model_train = ModelTrain.from_scratch(
model_name=model_name,
dataset_name=dataset_name,
batch_size=config[f"{model_name}"][f"{dataset_name}"]["batch_size"],
valsplit=config["val_split"],
num_workers=config["num_workers"],
d_model=d_model,
d_state=config[f"{model_name}"][f"{dataset_name}"]["d_state"],
depth=config[f"{model_name}"][f"{dataset_name}"]["depth"],
dropout=config[f"{model_name}"][f"{dataset_name}"]["dropout"],
norm=config[f"{model_name}"][f"{dataset_name}"]["norm"],
pre_norm=config[f"{model_name}"][f"{dataset_name}"]["pre-norm"],
active_idx_layers=[list(range(H)) for _ in range(config[f"{model_name}"][f"{dataset_name}"]["depth"])]
)
print(f"\nModello: {model_name}, Dataset: {dataset_name}")
print(model_train.model)
criterion = torch.nn.BCEWithLogitsLoss() if model_train.dataset.multilabel else torch.nn.CrossEntropyLoss()
optimizer, scheduler = setup_optimizer(
model_train.model,
lr=config[f"{model_name}"][f"{dataset_name}"]["lr"],
weight_decay=config[f"{model_name}"][f"{dataset_name}"]["wd"],
epochs=config[f"{model_name}"][f"{dataset_name}"]["epochs"],
)
print(f"\nStarting training for {config[f'{model_name}'][f'{dataset_name}']['epochs']} epochs with batch size {config[f'{model_name}'][f'{dataset_name}']['batch_size']}...")
# Training
model_train.run(optimizer, scheduler, criterion, config[f"{model_name}"][f"{dataset_name}"]["epochs"], checkpoints_folder=os.path.join(".", f"{checkpoints_folder}"), is_pruned=False, patience=config[f"{model_name}"][f"{dataset_name}"]["patience"])
# Testing
model_test = ModelTest.from_pth(model_path=model_path,
batch_size=config[f"{model_name}"][f"{dataset_name}"]["batch_size"],
valsplit=config["val_split"],
num_workers=config["num_workers"],
d_model=d_model,
d_state=config[f"{model_name}"][f"{dataset_name}"]["d_state"],
depth=config[f"{model_name}"][f"{dataset_name}"]["depth"],
dropout=config[f"{model_name}"][f"{dataset_name}"]["dropout"],
norm=config[f"{model_name}"][f"{dataset_name}"]["norm"],
pre_norm=config[f"{model_name}"][f"{dataset_name}"]["pre-norm"],
)
print("\nStarting testing...")
model_test.run()
# Model Info
model_info = ModelInfo(
model=model_test.model,
vocab_size=model_test.dataset.vocab_size,
input_size=model_test.dataset.input_size,
seq_len=model_test.dataset.seq_len,
batch_size=config[f"{model_name}"][f"{dataset_name}"]["batch_size"],
dual_stream=model_test.dataset.dual_stream,
dataset_name=dataset_name
)
os.makedirs("model_info", exist_ok=True)
if not os.path.exists(f"./model_info/{model_name}_{dataset_name}_torchinfo.txt"):
model_info.torchinfo(output_dir="model_info", name=f"{model_name}_{dataset_name}")
print("\nModel info salvato nella cartella 'model_info'")
else:
print("\nModel info già esistente nella cartella 'model_info', salto la creazione")
# Model Profile
model_profile = ModelProfile(iterations=100)
model_profile.add("prova")
model_profile.run("prova", model_test.model, model_info.get_example_input, iterations=100)
model_profile.info("prova")
# Se il modello esiste ed è stato specificato un modello prunato
elif pruned_model_name is not None:
if not os.path.exists(model_path):
raise FileNotFoundError(f"Pruned model path {model_path} does not exist.")
print(f"\nLoading pruned model from path {model_path}...")
# Testing
model_test = ModelTest.from_pth(model_path=model_path,
batch_size=config[f"{model_name}"][f"{dataset_name}"]["batch_size"],
valsplit=config["val_split"],
num_workers=config["num_workers"],
d_model=d_model,
d_state=config[f"{model_name}"][f"{dataset_name}"]["d_state"],
depth=config[f"{model_name}"][f"{dataset_name}"]["depth"],
dropout=config[f"{model_name}"][f"{dataset_name}"]["dropout"],
norm=config[f"{model_name}"][f"{dataset_name}"]["norm"],
pre_norm=config[f"{model_name}"][f"{dataset_name}"]["pre-norm"]
)
print("\nStarting testing...")
model_test.run()
print("\nStarting model profiling...")
# Model Info
model_info = ModelInfo(
model=model_test.model,
vocab_size=model_test.dataset.vocab_size,
input_size=model_test.dataset.input_size,
seq_len=model_test.dataset.seq_len,
batch_size=config[f"{model_name}"][f"{dataset_name}"]["batch_size"],
dual_stream=model_test.dataset.dual_stream,
dataset_name=dataset_name
)
os.makedirs("model_info_pruned_structural", exist_ok=True)
if not os.path.exists(f"./model_info_pruned_structural/{pruned_model_name}_torchinfo.txt"):
model_info.torchinfo(output_dir="model_info_pruned_structural", name=pruned_model_name)
print("\nModel info salvato nella cartella 'model_info_pruned_structural'")
else:
print("\nModel info già esistente nella cartella 'model_info_pruned_structural', salto la creazione")
# Model Profile
model_profile = ModelProfile(iterations=100)
model_profile.add("prova")
model_profile.run("prova", model_test.model, model_info.get_example_input, iterations=100)
model_profile.info("prova")
# Se il modello esiste (e non è stato specificato un modello prunato), salto l'addestramento
else:
print(f"\nSkipping training because model path {model_path} already exists")
# Testing
model_test = ModelTest.from_pth(model_path=model_path,
batch_size=config[f"{model_name}"][f"{dataset_name}"]["batch_size"],
valsplit=config["val_split"],
num_workers=config["num_workers"],
d_model=d_model,
d_state=config[f"{model_name}"][f"{dataset_name}"]["d_state"],
depth=config[f"{model_name}"][f"{dataset_name}"]["depth"],
dropout=config[f"{model_name}"][f"{dataset_name}"]["dropout"],
norm=config[f"{model_name}"][f"{dataset_name}"]["norm"],
pre_norm=config[f"{model_name}"][f"{dataset_name}"]["pre-norm"]
)
print("\nStarting testing...")
model_test.run()
print("\nStarting model profiling...")
# Model Info
model_info = ModelInfo(
model=model_test.model,
vocab_size=model_test.dataset.vocab_size,
input_size=model_test.dataset.input_size,
seq_len=model_test.dataset.seq_len,
batch_size=config[f"{model_name}"][f"{dataset_name}"]["batch_size"],
dual_stream=model_test.dataset.dual_stream,
dataset_name=dataset_name
)
os.makedirs("model_info", exist_ok=True)
if not os.path.exists(f"./model_info/{model_name}_{dataset_name}_torchinfo.txt"):
model_info.torchinfo(output_dir="model_info", name=f"{model_name}_{dataset_name}")
print("\nModel info salvato nella cartella 'model_info'")
else:
print("\nModel info già esistente nella cartella 'model_info', salto la creazione")
# Model Profile
model_profile = ModelProfile(iterations=100)
model_profile.add("prova")
model_profile.run("prova", model_test.model, model_info.get_example_input, iterations=100)
model_profile.info("prova")
# Main
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(
"--checkpoints-folder", "-f",
dest="checkpoints_folder",
required=True, default=os.path.join(".", "checkpoints"),
help="Checkpoints folder")
parser.add_argument(
"--pruned-model", "-p",
dest="pruned_model_name",
required=False, default=None,
help="Pruned model index")
args = parser.parse_args()
main(args.model_name, args.dataset_name, args.checkpoints_folder, args.pruned_model_name)
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.