Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import pipeline
|
3 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
4 |
+
from google.colab import files
|
5 |
+
|
6 |
+
# device = torch.device("cpu" if torch.cuda.is_available() else "cuda")
|
7 |
+
device = torch.device("cpu")
|
8 |
+
# Load the GPT-2 model and tokenizer
|
9 |
+
model = GPT2LMHeadModel.from_pretrained("gpt2")
|
10 |
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
11 |
+
# Add a padding token to the tokenizer
|
12 |
+
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
|
13 |
+
|
14 |
+
# Move the model to the appropriate device
|
15 |
+
model = model.to(device)
|
16 |
+
# Upload your documents
|
17 |
+
uploaded_files = files.upload()
|
18 |
+
training_data = []
|
19 |
+
for file_name, content in uploaded_files.items():
|
20 |
+
try:
|
21 |
+
document = content.decode("utf-8")
|
22 |
+
except UnicodeDecodeError:
|
23 |
+
document = content.decode("latin-1")
|
24 |
+
training_data.append(document)
|
25 |
+
# Fine-tuning the GPT-2 model
|
26 |
+
tokenized_data = tokenizer('\n\n'.join(training_data), truncation=True, padding=True, max_length=256, return_tensors="pt")
|
27 |
+
model.resize_token_embeddings(len(tokenizer))
|
28 |
+
|
29 |
+
# Define the loss function
|
30 |
+
loss_function = torch.nn.CrossEntropyLoss()
|
31 |
+
|
32 |
+
# Define the training loop
|
33 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-5)
|
34 |
+
# optimizer = torch.nn.Module(optimizer)
|
35 |
+
# optimizer = optimizer.to(device)
|
36 |
+
model.train()
|
37 |
+
accumulation_steps = 4
|
38 |
+
batch_size = 4
|
39 |
+
|
40 |
+
for epoch in range(3):
|
41 |
+
for i in range(0, len(tokenized_data['input_ids']), batch_size):
|
42 |
+
input_ids_batch = tokenized_data['input_ids'][i:i + batch_size].to(device, non_blocking=True)
|
43 |
+
outputs = model(input_ids_batch)
|
44 |
+
logits = outputs.logits
|
45 |
+
loss = loss_function(logits.view(-1, model.config.vocab_size), input_ids_batch.view(-1))
|
46 |
+
loss.backward()
|
47 |
+
optimizer.step()
|
48 |
+
optimizer.zero_grad()
|
49 |
+
print(f"Epoch: {epoch+1}, Batch: {i+1}/{len(tokenized_data['input_ids'])//batch_size}, Loss: {loss.item()}")
|
50 |
+
|
51 |
+
if (i + 1) % accumulation_steps == 0:
|
52 |
+
optimizer.step()
|
53 |
+
optimizer.zero_grad()
|
54 |
+
# Start chatting with your trained model
|
55 |
+
while True:
|
56 |
+
user_input = input("User: ")
|
57 |
+
input_ids = tokenizer.encode(user_input, return_tensors='pt').to(device)
|
58 |
+
generate = pipeline('text-generation', model='gpt2')
|
59 |
+
output = model.generate(input_ids=input_ids, max_length=100, num_return_sequences=1)
|
60 |
+
response = tokenizer.decode(output[0])
|
61 |
+
print("ChatBot:", response)
|
62 |
+
break # Add a condition to break the while loop
|