Spaces:
Sleeping
Sleeping
Create roberta-base-squad2
Browse files- deepset/roberta-base-squad2 +175 -0
deepset/roberta-base-squad2
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""Untitled7.ipynb
|
3 |
+
Automatically generated by Colab.
|
4 |
+
Original file is located at
|
5 |
+
https://colab.research.google.com/drive/1MWc3B3JSbW5VvEuftDi2WoCjUWN1CtVj
|
6 |
+
"""
|
7 |
+
pip install transformers datasets evaluate accelerate
|
8 |
+
data_files = {
|
9 |
+
"train": "./train.json", # If saved in current working directory
|
10 |
+
"validation": "./validation.json"
|
11 |
+
}
|
12 |
+
from google.colab import files
|
13 |
+
uploaded = files.upload() # Select and upload your train.json and validation.json files
|
14 |
+
from google.colab import files
|
15 |
+
uploaded = files.upload() # Select and upload your train.json and validation.json files
|
16 |
+
import json
|
17 |
+
import pandas as pd
|
18 |
+
from datasets import Dataset, DatasetDict
|
19 |
+
with open("train.json", "r") as f:
|
20 |
+
train_data = json.load(f)
|
21 |
+
with open("validation.json", "r") as f:
|
22 |
+
validation_data = json.load(f)
|
23 |
+
train_list = train_data.get("data", [])
|
24 |
+
validation_list = validation_data.get("data", [])
|
25 |
+
train_df = pd.DataFrame(train_list)
|
26 |
+
validation_df = pd.DataFrame(validation_list)
|
27 |
+
train_dataset = Dataset.from_pandas(train_df)
|
28 |
+
validation_dataset = Dataset.from_pandas(validation_df)
|
29 |
+
dataset = DatasetDict({
|
30 |
+
"train": train_dataset,
|
31 |
+
"validation": validation_dataset
|
32 |
+
})
|
33 |
+
print(dataset)
|
34 |
+
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
|
35 |
+
model_checkpoint = "deepset/roberta-base-squad2"
|
36 |
+
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
|
37 |
+
model = AutoModelForQuestionAnswering.from_pretrained(model_checkpoint)
|
38 |
+
def prepare_features(examples):
|
39 |
+
tokenized_examples = {
|
40 |
+
"input_ids": [],
|
41 |
+
"attention_mask": [],
|
42 |
+
"offset_mapping": [],
|
43 |
+
"overflow_to_sample_mapping": [],
|
44 |
+
"start_positions": [],
|
45 |
+
"end_positions": [],
|
46 |
+
"example_id": [], # Add example_id to link back to original examples
|
47 |
+
}
|
48 |
+
|
49 |
+
for example_index, paragraphs in enumerate(examples["paragraphs"]):
|
50 |
+
for para in paragraphs:
|
51 |
+
context = para["context"]
|
52 |
+
for qa in para["qas"]:
|
53 |
+
question = qa["question"]
|
54 |
+
answers = qa["answers"] # This is a list of answer dictionaries
|
55 |
+
tokenized = tokenizer(
|
56 |
+
question,
|
57 |
+
context,
|
58 |
+
truncation="only_second",
|
59 |
+
max_length=384,
|
60 |
+
stride=128,
|
61 |
+
return_overflowing_tokens=True,
|
62 |
+
return_offsets_mapping=True,
|
63 |
+
padding="max_length"
|
64 |
+
)
|
65 |
+
sample_mapping = tokenized.pop("overflow_to_sample_mapping")
|
66 |
+
offset_mapping = tokenized.pop("offset_mapping")
|
67 |
+
for i, offsets in enumerate(offset_mapping):
|
68 |
+
input_ids = tokenized["input_ids"][i]
|
69 |
+
cls_index = input_ids.index(tokenizer.cls_token_id)
|
70 |
+
sequence_ids = tokenized.sequence_ids(i)
|
71 |
+
start_position = cls_index
|
72 |
+
end_position = cls_index
|
73 |
+
if len(answers) > 0:
|
74 |
+
first_answer = answers[0] # Get the first answer dictionary
|
75 |
+
start_char = first_answer["answer_start"]
|
76 |
+
end_char = start_char + len(first_answer["text"])
|
77 |
+
token_start_index = 0
|
78 |
+
while sequence_ids[token_start_index] != (1 if tokenizer.is_fast else 0):
|
79 |
+
token_start_index += 1
|
80 |
+
token_end_index = len(input_ids) - 1
|
81 |
+
while sequence_ids[token_end_index] != (1 if tokenizer.is_fast else 0):
|
82 |
+
token_end_index -= 1
|
83 |
+
if offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char:
|
84 |
+
# Move the token_start_index and token_end_index to the two ends of the answer
|
85 |
+
while token_start_index < len(offsets) and offsets[token_start_index][0] <= start_char:
|
86 |
+
token_start_index += 1
|
87 |
+
start_position = token_start_index - 1
|
88 |
+
|
89 |
+
while token_end_index >= 0 and offsets[token_end_index][1] >= end_char:
|
90 |
+
token_end_index -= 1
|
91 |
+
end_position = token_end_index + 1
|
92 |
+
|
93 |
+
tokenized_examples["input_ids"].append(input_ids)
|
94 |
+
tokenized_examples["attention_mask"].append(tokenized["attention_mask"][i])
|
95 |
+
tokenized_examples["offset_mapping"].append(offsets)
|
96 |
+
tokenized_examples["overflow_to_sample_mapping"].append(example_index) # Map back to the original example index in the batch
|
97 |
+
tokenized_examples["start_positions"].append(start_position)
|
98 |
+
tokenized_examples["end_positions"].append(end_position)
|
99 |
+
tokenized_examples["example_id"].append(qa.get("id", f"{examples.get('title', ['no_title'])[example_index]}_{len(tokenized_examples['input_ids'])}"))
|
100 |
+
tokenized_dataset = dataset.map(
|
101 |
+
prepare_features,
|
102 |
+
batched=True,
|
103 |
+
remove_columns=dataset["train"].column_names # Remove original columns after processing
|
104 |
+
)
|
105 |
+
print(tokenized_dataset)
|
106 |
+
from transformers import TrainingArguments, Trainer
|
107 |
+
training_args = TrainingArguments(
|
108 |
+
output_dir="./finetuned-roberta-squad2",
|
109 |
+
eval_strategy="epoch", # Corrected argument name
|
110 |
+
save_strategy="epoch", # Match save strategy to evaluation strategy
|
111 |
+
learning_rate=2e-5,
|
112 |
+
num_train_epochs=3,
|
113 |
+
weight_decay=0.01,
|
114 |
+
per_device_train_batch_size=8,
|
115 |
+
per_device_eval_batch_size=8,
|
116 |
+
save_total_limit=1,
|
117 |
+
load_best_model_at_end=True,
|
118 |
+
)
|
119 |
+
trainer = Trainer(
|
120 |
+
model=model,
|
121 |
+
args=training_args,
|
122 |
+
train_dataset=tokenized_dataset["train"],
|
123 |
+
eval_dataset=tokenized_dataset["validation"],
|
124 |
+
tokenizer=tokenizer
|
125 |
+
)
|
126 |
+
trainer.train()
|
127 |
+
trainer.save_model("./finetuned-roberta-squad2")
|
128 |
+
tokenizer.save_pretrained("./finetuned-roberta-squad2")
|
129 |
+
# EVALUATION
|
130 |
+
!pip install bert-score -q
|
131 |
+
from transformers import pipeline
|
132 |
+
qa_pipeline = pipeline("question-answering", model="./finetuned-roberta-squad2", tokenizer=tokenizer)
|
133 |
+
examples = dataset["validation"]
|
134 |
+
predictions = []
|
135 |
+
references = []
|
136 |
+
for example in examples:
|
137 |
+
for para in example["paragraphs"]:
|
138 |
+
context = para["context"]
|
139 |
+
for qa in para["qas"]:
|
140 |
+
question = qa["question"]
|
141 |
+
answers = qa["answers"] # This is a list of answer dictionaries
|
142 |
+
result = qa_pipeline({
|
143 |
+
"context": context,
|
144 |
+
"question": question
|
145 |
+
})
|
146 |
+
predictions.append(result["answer"])
|
147 |
+
if len(answers) > 0:
|
148 |
+
references.append(answers[0]["text"])
|
149 |
+
else:
|
150 |
+
references.append("") # Append empty string for unanswerable questions
|
151 |
+
from bert_score import score
|
152 |
+
P, R, F1 = score(predictions, references, lang="en", model_type="roberta-base")
|
153 |
+
print(f"🔹 BERTScore Precision: {P.mean().item():.4f}")
|
154 |
+
print(f"🔹 BERTScore Recall: {R.mean().item():.4f}")
|
155 |
+
print(f"🔹 BERTScore F1: {F1.mean().item():.4f}")
|
156 |
+
from transformers import AutoModel, AutoTokenizer
|
157 |
+
import torch
|
158 |
+
import torch.nn.functional as F
|
159 |
+
# Use sentence transformer or same QA model encoder
|
160 |
+
embed_model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
161 |
+
embed_tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
162 |
+
def get_embedding(text):
|
163 |
+
inputs = embed_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
164 |
+
with torch.no_grad():
|
165 |
+
outputs = embed_model(**inputs)
|
166 |
+
return outputs.last_hidden_state.mean(dim=1)
|
167 |
+
# Compute cosine similarities
|
168 |
+
cosine_scores = []
|
169 |
+
for pred, ref in zip(predictions, references):
|
170 |
+
pred_emb = get_embedding(pred)
|
171 |
+
ref_emb = get_embedding(ref)
|
172 |
+
cosine_sim = F.cosine_similarity(pred_emb, ref_emb).item()
|
173 |
+
cosine_scores.append(cosine_sim)
|
174 |
+
avg_cosine = sum(cosine_scores) / len(cosine_scores)
|
175 |
+
print(f"🔹 Average Cosine Similarity: {avg_cosine:.4f}")
|