Marcus Gawronsky commited on
Commit
9afa7a5
1 Parent(s): 27efffc

Create trainer.py

Browse files
Files changed (1) hide show
  1. trainer.py +86 -0
trainer.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # We want to train a classification model on our own data
2
+ from transformers import AutoImageProcessor, AutoModelForImageClassification, TrainingArguments, Trainer
3
+ from sklearn.preprocessing import LabelEncoder, OneHotEncoder
4
+ import numpy as np
5
+ import pandas as pd
6
+ from datasets import load_dataset, load_from_disk
7
+ import torch
8
+ from joblib import cpu_count
9
+ from fire import Fire
10
+
11
+ def get_feature_function(preprocessor, encoder):
12
+ def feature_extraction_function(examples):
13
+ data = {}
14
+ data["pixel_values"] = preprocessor(examples["image"]).pixel_values
15
+
16
+ data['label'] = np.eye(len(encoder.classes_))[encoder.transform(examples['product_subcategory_name'])]
17
+ return data
18
+
19
+ return feature_extraction_function
20
+
21
+
22
+ def train(
23
+ dataset_id,
24
+ hub_model_id,
25
+ model_id = 'facebook/convnextv2-atto-1k-224',
26
+ run_id = 'convextv2-atto-dataset',
27
+ logging_steps = 100
28
+ )
29
+ dataset = load_dataset(dataset_id)
30
+ preprocessor = AutoImageProcessor.from_pretrained(model_id)
31
+
32
+
33
+ labels = np.unique(dataset['train']['product_subcategory_name'])
34
+ encoder = LabelEncoder().fit(y=labels)
35
+
36
+ model = AutoModelForImageClassification.from_pretrained(model_id,
37
+ ignore_mismatched_sizes=True,
38
+ num_labels=len(encoder.classes_),
39
+ id2label={i: label for i, label in enumerate(encoder.classes_)},
40
+ label2id={label: i for i, label in enumerate(encoder.classes_)}
41
+ )
42
+
43
+ dataset.set_transform(get_feature_function(preprocessor, encoder))
44
+
45
+ training_args = TrainingArguments(
46
+ output_dir=f"results/{run_id}",
47
+ remove_unused_columns=False,
48
+ learning_rate=5e-5,
49
+ per_device_train_batch_size=32,
50
+ gradient_accumulation_steps=4,
51
+ per_device_eval_batch_size=16,
52
+ num_train_epochs=3,
53
+ warmup_ratio=0.1,
54
+ report_to=['tensorboard'],
55
+ run_name=run_id,
56
+ logging_steps=logging_steps,
57
+ eval_steps=logging_steps,
58
+ save_steps=logging_steps,
59
+ save_total_limit=1,
60
+ save_strategy="steps",
61
+ evaluation_strategy="steps",
62
+ skip_memory_metrics=False,
63
+ logging_first_step=True,
64
+ push_to_hub=True,
65
+ hub_model_id=hub_model_id,
66
+ hub_private_repo=True,
67
+ hub_strategy="every_save",
68
+ save_safetensors=True,
69
+
70
+ # memory
71
+ dataloader_num_workers=cpu_count()//4, # we have to prefetch the data to ensure efficient and stable GPU utilization
72
+ dataloader_pin_memory=True
73
+ )
74
+
75
+ trainer = Trainer(
76
+ model=model,
77
+ args=training_args,
78
+ train_dataset=dataset["train"],
79
+ eval_dataset=dataset["test"]
80
+ )
81
+
82
+ trainer.train()
83
+
84
+
85
+ if __name__ == '__main__':
86
+ Fire(train)