Upload finetune_eval.py with huggingface_hub
Browse files- finetune_eval.py +44 -12
finetune_eval.py
CHANGED
|
@@ -16,7 +16,7 @@ from huggingface_hub import HfApi
|
|
| 16 |
class XpertGPTForSequenceClassification(nn.Module):
|
| 17 |
def __init__(self, base_model, num_labels):
|
| 18 |
super().__init__()
|
| 19 |
-
self.transformer = base_model
|
| 20 |
self.config = base_model.config
|
| 21 |
self.classifier = nn.Linear(self.config.d_model, num_labels)
|
| 22 |
|
|
@@ -39,7 +39,7 @@ class XpertGPTForSequenceClassification(nn.Module):
|
|
| 39 |
class XpertGPTForMultipleChoice(nn.Module):
|
| 40 |
def __init__(self, base_model):
|
| 41 |
super().__init__()
|
| 42 |
-
self.transformer = base_model
|
| 43 |
self.config = base_model.config
|
| 44 |
self.scorer = nn.Linear(self.config.d_model, 1)
|
| 45 |
|
|
@@ -92,7 +92,8 @@ def train_classification(model, train_loader, val_loader, optimizer, epochs, dev
|
|
| 92 |
for epoch in range(epochs):
|
| 93 |
model.train()
|
| 94 |
total_loss = 0
|
| 95 |
-
|
|
|
|
| 96 |
optimizer.zero_grad()
|
| 97 |
input_ids = batch['input_ids'].to(device)
|
| 98 |
attention_mask = batch['attention_mask'].to(device)
|
|
@@ -103,10 +104,13 @@ def train_classification(model, train_loader, val_loader, optimizer, epochs, dev
|
|
| 103 |
|
| 104 |
loss.backward()
|
| 105 |
optimizer.step()
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
val_acc = evaluate_classification(model, val_loader, device)
|
| 109 |
-
print(f"Epoch {epoch+1} - Loss: {total_loss/len(train_loader):.4f} - Val Acc: {val_acc:.4f}")
|
| 110 |
|
| 111 |
if val_acc > best_acc:
|
| 112 |
best_acc = val_acc
|
|
@@ -137,7 +141,8 @@ def train_multiple_choice(model, train_loader, val_loader, optimizer, epochs, de
|
|
| 137 |
for epoch in range(epochs):
|
| 138 |
model.train()
|
| 139 |
total_loss = 0
|
| 140 |
-
|
|
|
|
| 141 |
optimizer.zero_grad()
|
| 142 |
input_ids = batch['input_ids'].to(device)
|
| 143 |
attention_mask = batch['attention_mask'].to(device)
|
|
@@ -148,10 +153,13 @@ def train_multiple_choice(model, train_loader, val_loader, optimizer, epochs, de
|
|
| 148 |
|
| 149 |
loss.backward()
|
| 150 |
optimizer.step()
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
val_acc = evaluate_multiple_choice(model, val_loader, device)
|
| 154 |
-
print(f"Epoch {epoch+1} - Loss: {total_loss/len(train_loader):.4f} - Val Acc: {val_acc:.4f}")
|
| 155 |
|
| 156 |
if val_acc > best_acc:
|
| 157 |
best_acc = val_acc
|
|
@@ -270,6 +278,18 @@ def main():
|
|
| 270 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 271 |
print(f"Using device: {device}")
|
| 272 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
model_id = "anonym5035/swi_glu_sw_64_16_8_4_xpert_gpt"
|
| 274 |
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 275 |
if tokenizer.pad_token is None:
|
|
@@ -281,28 +301,41 @@ def main():
|
|
| 281 |
os.makedirs("results", exist_ok=True)
|
| 282 |
|
| 283 |
# 1. SST-2
|
| 284 |
-
sst2_train, sst2_val = prep_sst2(tokenizer,
|
| 285 |
sst2_model = XpertGPTForSequenceClassification(base_model, num_labels=2).to(device)
|
|
|
|
|
|
|
|
|
|
| 286 |
optimizer = torch.optim.AdamW(sst2_model.parameters(), lr=args.lr, weight_decay=0.01)
|
| 287 |
acc = train_classification(sst2_model, sst2_train, sst2_val, optimizer, args.epochs, device, "SST-2")
|
| 288 |
results['SST-2'] = acc
|
| 289 |
|
| 290 |
# Reload fresh base model for next task
|
|
|
|
|
|
|
| 291 |
base_model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True)
|
| 292 |
|
| 293 |
# 2. COPA
|
| 294 |
-
copa_train, copa_val = prep_copa(tokenizer,
|
| 295 |
copa_model = XpertGPTForMultipleChoice(base_model).to(device)
|
|
|
|
|
|
|
|
|
|
| 296 |
optimizer = torch.optim.AdamW(copa_model.parameters(), lr=args.lr, weight_decay=0.01)
|
| 297 |
acc = train_multiple_choice(copa_model, copa_train, copa_val, optimizer, args.epochs, device, "COPA")
|
| 298 |
results['COPA'] = acc
|
| 299 |
|
| 300 |
# Reload fresh base model
|
|
|
|
|
|
|
| 301 |
base_model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True)
|
| 302 |
|
| 303 |
# 3. WinoGrande
|
| 304 |
-
wino_train, wino_val = prep_winogrande(tokenizer,
|
| 305 |
wino_model = XpertGPTForMultipleChoice(base_model).to(device)
|
|
|
|
|
|
|
|
|
|
| 306 |
optimizer = torch.optim.AdamW(wino_model.parameters(), lr=args.lr, weight_decay=0.01)
|
| 307 |
acc = train_multiple_choice(wino_model, wino_train, wino_val, optimizer, args.epochs, device, "WinoGrande")
|
| 308 |
results['WinoGrande'] = acc
|
|
@@ -324,7 +357,6 @@ def main():
|
|
| 324 |
repo_id=args.hf_repo,
|
| 325 |
path_in_repo="results"
|
| 326 |
)
|
| 327 |
-
# The script is uploading itself, let's just upload the results
|
| 328 |
print("Upload complete!")
|
| 329 |
|
| 330 |
if __name__ == "__main__":
|
|
|
|
| 16 |
class XpertGPTForSequenceClassification(nn.Module):
|
| 17 |
def __init__(self, base_model, num_labels):
|
| 18 |
super().__init__()
|
| 19 |
+
self.transformer = getattr(base_model, 'transformer', base_model)
|
| 20 |
self.config = base_model.config
|
| 21 |
self.classifier = nn.Linear(self.config.d_model, num_labels)
|
| 22 |
|
|
|
|
| 39 |
class XpertGPTForMultipleChoice(nn.Module):
|
| 40 |
def __init__(self, base_model):
|
| 41 |
super().__init__()
|
| 42 |
+
self.transformer = getattr(base_model, 'transformer', base_model)
|
| 43 |
self.config = base_model.config
|
| 44 |
self.scorer = nn.Linear(self.config.d_model, 1)
|
| 45 |
|
|
|
|
| 92 |
for epoch in range(epochs):
|
| 93 |
model.train()
|
| 94 |
total_loss = 0
|
| 95 |
+
pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{epochs}")
|
| 96 |
+
for batch in pbar:
|
| 97 |
optimizer.zero_grad()
|
| 98 |
input_ids = batch['input_ids'].to(device)
|
| 99 |
attention_mask = batch['attention_mask'].to(device)
|
|
|
|
| 104 |
|
| 105 |
loss.backward()
|
| 106 |
optimizer.step()
|
| 107 |
+
|
| 108 |
+
current_loss = loss.item()
|
| 109 |
+
total_loss += current_loss
|
| 110 |
+
pbar.set_postfix({'loss': f"{current_loss:.4f}"})
|
| 111 |
|
| 112 |
val_acc = evaluate_classification(model, val_loader, device)
|
| 113 |
+
print(f"Epoch {epoch+1} Summary - Avg Loss: {total_loss/len(train_loader):.4f} - Val Acc: {val_acc:.4f}")
|
| 114 |
|
| 115 |
if val_acc > best_acc:
|
| 116 |
best_acc = val_acc
|
|
|
|
| 141 |
for epoch in range(epochs):
|
| 142 |
model.train()
|
| 143 |
total_loss = 0
|
| 144 |
+
pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{epochs}")
|
| 145 |
+
for batch in pbar:
|
| 146 |
optimizer.zero_grad()
|
| 147 |
input_ids = batch['input_ids'].to(device)
|
| 148 |
attention_mask = batch['attention_mask'].to(device)
|
|
|
|
| 153 |
|
| 154 |
loss.backward()
|
| 155 |
optimizer.step()
|
| 156 |
+
|
| 157 |
+
current_loss = loss.item()
|
| 158 |
+
total_loss += current_loss
|
| 159 |
+
pbar.set_postfix({'loss': f"{current_loss:.4f}"})
|
| 160 |
|
| 161 |
val_acc = evaluate_multiple_choice(model, val_loader, device)
|
| 162 |
+
print(f"Epoch {epoch+1} Summary - Avg Loss: {total_loss/len(train_loader):.4f} - Val Acc: {val_acc:.4f}")
|
| 163 |
|
| 164 |
if val_acc > best_acc:
|
| 165 |
best_acc = val_acc
|
|
|
|
| 278 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 279 |
print(f"Using device: {device}")
|
| 280 |
|
| 281 |
+
# ---------------------------------------
|
| 282 |
+
# Setup DataParallel if multiple GPUs
|
| 283 |
+
# ---------------------------------------
|
| 284 |
+
num_gpus = torch.cuda.device_count()
|
| 285 |
+
if num_gpus > 1:
|
| 286 |
+
print(f"Detected {num_gpus} GPUs! Enabling nn.DataParallel.")
|
| 287 |
+
# If using DataParallel, we scale the batch size by the number of GPUs
|
| 288 |
+
effective_batch_size = args.batch_size * num_gpus
|
| 289 |
+
print(f"Scaling effective batch size to {effective_batch_size} (batch_size={args.batch_size} per GPU)")
|
| 290 |
+
else:
|
| 291 |
+
effective_batch_size = args.batch_size
|
| 292 |
+
|
| 293 |
model_id = "anonym5035/swi_glu_sw_64_16_8_4_xpert_gpt"
|
| 294 |
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 295 |
if tokenizer.pad_token is None:
|
|
|
|
| 301 |
os.makedirs("results", exist_ok=True)
|
| 302 |
|
| 303 |
# 1. SST-2
|
| 304 |
+
sst2_train, sst2_val = prep_sst2(tokenizer, effective_batch_size)
|
| 305 |
sst2_model = XpertGPTForSequenceClassification(base_model, num_labels=2).to(device)
|
| 306 |
+
if num_gpus > 1:
|
| 307 |
+
sst2_model = nn.DataParallel(sst2_model)
|
| 308 |
+
|
| 309 |
optimizer = torch.optim.AdamW(sst2_model.parameters(), lr=args.lr, weight_decay=0.01)
|
| 310 |
acc = train_classification(sst2_model, sst2_train, sst2_val, optimizer, args.epochs, device, "SST-2")
|
| 311 |
results['SST-2'] = acc
|
| 312 |
|
| 313 |
# Reload fresh base model for next task
|
| 314 |
+
del sst2_model
|
| 315 |
+
torch.cuda.empty_cache()
|
| 316 |
base_model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True)
|
| 317 |
|
| 318 |
# 2. COPA
|
| 319 |
+
copa_train, copa_val = prep_copa(tokenizer, effective_batch_size)
|
| 320 |
copa_model = XpertGPTForMultipleChoice(base_model).to(device)
|
| 321 |
+
if num_gpus > 1:
|
| 322 |
+
copa_model = nn.DataParallel(copa_model)
|
| 323 |
+
|
| 324 |
optimizer = torch.optim.AdamW(copa_model.parameters(), lr=args.lr, weight_decay=0.01)
|
| 325 |
acc = train_multiple_choice(copa_model, copa_train, copa_val, optimizer, args.epochs, device, "COPA")
|
| 326 |
results['COPA'] = acc
|
| 327 |
|
| 328 |
# Reload fresh base model
|
| 329 |
+
del copa_model
|
| 330 |
+
torch.cuda.empty_cache()
|
| 331 |
base_model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True)
|
| 332 |
|
| 333 |
# 3. WinoGrande
|
| 334 |
+
wino_train, wino_val = prep_winogrande(tokenizer, effective_batch_size)
|
| 335 |
wino_model = XpertGPTForMultipleChoice(base_model).to(device)
|
| 336 |
+
if num_gpus > 1:
|
| 337 |
+
wino_model = nn.DataParallel(wino_model)
|
| 338 |
+
|
| 339 |
optimizer = torch.optim.AdamW(wino_model.parameters(), lr=args.lr, weight_decay=0.01)
|
| 340 |
acc = train_multiple_choice(wino_model, wino_train, wino_val, optimizer, args.epochs, device, "WinoGrande")
|
| 341 |
results['WinoGrande'] = acc
|
|
|
|
| 357 |
repo_id=args.hf_repo,
|
| 358 |
path_in_repo="results"
|
| 359 |
)
|
|
|
|
| 360 |
print("Upload complete!")
|
| 361 |
|
| 362 |
if __name__ == "__main__":
|