-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathfinetune_basic.py
66 lines (51 loc) · 1.5 KB
/
finetune_basic.py
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
import os
import sys
import datasets
import torch
import torch.nn as nn
from typing import Any, Dict, List, Optional, Tuple, Union
from dataclasses import dataclass, field
from transformers import (
HfArgumentParser,
Trainer,
TrainingArguments,
)
import transformers
from transformers.trainer_utils import get_last_checkpoint
from torch.utils.data import Dataset
@dataclass
class FinetuneArguments:
dataset_path: str = field()
tokenizer_path: str = field()
model_path: str = field()
class ModifiedTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False):
return model(
input_ids=inputs["input_ids"],
attention_mask=torch.ones_like(inputs["input_ids"]),
labels=inputs["input_ids"],
).loss
def data_collator(features: list) -> dict:
batch = {
"input_ids": torch.stack([
torch.LongTensor(f["input_ids"][:7])
for f in features
])
}
return batch
def main():
finetune_args, training_args = HfArgumentParser((
FinetuneArguments,
TrainingArguments,
)).parse_args_into_dataclasses()
train_ds = datasets.load_from_disk(finetune_args.dataset_path)
model = transformers.AutoModelForCausalLM.from_pretrained(finetune_args.model_path)
trainer = ModifiedTrainer(
model=model,
args=training_args,
train_dataset=train_ds,
data_collator=data_collator,
)
trainer.train()
if __name__ == "__main__":
main()