Spaces:
Runtime error
Runtime error
Update train.py
Browse files
train.py
CHANGED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import MBartForSequenceClassification, MBart50Tokenizer, TrainingArguments, Trainer
|
2 |
+
from datasets import Dataset
|
3 |
+
|
4 |
+
|
5 |
+
# Load the model and tokenizer
|
6 |
+
model_name = "LocalDoc/mbart_large_qa_azerbaijan" # Replace with your model name if different
|
7 |
+
tokenizer = MBart50Tokenizer.from_pretrained(model_name)
|
8 |
+
model = MBartForSequenceClassification.from_pretrained(model_name)
|
9 |
+
chunk_size = 512
|
10 |
+
|
11 |
+
# Prepare the dataset (simplified)
|
12 |
+
def prepare_text_dataset(data):
|
13 |
+
# Split the text into smaller chunks (consider logical divisions of the Constitution)
|
14 |
+
chunks = [data[i:i+chunk_size] for i in range(0, len(data), chunk_size)]
|
15 |
+
# Convert chunks to dictionaries with a single feature "text"
|
16 |
+
formatted_data = [{"text": chunk} for chunk in chunks]
|
17 |
+
# Create the dataset from the list of dictionaries
|
18 |
+
formatted_dataset = Dataset.from_list(formatted_data)
|
19 |
+
# Tokenize the text using the MBart tokenizer
|
20 |
+
formatted_dataset = formatted_dataset.map(
|
21 |
+
lambda x: tokenizer(x["text"], truncation=True, padding="max_length"),
|
22 |
+
batched=True
|
23 |
+
)
|
24 |
+
|
25 |
+
# Set the format of the dataset to "torch" for compatibility with the model
|
26 |
+
formatted_dataset.set_format("torch")
|
27 |
+
# Print a message indicating preparation completion (optional)
|
28 |
+
print('Prep done')
|
29 |
+
|
30 |
+
return formatted_dataset
|
31 |
+
|
32 |
+
|
33 |
+
# Load the plain text (replace with your actual loading logic)
|
34 |
+
with open("constitution.txt", "r", encoding="utf-8") as f:
|
35 |
+
constitution_text = f.read()
|
36 |
+
|
37 |
+
# Prepare the dataset
|
38 |
+
train_dataset = prepare_text_dataset(constitution_text)
|
39 |
+
|
40 |
+
# Define training arguments
|
41 |
+
training_args = TrainingArguments(
|
42 |
+
output_dir="./results", # Adjust output directory
|
43 |
+
overwrite_output_dir=True,
|
44 |
+
num_train_epochs=3, # Adjust training epochs
|
45 |
+
per_device_train_batch_size=1, # Adjust batch size based on your GPU memory
|
46 |
+
save_steps=500,
|
47 |
+
save_total_limit=2,
|
48 |
+
)
|
49 |
+
|
50 |
+
# Create the Trainer
|
51 |
+
trainer = Trainer(
|
52 |
+
model=model,
|
53 |
+
args=training_args,
|
54 |
+
train_dataset=train_dataset,
|
55 |
+
)
|
56 |
+
|
57 |
+
# Start training
|
58 |
+
trainer.train()
|
59 |
+
|
60 |
+
# Save the fine-tuned model
|
61 |
+
model.save_pretrained("./fine-tuned_model")
|
62 |
+
tokenizer.save_pretrained("./fine-tuned_model")
|