-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
160 lines (139 loc) · 5 KB
/
train.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
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
# Import the required library
import evaluate
from transformers import BeitFeatureExtractor, AutoModelForImageClassification, TrainingArguments, Trainer, AdamW
import torch
from datasets import load_dataset
from torchvision.transforms import (
CenterCrop,
Compose,
Normalize,
RandomHorizontalFlip,
RandomResizedCrop,
Resize,
ToTensor,
)
import numpy as np
from pynvml import *
from PIL import Image, ImageFile
# make pillow work properly
Image.MAX_IMAGE_PIXELS = None
ImageFile.LOAD_TRUNCATED_IMAGES = True
if __name__ == '__main__':
# Load models and dataset
dataset = load_dataset("imagefolder", data_dir="Dataset", num_proc=8)
batch_size = 10
beit_model = "microsoft/beit-base-patch16-224" # 384
feature_extractor = BeitFeatureExtractor.from_pretrained(beit_model)
# create lookups
labels = dataset["train"].features["label"].names
label2id, id2label = dict(), dict()
for i, label in enumerate(labels):
label2id[label] = i
id2label[i] = label
# set up eval metric
metric = evaluate.load("accuracy")
# Function to compute evaluation metrics
def compute_metrics(eval_pred):
predictions = np.argmax(eval_pred.predictions, axis=1)
return metric.compute(predictions=predictions, references=eval_pred.label_ids)
# Function to collate data for training
def collate_fn(examples):
pixel_values = torch.stack([example["pixel_values"] for example in examples])
labels2 = torch.tensor([example["label"] for example in examples])
return {"pixel_values": pixel_values, "labels": labels2}
# Splitting dataset into training and validation sets
splits = dataset['train'].train_test_split(test_size=0.1)
train_ds = splits['train']
val_ds = splits['test']
img_size = (feature_extractor.size['width'], feature_extractor.size['height'])
# Data augmentation and normalization transforms
normalize = Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
train_transforms = Compose(
[
RandomResizedCrop(img_size),
RandomHorizontalFlip(),
ToTensor(),
normalize,
]
)
val_transforms = Compose(
[
Resize(img_size),
CenterCrop(img_size),
ToTensor(),
normalize,
]
)
# Preprocessing function for training set
def preprocess_train(example_batch):
example_batch["pixel_values"] = [
train_transforms(image.convert("RGB")) for image in example_batch["image"]
]
return example_batch
# Preprocessing function for validation set
def preprocess_val(example_batch):
example_batch["pixel_values"] = [val_transforms(image.convert("RGB")) for image in example_batch["image"]]
return example_batch
# Function to print GPU utilization
def print_gpu_utilization():
nvmlInit()
handle = nvmlDeviceGetHandleByIndex(0)
info = nvmlDeviceGetMemoryInfo(handle)
print(f"GPU memory occupied: {info.used // 1024 ** 2} MB.")
# Function to print training summary
def print_summary(result):
print(f"Time: {result.metrics['train_runtime']:.2f}")
print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}")
print_gpu_utilization()
# Applying preprocessing functions to datasets
train_ds.set_transform(preprocess_train)
val_ds.set_transform(preprocess_val)
# Load BEiT model for image classification
model = AutoModelForImageClassification.from_pretrained(
beit_model,
label2id=label2id,
id2label=id2label,
ignore_mismatched_sizes=True
).to("cpu")
# Setting up training arguments
train_args = TrainingArguments(
f"yuuki0\\test",
remove_unused_columns=False,
evaluation_strategy="steps",
eval_steps=10,
save_strategy="steps",
learning_rate=5e-5,
per_device_train_batch_size=batch_size,
gradient_accumulation_steps=4,
per_device_eval_batch_size=batch_size,
num_train_epochs=1,
warmup_ratio=0.1,
logging_steps=10,
load_best_model_at_end=True,
metric_for_best_model="accuracy",
push_to_hub=False,
report_to=[],
lr_scheduler_type="cosine",
optim='adamw_hf',
)
# Creating trainer object
trainer = Trainer(
model,
train_args,
train_dataset=train_ds,
eval_dataset=val_ds,
tokenizer=feature_extractor,
compute_metrics=compute_metrics,
data_collator=collate_fn,
)
# Training the model
train_results = trainer.train()
# Saving training metrics and state
trainer.save_model()
trainer.log_metrics("train", train_results.metrics)
trainer.save_metrics("train", train_results.metrics)
trainer.save_state()
# Evaluating and saving the best model
metrics = trainer.evaluate()
trainer.log_metrics("eval", metrics)
trainer.save_metrics("eval", metrics)