ShynBui commited on
Commit
eb7e2af
·
1 Parent(s): 3e01496

Add application file

Browse files
Files changed (1) hide show
  1. app.py +92 -0
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import torch
3
+ from transformers import BertForSequenceClassification, AdamW
4
+ from torch.utils.data import DataLoader, TensorDataset
5
+ from transformers import BertTokenizer
6
+ import gradio as gr
7
+ import pandas as pd
8
+ import os
9
+ import spaces
10
+
11
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+ print(device)
13
+
14
+ model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
15
+ tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
16
+ model.to(device)
17
+
18
+ optimizer = AdamW(model.parameters(), lr=1e-5)
19
+
20
+ global_data = None
21
+
22
+ def load_data(file):
23
+ global global_data
24
+ df = pd.read_csv(file)
25
+ inputs = tokenizer(df['text'].tolist(), padding=True, truncation=True, return_tensors="pt") # Mã hóa văn bản
26
+ labels = torch.tensor(df['lable'].tolist()).long() #
27
+ global_data = TensorDataset(inputs['input_ids'], inputs['attention_mask'], labels)
28
+
29
+ print(global_data)
30
+
31
+ def get_dataloader(start, end, batch_size=8):
32
+ global global_data
33
+ subset = torch.utils.data.Subset(global_data, range(start, end))
34
+ return DataLoader(subset, batch_size=batch_size)
35
+
36
+ @spaces.GPU
37
+ def train_batch(dataloader):
38
+ model.train()
39
+ start_time = time.time()
40
+
41
+ for step, batch in enumerate(dataloader):
42
+ input_ids, attention_mask, labels = batch
43
+ input_ids, attention_mask, labels = input_ids.to(device), attention_mask.to(device), labels.to(device)
44
+
45
+ optimizer.zero_grad()
46
+ outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
47
+ loss = outputs.loss
48
+ loss.backward()
49
+ optimizer.step()
50
+
51
+ elapsed_time = time.time() - start_time
52
+ if elapsed_time > 55: # Dừng trước 60 giây để lưu checkpoint
53
+ torch.save(model.state_dict(), "./checkpoint/model.pt")
54
+ return False, "Checkpoint saved. Training paused."
55
+
56
+ return True, "Batch training completed."
57
+
58
+
59
+ def train_step(file=None):
60
+ if file:
61
+ load_data(file)
62
+ print(global_data)
63
+
64
+ start_idx = 0
65
+ batch_size = 8
66
+ total_samples = len(global_data)
67
+
68
+ counting = 0
69
+ while start_idx < total_samples:
70
+ print("Step:", counting)
71
+ counting = counting + 1
72
+ end_idx = min(start_idx + (batch_size * 10), total_samples) # 10 batches per loop
73
+ dataloader = get_dataloader(start_idx, end_idx, batch_size)
74
+
75
+ success, message = train_batch(dataloader)
76
+ if not success:
77
+ return message
78
+
79
+ start_idx = end_idx
80
+ time.sleep(5) # Nghỉ 5 giây giữa các phiên huấn luyện
81
+
82
+ torch.save(model.state_dict(), "./checkpoint/model.pt")
83
+ return "Training completed and model saved."
84
+
85
+
86
+ if __name__ == "__main__":
87
+ iface = gr.Interface(
88
+ fn=train_step,
89
+ inputs=gr.File(label="Upload CSV"),
90
+ outputs="text"
91
+ )
92
+ iface.launch()