Chamsol's picture
Upload 15 files
01b54d8 verified
Raw History Blame Contribute Delete
5.75 kB
#pre_train.py
#ec2-train
from transformers import AutoModelForSequenceClassification
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pandas as pd
from transformers import EvalPrediction
from sklearn.metrics import accuracy_score
from transformers import TrainerCallback
# GPU μ‚¬μš© κ°€λŠ₯ 확인 및 device μ„€μ •
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# SentimentDataset 클래슀 μ •μ˜
class SentimentDataset(Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
# CSV 파일 λ‘œλ“œ
import pandas as pd
df = pd.read_csv('/home/ec2-user/train_org.csv') # 'your_dataset.csv'λ₯Ό μ‹€μ œ 파일 경둜둜 λ³€κ²½ν•˜μ„Έμš”.
# 데이터 μ „μ²˜λ¦¬
texts = df['document'].tolist() # 리뷰 ν…μŠ€νŠΈ
labels = df['label'].tolist() # 라벨 λ°μ΄ν„°λŠ” μ •μˆ˜λ‘œ λ³€ν™˜λ˜μ–΄ μžˆμ–΄μ•Ό ν•©λ‹ˆλ‹€..
labels = [int(label) for label in labels] # 라벨을 μ •μˆ˜ν˜•μœΌλ‘œ λ³€ν™˜
texts = [str(text) for text in texts if text is not None]
# ν† ν¬λ‚˜μ΄μ € λ‘œλ”©
tokenizer_roberta = AutoTokenizer.from_pretrained("klue/roberta-large")
tokenizer_electra = AutoTokenizer.from_pretrained("monologg/koelectra-base-v3-discriminator")
# 데이터셋 토큰화
encodings_roberta = tokenizer_roberta(texts, truncation=True, padding=True, max_length=128)
encodings_electra = tokenizer_electra(texts, truncation=True, padding=True, max_length=128)
# 데이터셋 생성
dataset_roberta = SentimentDataset(encodings_roberta, labels)
dataset_electra = SentimentDataset(encodings_electra, labels)
# λ‘œλ“œν•  RoBERTa λͺ¨λΈ 경둜
roberta_model_path = "/home/ec2-user/roberta_model"
# λ‘œλ“œν•  Electra λͺ¨λΈ 경둜
electra_model_path = "/home/ec2-user/electra_model"
# μ €μž₯된 λͺ¨λΈ λ‘œλ“œ
model_roberta = AutoModelForSequenceClassification.from_pretrained(roberta_model_path)
model_electra = AutoModelForSequenceClassification.from_pretrained(electra_model_path)
# μ‚¬μš©μž μ§€μ • 콜백 클래슀 μ •μ˜
class PrintProgressCallback(TrainerCallback):
def on_epoch_end(self, args, state, control, **kwargs):
print(f"Epoch {state.epoch} μ’…λ£Œ. μ§„ν–‰ μƒνƒœ: {state.global_step}/{state.max_steps} ({(state.global_step/state.max_steps)*100:.2f}%)")
if 'eval_metrics' in kwargs:
print(f"Epoch {state.epoch} Accuracy: {kwargs['eval_metrics']['eval_accuracy']:.4f}")
# μœ„μ—μ„œ μ •μ˜ν•œ compute_metrics ν•¨μˆ˜ μ‚¬μš©
def compute_metrics(p: EvalPrediction):
preds = np.argmax(p.predictions, axis=1)
return {"accuracy": accuracy_score(p.label_ids, preds)}
class CustomTrainer(Trainer):
def __init__(self, label_weights, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label_weights = label_weights
def compute_loss(self, model, inputs, return_outputs=False):
labels = inputs.get("labels")
# λͺ¨λΈμ˜ 좜λ ₯μ—μ„œ 둜슀 계산
outputs = model(**inputs)
logits = outputs.get('logits')
# κ°€μ€‘μΉ˜ μ μš©ν•˜μ—¬ 둜슀 계산
loss_fct = torch.nn.CrossEntropyLoss(weight=self.label_weights)
loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
return (loss, outputs) if return_outputs else loss
# def on_step_end(self, args, state, control, **kwargs):
# super().on_step_end(args, state, control, **kwargs)
# # λ§€ 1000 μŠ€ν…λ§ˆλ‹€ λͺ¨λΈ μ €μž₯
# if state.global_step % 10 == 0:
# output_dir1 = f"{args.output_dir1}/checkpoint-{state.global_step}"
# self.save_model(output_dir1)
# print(f"λͺ¨λΈμ„ {output_dir1}에 μ €μž₯ν–ˆμŠ΅λ‹ˆλ‹€.")
# if state.global_step % 10 == 0:
# output_dir2 = f"{args.output_dir2}/checkpoint-{state.global_step}"
# self.save_model(output_dir2)
# print(f"λͺ¨λΈμ„ {output_dir2}에 μ €μž₯ν–ˆμŠ΅λ‹ˆλ‹€.")
# TrainingArguments μ„€μ •
training_args = TrainingArguments(
output_dir= './result',
num_train_epochs=1,
per_device_train_batch_size=32,
warmup_steps=160000000,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=800,
)
# 라벨 κ°€μ€‘μΉ˜ μ„€μ •
# μ˜ˆμ‹œ: 각 라벨에 λŒ€ν•œ κ°€μ€‘μΉ˜κ°€ λ™μΌν•˜λ‹€κ³  κ°€μ •
label_weights = torch.tensor([1.0, 1.0, 1.0, 1.0]).to(device)
# CustomTrainer μΈμŠ€ν„΄μŠ€ 생성 μ‹œ μ‚¬μš©μž μ§€μ • 콜백 μΆ”κ°€
trainer_roberta = CustomTrainer(
model=model_roberta,
args=training_args,
train_dataset=dataset_roberta,
label_weights=label_weights,
compute_metrics=compute_metrics,
callbacks=[PrintProgressCallback()], # 콜백 μΆ”κ°€
)
trainer_electra = CustomTrainer(
model=model_electra,
args=training_args,
train_dataset=dataset_electra,
label_weights=label_weights,
compute_metrics=compute_metrics,
callbacks=[PrintProgressCallback()], # 콜백 μΆ”κ°€
)
# ν›ˆλ ¨ μ‹œμž‘
trainer_roberta.train()
trainer_electra.train()
# ν›ˆλ ¨λœ RoBERTa λͺ¨λΈ μ €μž₯
model_save_path = "/home/ec2-user/to/save/roberta_model"
trainer_roberta.save_model(model_save_path)
# ν›ˆλ ¨λœ Electra λͺ¨λΈ μ €μž₯
model_save_path = "/home/ec2-user/to/save/electra_model"
trainer_electra.save_model(model_save_path)