LivisLiquoro commited on
Commit
c163b71
·
verified ·
1 Parent(s): 429abc5

Upload 6 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ EDITH[[:space:]]CHATBOT[[:space:]]DEMO[[:space:]]-[[:space:]]HD[[:space:]]1080p.mov filter=lfs diff=lfs merge=lfs -text
37
+ EDITH[[:space:]]Q&A[[:space:]]ChatBot.pptx filter=lfs diff=lfs merge=lfs -text
EDITH CHATBOT DEMO - HD 1080p.mov ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:194b1a5ee8d5356c715c1db9c6b77951c86fb9d9347d209e45060bc5b3573ec8
3
+ size 61645856
EDITH Q&A ChatBot.pptx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c49fa3255a600626fe7bee8c696352cf6aa13214c629fa6d8ed97b0380c0fad6
3
+ size 62628833
EDITH_BERT_Traning_Evaluation.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
EDITH_ChatBot_UI.ipynb ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "EpuzgeBWEYWR",
7
+ "metadata": {
8
+ "colab": {
9
+ "base_uri": "https://localhost:8080/"
10
+ },
11
+ "executionInfo": {
12
+ "elapsed": 29790,
13
+ "status": "ok",
14
+ "timestamp": 1729514059235,
15
+ "user": {
16
+ "displayName": "Ayush kumar",
17
+ "userId": "09471472999674147959"
18
+ },
19
+ "user_tz": -330
20
+ },
21
+ "id": "EpuzgeBWEYWR",
22
+ "outputId": "3f0077f2-6be0-498e-c8ea-ea605099759a"
23
+ },
24
+ "outputs": [],
25
+ "source": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "execution_count": 2,
30
+ "id": "522d1bb0-d1df-4811-bc4e-1062e1ee4515",
31
+ "metadata": {
32
+ "colab": {
33
+ "base_uri": "https://localhost:8080/",
34
+ "height": 609
35
+ },
36
+ "executionInfo": {
37
+ "elapsed": 29742,
38
+ "status": "ok",
39
+ "timestamp": 1729514088953,
40
+ "user": {
41
+ "displayName": "Ayush kumar",
42
+ "userId": "09471472999674147959"
43
+ },
44
+ "user_tz": -330
45
+ },
46
+ "id": "522d1bb0-d1df-4811-bc4e-1062e1ee4515",
47
+ "outputId": "046cc978-0a86-40fa-a117-56c248b60032"
48
+ },
49
+ "outputs": [
50
+ {
51
+ "name": "stdout",
52
+ "output_type": "stream",
53
+ "text": [
54
+ "* Running on local URL: http://127.0.0.1:7869\n",
55
+ "* Running on public URL: https://c4db01568dfdb26c7a.gradio.live\n",
56
+ "\n",
57
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n"
58
+ ]
59
+ },
60
+ {
61
+ "data": {
62
+ "text/html": [
63
+ "<div><iframe src=\"https://c4db01568dfdb26c7a.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
64
+ ],
65
+ "text/plain": [
66
+ "<IPython.core.display.HTML object>"
67
+ ]
68
+ },
69
+ "metadata": {},
70
+ "output_type": "display_data"
71
+ }
72
+ ],
73
+ "source": [
74
+ "!pip install -q gradio\n",
75
+ "import warnings\n",
76
+ "warnings.filterwarnings('ignore')\n",
77
+ "\n",
78
+ "# Import necessary libraries\n",
79
+ "import gradio as gr\n",
80
+ "import torch\n",
81
+ "from transformers import (\n",
82
+ " BertTokenizerFast,\n",
83
+ " BertForQuestionAnswering,\n",
84
+ " AutoTokenizer,\n",
85
+ " BartForQuestionAnswering,\n",
86
+ " DistilBertTokenizerFast,\n",
87
+ " DistilBertForQuestionAnswering\n",
88
+ ")\n",
89
+ "import gc\n",
90
+ "\n",
91
+ "# Create a context store\n",
92
+ "context_store = []\n",
93
+ "selected_model = None # To track the selected model\n",
94
+ "\n",
95
+ "# Define models and tokenizers\n",
96
+ "def load_bert_model_and_tokenizer():\n",
97
+ " device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
98
+ " model_save_path = \"LivisLiquoro/BERT_Model_Squad1.1\"\n",
99
+ " model = BertForQuestionAnswering.from_pretrained(model_save_path)\n",
100
+ " tokenizer = BertTokenizerFast.from_pretrained(model_save_path)\n",
101
+ " model.eval().to(device)\n",
102
+ " gc.collect()\n",
103
+ " torch.cuda.empty_cache()\n",
104
+ " return tokenizer, model, device\n",
105
+ "\n",
106
+ "def load_bart_model_and_tokenizer():\n",
107
+ " device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
108
+ " model = BartForQuestionAnswering.from_pretrained(\"valhalla/bart-large-finetuned-squadv1\")\n",
109
+ " tokenizer = AutoTokenizer.from_pretrained(\"valhalla/bart-large-finetuned-squadv1\")\n",
110
+ " model.eval().to(device)\n",
111
+ " gc.collect()\n",
112
+ " torch.cuda.empty_cache()\n",
113
+ " return tokenizer, model, device\n",
114
+ "\n",
115
+ "def load_distilbert_model_and_tokenizer():\n",
116
+ " device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
117
+ " model_save_path = \"LivisLiquoro/DistilBert_model_squad1.1\"\n",
118
+ " model = DistilBertForQuestionAnswering.from_pretrained(model_save_path)\n",
119
+ " tokenizer = DistilBertTokenizerFast.from_pretrained(model_save_path)\n",
120
+ " model.eval().to(device)\n",
121
+ " gc.collect()\n",
122
+ " torch.cuda.empty_cache()\n",
123
+ " return tokenizer, model, device\n",
124
+ "\n",
125
+ "def clean_answer(tokens):\n",
126
+ " \"\"\"\n",
127
+ " Clean the tokens by removing special tokens like [SEP], [CLS], and fixing token fragments.\n",
128
+ " \"\"\"\n",
129
+ " cleaned_tokens = []\n",
130
+ " for token in tokens:\n",
131
+ " if token in ['[SEP]', '[CLS]']:\n",
132
+ " continue # Skip special tokens\n",
133
+ " token = token.replace('##', '') # Remove '##' prefix\n",
134
+ " if token: # Only add non-empty tokens\n",
135
+ " cleaned_tokens.append(token)\n",
136
+ "\n",
137
+ " return tokenizer.convert_tokens_to_string(cleaned_tokens).strip() or None\n",
138
+ "\n",
139
+ "def generate_answer(context, question):\n",
140
+ " max_attempts = 50 # Set maximum attempts for generating answers\n",
141
+ " attempts = 0\n",
142
+ " best_answer = None\n",
143
+ " \n",
144
+ " # Adjusting the context chunking method\n",
145
+ " max_length = 512\n",
146
+ " chunks = [context[i:i + max_length] for i in range(0, len(context), max_length)]\n",
147
+ "\n",
148
+ " while attempts < max_attempts:\n",
149
+ " attempts += 1\n",
150
+ " for chunk in chunks:\n",
151
+ " inputs = tokenizer(chunk, question, return_tensors='pt', truncation=True, max_length=max_length).to(device)\n",
152
+ "\n",
153
+ " with torch.no_grad():\n",
154
+ " outputs = model(**inputs)\n",
155
+ " answer_start = torch.argmax(outputs.start_logits)\n",
156
+ " answer_end = torch.argmax(outputs.end_logits) + 1\n",
157
+ "\n",
158
+ " if answer_start < answer_end:\n",
159
+ " answer = clean_answer(tokenizer.convert_ids_to_tokens(inputs['input_ids'][0][answer_start:answer_end]))\n",
160
+ "\n",
161
+ " # Validate answer and ensure it's direct\n",
162
+ " if answer and answer.lower() != \"no valid answer found\":\n",
163
+ " best_answer = answer.capitalize()\n",
164
+ " break # Exit the chunk loop if a valid answer is found\n",
165
+ " if best_answer: # If an answer is found, no need to keep trying\n",
166
+ " break\n",
167
+ " \n",
168
+ " if best_answer: # If a valid answer was found, exit the attempts loop\n",
169
+ " break\n",
170
+ " \n",
171
+ " if best_answer:\n",
172
+ " return best_answer\n",
173
+ " else:\n",
174
+ " return \"❌ No valid answer found.\"\n",
175
+ "\n",
176
+ "# Define the Gradio interface with light theme and organized layout\n",
177
+ "def chatbot_interface():\n",
178
+ " with gr.Blocks() as demo:\n",
179
+ " # Custom CSS for light theme and layout\n",
180
+ " gr.Markdown(\"\"\"\n",
181
+ " <style>\n",
182
+ " body { background-color: #f9f9f9; }\n",
183
+ " .chatbot-container { background-color: #ffffff; border-radius: 10px; padding: 20px; color: #333; font-family: Arial, sans-serif; }\n",
184
+ " .gr-button { background-color: #4CAF50; color: white; border: none; border-radius: 5px; padding: 10px 20px; font-size: 14px; cursor: pointer; }\n",
185
+ " .gr-button:hover { background-color: #45a049; }\n",
186
+ " .gr-textbox { background-color: #ffffff; color: #333; border-radius: 5px; border: 1px solid #ddd; padding: 10px; }\n",
187
+ " .gr-chatbot { background-color: #e6e6e6; border-radius: 10px; padding: 15px; color: #333; }\n",
188
+ " .footer { text-align: right; font-size: 12px; color: #777; font-style: italic; }\n",
189
+ " .note { text-align: right; font-size: 10px; color: #777; font-style: italic; position: absolute; bottom: 10px; right: 10px; }\n",
190
+ " </style>\n",
191
+ " \"\"\")\n",
192
+ "\n",
193
+ " # Header\n",
194
+ " gr.Markdown(\"<h1 style='text-align: center; color: #4CAF50;'>EDITH: Multi-Model Question Answering Platform</h1>\")\n",
195
+ " gr.Markdown(\"<p style='text-align: center; color: #777;'>Switch between BERT, BART, and DistilBERT models and ask questions based on the context.</p>\")\n",
196
+ "\n",
197
+ " context_state = gr.State()\n",
198
+ " model_choice_state = gr.State(value=\"BERT\") # Default model is BERT\n",
199
+ "\n",
200
+ " with gr.Row():\n",
201
+ " with gr.Column(scale=11): # Left panel for chatbot and question input (45%)\n",
202
+ " chatbot = gr.Chatbot(label=\"Chatbot\")\n",
203
+ " question_input = gr.Textbox(label=\"Ask a Question\", placeholder=\"Enter your question here...\", lines=1)\n",
204
+ " submit_btn = gr.Button(\"Submit Question\")\n",
205
+ "\n",
206
+ " with gr.Column(scale=9): # Right panel for setting context and instructions (55%)\n",
207
+ " context_input = gr.Textbox(label=\"Set Context\", placeholder=\"Enter the context here...\", lines=4)\n",
208
+ " set_context_btn = gr.Button(\"Set Context\")\n",
209
+ " clear_context_btn = gr.Button(\"Clear Context\")\n",
210
+ "\n",
211
+ " # Model selection buttons\n",
212
+ " model_selection = gr.Radio(choices=[\"BERT\", \"BART\", \"DistilBERT\"], label=\"Select Model\", value=\"BERT\")\n",
213
+ " status_message = gr.Markdown(\"\")\n",
214
+ "\n",
215
+ " gr.Markdown(\"<strong>Instructions:</strong><br>1. Set a context.<br>2. Select the model (BERT, BART, or DistilBERT).<br>3. Ask questions based on the context.<br><br><strong>Note:</strong> <span class='note'>The BART model is pre-trained from Hugging Face. Credits to Hugging Face and the person who fine-tuned this model ('valhalla/bart-large-finetuned-squadv1')</span>\")\n",
216
+ "\n",
217
+ " footer = gr.Markdown(\"<div class='footer'>Prepared by: Team EDITH</div>\")\n",
218
+ "\n",
219
+ " def set_context(context):\n",
220
+ " if not context.strip():\n",
221
+ " return gr.update(), \"Please enter a valid context.\", None\n",
222
+ " return gr.update(visible=False), \"Context has been set. You can now ask questions.\", context\n",
223
+ "\n",
224
+ " def clear_context():\n",
225
+ " return gr.update(visible=True), \"Context has been cleared. Please set a new context.\", None\n",
226
+ "\n",
227
+ " def handle_question(question, history, context, model_choice):\n",
228
+ " global tokenizer, model, device\n",
229
+ "\n",
230
+ " if not context:\n",
231
+ " return history, \"Please set the context before asking questions.\"\n",
232
+ " if not question.strip():\n",
233
+ " return history, \"Please enter a valid question.\"\n",
234
+ "\n",
235
+ " # Load the selected model and tokenizer\n",
236
+ " if model_choice == \"BERT\":\n",
237
+ " tokenizer, model, device = load_bert_model_and_tokenizer()\n",
238
+ " model_name = \"BERT\"\n",
239
+ " elif model_choice == \"BART\":\n",
240
+ " tokenizer, model, device = load_bart_model_and_tokenizer()\n",
241
+ " model_name = \"BART\"\n",
242
+ " elif model_choice == \"DistilBERT\":\n",
243
+ " tokenizer, model, device = load_distilbert_model_and_tokenizer()\n",
244
+ " model_name = \"DistilBERT\"\n",
245
+ "\n",
246
+ " answer = generate_answer(context, question)\n",
247
+ " history = history + [[f\"👤: {question}\", f\"🤖 ({model_name}): {answer}\"]] # Show the selected model with the answer\n",
248
+ " return history, \"\"\n",
249
+ "\n",
250
+ " set_context_btn.click(set_context, inputs=context_input, outputs=[context_input, status_message, context_state])\n",
251
+ " clear_context_btn.click(clear_context, inputs=None, outputs=[context_input, status_message, context_state])\n",
252
+ " submit_btn.click(handle_question, inputs=[question_input, chatbot, context_state, model_selection], outputs=[chatbot, question_input])\n",
253
+ "\n",
254
+ " # Enable \"Enter\" key to trigger the \"Submit\" button\n",
255
+ " question_input.submit(handle_question, inputs=[question_input, chatbot, context_state, model_selection], outputs=[chatbot, question_input])\n",
256
+ "\n",
257
+ " return demo\n",
258
+ "\n",
259
+ "# Run the Gradio interface\n",
260
+ "interface = chatbot_interface()\n",
261
+ "interface.launch(share=True)\n"
262
+ ]
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "execution_count": null,
267
+ "id": "ed897183",
268
+ "metadata": {
269
+ "id": "ed897183"
270
+ },
271
+ "outputs": [],
272
+ "source": [
273
+ "|"
274
+ ]
275
+ }
276
+ ],
277
+ "metadata": {
278
+ "colab": {
279
+ "provenance": []
280
+ },
281
+ "kernelspec": {
282
+ "display_name": "Python 3 (ipykernel)",
283
+ "language": "python",
284
+ "name": "python3"
285
+ },
286
+ "language_info": {
287
+ "codemirror_mode": {
288
+ "name": "ipython",
289
+ "version": 3
290
+ },
291
+ "file_extension": ".py",
292
+ "mimetype": "text/x-python",
293
+ "name": "python",
294
+ "nbconvert_exporter": "python",
295
+ "pygments_lexer": "ipython3",
296
+ "version": "3.11.4"
297
+ }
298
+ },
299
+ "nbformat": 4,
300
+ "nbformat_minor": 5
301
+ }
EDITH_DistilBERT_Traing_Evaluation.ipynb ADDED
@@ -0,0 +1,1047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "### DistilBERT Model Exploration\n",
8
+ "\n",
9
+ "In this section, we shift our focus to exploring the DistilBERT model, a lighter and faster version of the original BERT architecture. While DistilBERT aims to retain much of the knowledge and capabilities of BERT, it does so with fewer parameters and reduced computational requirements. This exploration is particularly relevant in scenarios where speed and efficiency are critical, such as real-time applications or resource-constrained environments.\n",
10
+ "\n",
11
+ "**Model Implementation and Purpose**\n",
12
+ "\n",
13
+ "Our implementation involves fine-tuning DistilBERT on the same dataset we used for the BERT model, aiming to evaluate its performance in the context of question answering. The goal is to see how well DistilBERT can understand and generate answers based on the provided context, even though it's widely recognized that it may not match BERT's performance in many cases.\n",
14
+ "\n",
15
+ "**Key Features of the Code**\n",
16
+ "\n",
17
+ "1. **Data Preparation**: Just like with BERT, we preprocess our data to ensure it's in the right format for DistilBERT. This includes tokenizing the questions and contexts, as well as padding them to ensure uniform input lengths.\n",
18
+ "\n",
19
+ "2. **Model Training**: We set up the training loop, where DistilBERT is fine-tuned on our dataset. The training process involves adjusting the model's weights based on how well it predicts the answers, optimizing its understanding of the context.\n",
20
+ "\n",
21
+ "3. **Evaluation & Testing**: Post-training, we evaluate the model using metrics such as ROUGE, BLEU, and F1 scores. These metrics provide insight into how accurately DistilBERT generates answers compared to the reference answers.\n",
22
+ "\n",
23
+ "4. **Performance Analysis**: After evaluation, we will compare the performance of DistilBERT with that of the BERT model. This analysis will help us understand the trade-offs involved in using a distilled version of BERT, particularly in terms of response accuracy and computational efficiency.\n",
24
+ "\n",
25
+ "**Conclusion and Future Directions**\n",
26
+ "\n",
27
+ "It's important to note that we haven't invested extensive time in optimizing DistilBERT for our use case, given the general consensus that it often yields inferior performance compared to BERT. However, this exploration is valuable for understanding the potential benefits of using lighter models in appropriate contexts. Future work may involve further tuning and experimenting with different configurations to maximize DistilBERT's effectiveness, particularly in situations where computational resources are limited. By examining DistilBERT alongside BERT, we gain insights into the versatility and adaptability of transformer-based models for context-based question answering applications.\n"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": 16,
33
+ "metadata": {
34
+ "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
35
+ "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
36
+ "execution": {
37
+ "iopub.execute_input": "2024-10-20T15:42:01.494045Z",
38
+ "iopub.status.busy": "2024-10-20T15:42:01.493704Z",
39
+ "iopub.status.idle": "2024-10-20T15:42:02.681840Z",
40
+ "shell.execute_reply": "2024-10-20T15:42:02.680746Z",
41
+ "shell.execute_reply.started": "2024-10-20T15:42:01.494004Z"
42
+ }
43
+ },
44
+ "outputs": [],
45
+ "source": [
46
+ "import pandas as pd\n",
47
+ "import numpy as np\n",
48
+ "import seaborn as sns\n",
49
+ "import matplotlib.pyplot as plt\n",
50
+ "# Import Gaussian filter for smoothing\n",
51
+ "from scipy.ndimage import gaussian_filter1d\n",
52
+ "import json\n",
53
+ "import torch\n",
54
+ "from transformers import DistilBertTokenizerFast, DistilBertForQuestionAnswering, AdamW\n",
55
+ "from torch.utils.data import DataLoader, Dataset, random_split, default_collate\n",
56
+ "from torch.cuda.amp import autocast, GradScaler\n",
57
+ "import warnings\n",
58
+ "warnings.filterwarnings('ignore')"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": 17,
64
+ "metadata": {
65
+ "execution": {
66
+ "iopub.execute_input": "2024-10-20T15:42:22.376215Z",
67
+ "iopub.status.busy": "2024-10-20T15:42:22.375839Z",
68
+ "iopub.status.idle": "2024-10-20T15:42:33.763837Z",
69
+ "shell.execute_reply": "2024-10-20T15:42:33.762508Z",
70
+ "shell.execute_reply.started": "2024-10-20T15:42:22.376183Z"
71
+ }
72
+ },
73
+ "outputs": [],
74
+ "source": [
75
+ "!pip install -q transformers"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": 23,
81
+ "metadata": {},
82
+ "outputs": [],
83
+ "source": [
84
+ "dataset_path = 'train-v1.1.json'"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "execution_count": 24,
90
+ "metadata": {
91
+ "execution": {
92
+ "iopub.execute_input": "2024-10-20T15:42:33.766611Z",
93
+ "iopub.status.busy": "2024-10-20T15:42:33.765615Z",
94
+ "iopub.status.idle": "2024-10-20T15:42:33.923066Z",
95
+ "shell.execute_reply": "2024-10-20T15:42:33.922123Z",
96
+ "shell.execute_reply.started": "2024-10-20T15:42:33.766562Z"
97
+ }
98
+ },
99
+ "outputs": [],
100
+ "source": [
101
+ "# Step 1: Initialize the tokenizer\n",
102
+ "tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased')\n",
103
+ "\n",
104
+ "# Custom dataset class for question-answering\n",
105
+ "class QADataset(Dataset):\n",
106
+ " def __init__(self, examples):\n",
107
+ " self.examples = examples\n",
108
+ " \n",
109
+ " def __len__(self):\n",
110
+ " return len(self.examples)\n",
111
+ " \n",
112
+ " def __getitem__(self, idx):\n",
113
+ " return self.examples[idx]"
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "execution_count": 25,
119
+ "metadata": {
120
+ "execution": {
121
+ "iopub.execute_input": "2024-10-20T15:42:33.925160Z",
122
+ "iopub.status.busy": "2024-10-20T15:42:33.924484Z",
123
+ "iopub.status.idle": "2024-10-20T15:42:33.934652Z",
124
+ "shell.execute_reply": "2024-10-20T15:42:33.933588Z",
125
+ "shell.execute_reply.started": "2024-10-20T15:42:33.925113Z"
126
+ }
127
+ },
128
+ "outputs": [],
129
+ "source": [
130
+ "# Step 2: Preprocessing function for the dataset\n",
131
+ "def prepare_features(example):\n",
132
+ " inputs = tokenizer(\n",
133
+ " example['question'],\n",
134
+ " example['context'],\n",
135
+ " max_length=256, # Reduced sequence length for faster processing\n",
136
+ " truncation=True,\n",
137
+ " padding=\"max_length\",\n",
138
+ " return_tensors=\"pt\",\n",
139
+ " return_offsets_mapping=True\n",
140
+ " )\n",
141
+ "\n",
142
+ " if 'answers' not in example or len(example['answers']['answer_start']) == 0:\n",
143
+ " return None\n",
144
+ "\n",
145
+ " start_char = example['answers']['answer_start'][0]\n",
146
+ " end_char = start_char + len(example['answers']['text'][0])\n",
147
+ " offset_mapping = inputs['offset_mapping'][0]\n",
148
+ "\n",
149
+ " try:\n",
150
+ " start_pos = next(idx for idx, (start, end) in enumerate(offset_mapping) if start <= start_char < end)\n",
151
+ " end_pos = next(idx for idx, (start, end) in enumerate(offset_mapping) if start < end_char <= end)\n",
152
+ " except StopIteration:\n",
153
+ " return None\n",
154
+ "\n",
155
+ " inputs['start_positions'] = torch.tensor([start_pos])\n",
156
+ " inputs['end_positions'] = torch.tensor([end_pos])\n",
157
+ " inputs.pop('offset_mapping')\n",
158
+ "\n",
159
+ " return {\n",
160
+ " 'input_ids': inputs['input_ids'].squeeze(),\n",
161
+ " 'attention_mask': inputs['attention_mask'].squeeze(),\n",
162
+ " 'start_positions': inputs['start_positions'].squeeze(),\n",
163
+ " 'end_positions': inputs['end_positions'].squeeze(),\n",
164
+ " }"
165
+ ]
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "execution_count": 26,
170
+ "metadata": {
171
+ "execution": {
172
+ "iopub.execute_input": "2024-10-20T15:42:33.936157Z",
173
+ "iopub.status.busy": "2024-10-20T15:42:33.935788Z",
174
+ "iopub.status.idle": "2024-10-20T15:42:33.947810Z",
175
+ "shell.execute_reply": "2024-10-20T15:42:33.946881Z",
176
+ "shell.execute_reply.started": "2024-10-20T15:42:33.936123Z"
177
+ }
178
+ },
179
+ "outputs": [],
180
+ "source": [
181
+ "# Step 3: Load and preprocess the dataset\n",
182
+ "def load_dataset(dataset_path):\n",
183
+ " with open(dataset_path, 'r') as f:\n",
184
+ " dataset = json.load(f)\n",
185
+ " examples = []\n",
186
+ " for article in dataset['data']:\n",
187
+ " for paragraph in article['paragraphs']:\n",
188
+ " context = paragraph['context']\n",
189
+ " for qa in paragraph['qas']:\n",
190
+ " question = qa['question']\n",
191
+ " answers = {\n",
192
+ " 'answer_start': [ans['answer_start'] for ans in qa['answers']],\n",
193
+ " 'text': [ans['text'] for ans in qa['answers']]\n",
194
+ " }\n",
195
+ " examples.append({\n",
196
+ " 'context': context,\n",
197
+ " 'question': question,\n",
198
+ " 'answers': answers\n",
199
+ " })\n",
200
+ " return examples\n"
201
+ ]
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "execution_count": 27,
206
+ "metadata": {
207
+ "execution": {
208
+ "iopub.execute_input": "2024-10-20T15:42:34.052073Z",
209
+ "iopub.status.busy": "2024-10-20T15:42:34.051810Z",
210
+ "iopub.status.idle": "2024-10-20T15:55:50.144298Z",
211
+ "shell.execute_reply": "2024-10-20T15:55:50.143437Z",
212
+ "shell.execute_reply.started": "2024-10-20T15:42:34.052042Z"
213
+ }
214
+ },
215
+ "outputs": [],
216
+ "source": [
217
+ "# Step 4: Preprocess the dataset examples for training\n",
218
+ " \n",
219
+ "dataset_examples = load_dataset(dataset_path)\n",
220
+ "encoded_dataset = [prepare_features(example) for example in dataset_examples if prepare_features(example) is not None]\n"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "execution_count": 32,
226
+ "metadata": {},
227
+ "outputs": [
228
+ {
229
+ "data": {
230
+ "text/plain": [
231
+ "{'input_ids': tensor([ 101, 2000, 3183, 2106, 1996, 6261, 2984, 9382, 3711, 1999,\n",
232
+ " 8517, 1999, 10223, 26371, 2605, 1029, 102, 6549, 2135, 1010,\n",
233
+ " 1996, 2082, 2038, 1037, 3234, 2839, 1012, 10234, 1996, 2364,\n",
234
+ " 2311, 1005, 1055, 2751, 8514, 2003, 1037, 3585, 6231, 1997,\n",
235
+ " 1996, 6261, 2984, 1012, 3202, 1999, 2392, 1997, 1996, 2364,\n",
236
+ " 2311, 1998, 5307, 2009, 1010, 2003, 1037, 6967, 6231, 1997,\n",
237
+ " 4828, 2007, 2608, 2039, 14995, 6924, 2007, 1996, 5722, 1000,\n",
238
+ " 2310, 3490, 2618, 4748, 2033, 18168, 5267, 1000, 1012, 2279,\n",
239
+ " 2000, 1996, 2364, 2311, 2003, 1996, 13546, 1997, 1996, 6730,\n",
240
+ " 2540, 1012, 3202, 2369, 1996, 13546, 2003, 1996, 24665, 23052,\n",
241
+ " 1010, 1037, 14042, 2173, 1997, 7083, 1998, 9185, 1012, 2009,\n",
242
+ " 2003, 1037, 15059, 1997, 1996, 24665, 23052, 2012, 10223, 26371,\n",
243
+ " 1010, 2605, 2073, 1996, 6261, 2984, 22353, 2135, 2596, 2000,\n",
244
+ " 3002, 16595, 9648, 4674, 2061, 12083, 9711, 2271, 1999, 8517,\n",
245
+ " 1012, 2012, 1996, 2203, 1997, 1996, 2364, 3298, 1006, 1998,\n",
246
+ " 1999, 1037, 3622, 2240, 2008, 8539, 2083, 1017, 11342, 1998,\n",
247
+ " 1996, 2751, 8514, 1007, 1010, 2003, 1037, 3722, 1010, 2715,\n",
248
+ " 2962, 6231, 1997, 2984, 1012, 102, 0, 0, 0, 0,\n",
249
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
250
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
251
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
252
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
253
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
254
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
255
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
256
+ " 0, 0, 0, 0, 0, 0]),\n",
257
+ " 'attention_mask': tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
258
+ " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
259
+ " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
260
+ " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
261
+ " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
262
+ " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
263
+ " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
264
+ " 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
265
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
266
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
267
+ " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),\n",
268
+ " 'start_positions': tensor(130),\n",
269
+ " 'end_positions': tensor(137)}"
270
+ ]
271
+ },
272
+ "execution_count": 32,
273
+ "metadata": {},
274
+ "output_type": "execute_result"
275
+ }
276
+ ],
277
+ "source": [
278
+ "encoded_dataset[0]"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": 28,
284
+ "metadata": {
285
+ "execution": {
286
+ "iopub.execute_input": "2024-10-20T15:57:26.018871Z",
287
+ "iopub.status.busy": "2024-10-20T15:57:26.018005Z",
288
+ "iopub.status.idle": "2024-10-20T15:57:26.022910Z",
289
+ "shell.execute_reply": "2024-10-20T15:57:26.021938Z",
290
+ "shell.execute_reply.started": "2024-10-20T15:57:26.018829Z"
291
+ }
292
+ },
293
+ "outputs": [],
294
+ "source": [
295
+ "# Step 5: Create PyTorch dataset\n",
296
+ "qa_dataset = QADataset(encoded_dataset)\n"
297
+ ]
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "execution_count": 29,
302
+ "metadata": {
303
+ "execution": {
304
+ "iopub.execute_input": "2024-10-20T15:57:31.125889Z",
305
+ "iopub.status.busy": "2024-10-20T15:57:31.125528Z",
306
+ "iopub.status.idle": "2024-10-20T15:57:31.154920Z",
307
+ "shell.execute_reply": "2024-10-20T15:57:31.154116Z",
308
+ "shell.execute_reply.started": "2024-10-20T15:57:31.125856Z"
309
+ }
310
+ },
311
+ "outputs": [],
312
+ "source": [
313
+ "# Step 6: Split into training and validation sets\n",
314
+ "train_size = int(0.9 * len(qa_dataset))\n",
315
+ "val_size = len(qa_dataset) - train_size\n",
316
+ "train_dataset, val_dataset = random_split(qa_dataset, [train_size, val_size])\n",
317
+ "\n",
318
+ "def custom_collate_fn(batch):\n",
319
+ " return default_collate([item for item in batch if item is not None])\n",
320
+ "\n",
321
+ "train_dataloader = DataLoader(train_dataset, batch_size=16, shuffle=True, collate_fn=custom_collate_fn)\n",
322
+ "val_dataloader = DataLoader(val_dataset, batch_size=8, collate_fn=custom_collate_fn)\n"
323
+ ]
324
+ },
325
+ {
326
+ "cell_type": "markdown",
327
+ "metadata": {},
328
+ "source": [
329
+ "### Explanation of DistilBERT Question-Answering Pipeline\n",
330
+ "\n",
331
+ "In this section, we outline the steps involved in preparing our dataset for fine-tuning the DistilBERT model on a question-answering task. This process is crucial for ensuring that the model receives the properly formatted input necessary for effective learning.\n",
332
+ "\n",
333
+ "1. **Dataset Path Initialization**:\n",
334
+ " We start by defining the path to the SQuAD1.1 dataset, which is a widely used dataset for training question-answering models. This JSON file contains questions, contexts, and corresponding answers that our model will learn from.\n",
335
+ "\n",
336
+ "2. **Tokenizer Initialization**:\n",
337
+ " We initialize the tokenizer for the DistilBERT model. This tokenizer converts text into a format that the model can understand, including input IDs and attention masks. By loading a pre-trained tokenizer, we ensure consistency with the DistilBERT vocabulary.\n",
338
+ "\n",
339
+ "3. **Custom Dataset Class**:\n",
340
+ " A custom dataset class is defined to handle our examples. This class allows us to easily manage the dataset, including determining its length and accessing individual examples based on their index.\n",
341
+ "\n",
342
+ "4. **Preprocessing Function**:\n",
343
+ " The preprocessing function is responsible for tokenizing each example (question and context) and generating the necessary input format for the model. It sets a maximum sequence length, handles padding and truncation, and calculates the start and end positions of answers within the context. This step is critical for training the model to locate answers in the text.\n",
344
+ "\n",
345
+ "5. **Loading and Preprocessing the Dataset**:\n",
346
+ " We load the dataset by reading the JSON file and extracting relevant data into a structured format. Each entry consists of a context, a question, and associated answers. This organization is essential for further processing.\n",
347
+ "\n",
348
+ "6. **Encoding the Dataset Examples**:\n",
349
+ " After loading the dataset examples, we encode each example using the preprocessing function, filtering out any that cannot be processed. This ensures that we retain only valid inputs for training.\n",
350
+ "\n",
351
+ "7. **Creating the PyTorch Dataset**:\n",
352
+ " We create an instance of our custom dataset class, passing in the encoded examples. This structure facilitates working with the dataset in PyTorch, allowing for straightforward data manipulation during training.\n",
353
+ "\n",
354
+ "8. **Splitting the Dataset**:\n",
355
+ " The dataset is split into training and validation sets, typically allocating 90% for training and 10% for validation. This division is crucial for evaluating the model's performance on unseen data during the training process.\n",
356
+ "\n",
357
+ "9. **Custom Collate Function**:\n",
358
+ " We define a custom collate function to handle batches of data, ensuring that only valid items are included in each batch. This prevents potential issues during the training phase.\n",
359
+ "\n",
360
+ "10. **Creating DataLoaders**:\n",
361
+ " Finally, we create `DataLoader` instances for both the training and validation datasets. These loaders facilitate batch processing, allowing us to efficiently feed data into the model in specified batch sizes.\n",
362
+ "\n",
363
+ "### Summary\n",
364
+ "\n",
365
+ "This code establishes a comprehensive pipeline for preparing data for fine-tuning the DistilBERT model on a question-answering task. By carefully preprocessing the dataset and structuring it for PyTorch, we set the stage for effective model training and evaluation. As we proceed with the training, we will be able to assess the performance of DistilBERT in understanding context and generating answers based on the provided questions and contexts.\n"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "markdown",
370
+ "metadata": {},
371
+ "source": [
372
+ "### Model Training\n",
373
+ "\n",
374
+ "\n",
375
+ "In this section, we implement the training and evaluation process for a DistilBERT model tailored for question answering tasks.\n",
376
+ "\n",
377
+ "1. **Model Initialization**: We load a pre-trained DistilBERT model, which provides a robust foundation for understanding language, and set up an optimizer to adjust the model's parameters during training.\n",
378
+ "\n",
379
+ "2. **Device Setup**: We determine whether to use a GPU or CPU for training to maximize efficiency, enabling faster computations.\n",
380
+ "\n",
381
+ "3. **Mixed Precision Training**: By employing mixed precision, we enhance training speed and reduce memory usage, allowing us to work with larger models or batch sizes.\n",
382
+ "\n",
383
+ "4. **Training and Validation Functions**: We define functions for training and validating the model. The training function computes the loss and updates the model's weights, while the validation function evaluates model performance on a separate dataset to monitor its accuracy.\n",
384
+ "\n",
385
+ "5. **Training Loop**: A loop executes the training and validation processes for a specified number of epochs, tracking and printing performance metrics to observe improvements over time.\n",
386
+ "\n",
387
+ "6. **Model Saving**: After training, we save the trained model and tokenizer to a designated directory for future use.\n",
388
+ "\n",
389
+ "This structured approach facilitates efficient training and evaluation of the DistilBERT model, ensuring it is well-prepared for real-world question-answering applications.\n"
390
+ ]
391
+ },
392
+ {
393
+ "cell_type": "code",
394
+ "execution_count": 16,
395
+ "metadata": {
396
+ "execution": {
397
+ "iopub.execute_input": "2024-10-20T15:57:36.950445Z",
398
+ "iopub.status.busy": "2024-10-20T15:57:36.950023Z",
399
+ "iopub.status.idle": "2024-10-20T15:57:39.550098Z",
400
+ "shell.execute_reply": "2024-10-20T15:57:39.549285Z",
401
+ "shell.execute_reply.started": "2024-10-20T15:57:36.950405Z"
402
+ }
403
+ },
404
+ "outputs": [
405
+ {
406
+ "data": {
407
+ "application/vnd.jupyter.widget-view+json": {
408
+ "model_id": "df9ea53ab3344dea8253eac2d673ff4a",
409
+ "version_major": 2,
410
+ "version_minor": 0
411
+ },
412
+ "text/plain": [
413
+ "model.safetensors: 0%| | 0.00/268M [00:00<?, ?B/s]"
414
+ ]
415
+ },
416
+ "metadata": {},
417
+ "output_type": "display_data"
418
+ },
419
+ {
420
+ "name": "stderr",
421
+ "output_type": "stream",
422
+ "text": [
423
+ "Some weights of DistilBertForQuestionAnswering were not initialized from the model checkpoint at distilbert-base-uncased and are newly initialized: ['qa_outputs.bias', 'qa_outputs.weight']\n",
424
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
425
+ "/opt/conda/lib/python3.10/site-packages/transformers/optimization.py:591: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning\n",
426
+ " warnings.warn(\n"
427
+ ]
428
+ }
429
+ ],
430
+ "source": [
431
+ "# Step 7: Initialize the model for Question Answering\n",
432
+ "model = DistilBertForQuestionAnswering.from_pretrained('distilbert-base-uncased')\n",
433
+ "optimizer = AdamW(model.parameters(), lr=3e-5)\n"
434
+ ]
435
+ },
436
+ {
437
+ "cell_type": "code",
438
+ "execution_count": 7,
439
+ "metadata": {},
440
+ "outputs": [
441
+ {
442
+ "data": {
443
+ "text/plain": [
444
+ "DistilBertForQuestionAnswering(\n",
445
+ " (distilbert): DistilBertModel(\n",
446
+ " (embeddings): Embeddings(\n",
447
+ " (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
448
+ " (position_embeddings): Embedding(512, 768)\n",
449
+ " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
450
+ " (dropout): Dropout(p=0.1, inplace=False)\n",
451
+ " )\n",
452
+ " (transformer): Transformer(\n",
453
+ " (layer): ModuleList(\n",
454
+ " (0-5): 6 x TransformerBlock(\n",
455
+ " (attention): MultiHeadSelfAttention(\n",
456
+ " (dropout): Dropout(p=0.1, inplace=False)\n",
457
+ " (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
458
+ " (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
459
+ " (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
460
+ " (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
461
+ " )\n",
462
+ " (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
463
+ " (ffn): FFN(\n",
464
+ " (dropout): Dropout(p=0.1, inplace=False)\n",
465
+ " (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
466
+ " (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
467
+ " (activation): GELUActivation()\n",
468
+ " )\n",
469
+ " (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
470
+ " )\n",
471
+ " )\n",
472
+ " )\n",
473
+ " )\n",
474
+ " (qa_outputs): Linear(in_features=768, out_features=2, bias=True)\n",
475
+ " (dropout): Dropout(p=0.1, inplace=False)\n",
476
+ ")"
477
+ ]
478
+ },
479
+ "execution_count": 7,
480
+ "metadata": {},
481
+ "output_type": "execute_result"
482
+ }
483
+ ],
484
+ "source": [
485
+ "# Step 8: Set up the device for training\n",
486
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
487
+ "model.to(device)"
488
+ ]
489
+ },
490
+ {
491
+ "cell_type": "code",
492
+ "execution_count": 29,
493
+ "metadata": {
494
+ "execution": {
495
+ "iopub.execute_input": "2024-10-20T16:09:07.905385Z",
496
+ "iopub.status.busy": "2024-10-20T16:09:07.904589Z",
497
+ "iopub.status.idle": "2024-10-20T16:09:07.985212Z",
498
+ "shell.execute_reply": "2024-10-20T16:09:07.984286Z",
499
+ "shell.execute_reply.started": "2024-10-20T16:09:07.905341Z"
500
+ }
501
+ },
502
+ "outputs": [
503
+ {
504
+ "name": "stderr",
505
+ "output_type": "stream",
506
+ "text": [
507
+ "/tmp/ipykernel_30/590130087.py:6: FutureWarning: `torch.cuda.amp.GradScaler(args...)` is deprecated. Please use `torch.amp.GradScaler('cuda', args...)` instead.\n",
508
+ " scaler = GradScaler()\n"
509
+ ]
510
+ }
511
+ ],
512
+ "source": [
513
+ "\n",
514
+ "\n",
515
+ "# Mixed precision scaler\n",
516
+ "scaler = GradScaler()\n"
517
+ ]
518
+ },
519
+ {
520
+ "cell_type": "code",
521
+ "execution_count": 18,
522
+ "metadata": {
523
+ "execution": {
524
+ "iopub.execute_input": "2024-10-20T15:57:48.870796Z",
525
+ "iopub.status.busy": "2024-10-20T15:57:48.869932Z",
526
+ "iopub.status.idle": "2024-10-20T15:57:48.884453Z",
527
+ "shell.execute_reply": "2024-10-20T15:57:48.881684Z",
528
+ "shell.execute_reply.started": "2024-10-20T15:57:48.870754Z"
529
+ }
530
+ },
531
+ "outputs": [],
532
+ "source": [
533
+ "# Step 9: Define the training and validation functions with mixed precision\n",
534
+ "def train(model, dataloader, optimizer, device, scaler):\n",
535
+ " model.train()\n",
536
+ " total_loss = 0\n",
537
+ " for batch in dataloader:\n",
538
+ " input_ids = batch['input_ids'].to(device)\n",
539
+ " attention_mask = batch['attention_mask'].to(device)\n",
540
+ " start_positions = batch['start_positions'].to(device)\n",
541
+ " end_positions = batch['end_positions'].to(device)\n",
542
+ "\n",
543
+ " optimizer.zero_grad()\n",
544
+ "\n",
545
+ " # Use autocast for mixed precision\n",
546
+ " with autocast():\n",
547
+ " outputs = model(input_ids, attention_mask=attention_mask, start_positions=start_positions, end_positions=end_positions)\n",
548
+ " loss = outputs.loss\n",
549
+ " total_loss += loss.item()\n",
550
+ "\n",
551
+ " # Scale the loss and backpropagate\n",
552
+ " scaler.scale(loss).backward()\n",
553
+ " scaler.step(optimizer)\n",
554
+ " scaler.update()\n",
555
+ "\n",
556
+ " return total_loss / len(dataloader)\n",
557
+ "\n",
558
+ "def validate(model, dataloader, device):\n",
559
+ " model.eval()\n",
560
+ " total_loss = 0\n",
561
+ " correct = 0\n",
562
+ " total = 0\n",
563
+ " with torch.no_grad():\n",
564
+ " for batch in dataloader:\n",
565
+ " input_ids = batch['input_ids'].to(device)\n",
566
+ " attention_mask = batch['attention_mask'].to(device)\n",
567
+ " start_positions = batch['start_positions'].to(device)\n",
568
+ " end_positions = batch['end_positions'].to(device)\n",
569
+ "\n",
570
+ " outputs = model(input_ids, attention_mask=attention_mask, start_positions=start_positions, end_positions=end_positions)\n",
571
+ " loss = outputs.loss\n",
572
+ " total_loss += loss.item()\n",
573
+ "\n",
574
+ " # Get the predicted start and end positions\n",
575
+ " start_preds = torch.argmax(outputs.start_logits, dim=1)\n",
576
+ " end_preds = torch.argmax(outputs.end_logits, dim=1)\n",
577
+ "\n",
578
+ " # Calculate accuracy: Check if both start and end positions are correct\n",
579
+ " correct += ((start_preds == start_positions) & (end_preds == end_positions)).sum().item()\n",
580
+ " total += input_ids.size(0)\n",
581
+ "\n",
582
+ " avg_loss = total_loss / len(dataloader)\n",
583
+ " accuracy = correct / total if total > 0 else 0\n",
584
+ " return avg_loss, accuracy\n"
585
+ ]
586
+ },
587
+ {
588
+ "cell_type": "code",
589
+ "execution_count": 12,
590
+ "metadata": {
591
+ "execution": {
592
+ "iopub.execute_input": "2024-10-18T20:24:54.990665Z",
593
+ "iopub.status.busy": "2024-10-18T20:24:54.990241Z",
594
+ "iopub.status.idle": "2024-10-18T20:59:50.571427Z",
595
+ "shell.execute_reply": "2024-10-18T20:59:50.570475Z",
596
+ "shell.execute_reply.started": "2024-10-18T20:24:54.990623Z"
597
+ }
598
+ },
599
+ "outputs": [
600
+ {
601
+ "name": "stderr",
602
+ "output_type": "stream",
603
+ "text": [
604
+ "/tmp/ipykernel_30/3732227169.py:14: FutureWarning: `torch.cuda.amp.autocast(args...)` is deprecated. Please use `torch.amp.autocast('cuda', args...)` instead.\n",
605
+ " with autocast():\n"
606
+ ]
607
+ },
608
+ {
609
+ "name": "stdout",
610
+ "output_type": "stream",
611
+ "text": [
612
+ "Epoch 1/3, Training Loss: 1.7261, Validation Loss: 1.3148, Validation Accuracy: 0.4825\n",
613
+ "Epoch 2/3, Training Loss: 1.1330, Validation Loss: 1.3120, Validation Accuracy: 0.4916\n",
614
+ "Epoch 3/3, Training Loss: 0.8496, Validation Loss: 1.3419, Validation Accuracy: 0.4988\n",
615
+ "\n",
616
+ "Total Average Validation Accuracy over 3 epochs: 0.4910\n"
617
+ ]
618
+ }
619
+ ],
620
+ "source": [
621
+ "# Step 10: Training Loop with accuracy printing\n",
622
+ "num_epochs = 3 # Reduced number of epochs for faster results\n",
623
+ "total_accuracy = 0 # To track cumulative accuracy across epochs\n",
624
+ "\n",
625
+ "for epoch in range(num_epochs):\n",
626
+ " avg_train_loss = train(model, train_dataloader, optimizer, device, scaler)\n",
627
+ " avg_val_loss, val_accuracy = validate(model, val_dataloader, device)\n",
628
+ " \n",
629
+ " # Accumulate total accuracy over all epochs\n",
630
+ " total_accuracy += val_accuracy\n",
631
+ " \n",
632
+ " print(f\"Epoch {epoch+1}/{num_epochs}, Training Loss: {avg_train_loss:.4f}, Validation Loss: {avg_val_loss:.4f}, Validation Accuracy: {val_accuracy:.4f}\")\n",
633
+ "\n",
634
+ "# Print the cumulative accuracy over all epochs\n",
635
+ "avg_total_accuracy = total_accuracy / num_epochs\n",
636
+ "print(f\"\\nTotal Average Validation Accuracy over {num_epochs} epochs: {avg_total_accuracy:.4f}\")\n"
637
+ ]
638
+ },
639
+ {
640
+ "cell_type": "code",
641
+ "execution_count": 24,
642
+ "metadata": {
643
+ "execution": {
644
+ "iopub.execute_input": "2024-10-20T15:59:38.631362Z",
645
+ "iopub.status.busy": "2024-10-20T15:59:38.630998Z",
646
+ "iopub.status.idle": "2024-10-20T15:59:41.417489Z",
647
+ "shell.execute_reply": "2024-10-20T15:59:41.416356Z",
648
+ "shell.execute_reply.started": "2024-10-20T15:59:38.631329Z"
649
+ }
650
+ },
651
+ "outputs": [
652
+ {
653
+ "data": {
654
+ "text/plain": [
655
+ "('squad-distilbert-trained/DISTILBERT_model/tokenizer_config.json',\n",
656
+ " 'squad-distilbert-trained/DISTILBERT_model/special_tokens_map.json',\n",
657
+ " 'squad-distilbert-trained/DISTILBERT_model/vocab.txt',\n",
658
+ " 'squad-distilbert-trained/DISTILBERT_model/added_tokens.json',\n",
659
+ " 'squad-distilbert-trained/DISTILBERT_model/tokenizer.json')"
660
+ ]
661
+ },
662
+ "execution_count": 24,
663
+ "metadata": {},
664
+ "output_type": "execute_result"
665
+ }
666
+ ],
667
+ "source": [
668
+ "# Define the directory where you want to save the model\n",
669
+ "model_save_path = 'DISTILBERT_model'\n",
670
+ "\n",
671
+ "# Create the directory if it doesn't exist\n",
672
+ "if not os.path.exists(model_save_path):\n",
673
+ " os.makedirs(model_save_path)\n",
674
+ "\n",
675
+ "\n",
676
+ "# Save the trained model and tokenizer\n",
677
+ "model.save_pretrained(model_save_path)\n",
678
+ "tokenizer.save_pretrained(model_save_path)"
679
+ ]
680
+ },
681
+ {
682
+ "cell_type": "code",
683
+ "execution_count": 2,
684
+ "metadata": {
685
+ "execution": {
686
+ "iopub.execute_input": "2024-10-20T16:01:01.362751Z",
687
+ "iopub.status.busy": "2024-10-20T16:01:01.362320Z",
688
+ "iopub.status.idle": "2024-10-20T16:01:16.259581Z",
689
+ "shell.execute_reply": "2024-10-20T16:01:16.258628Z",
690
+ "shell.execute_reply.started": "2024-10-20T16:01:01.362708Z"
691
+ }
692
+ },
693
+ "outputs": [],
694
+ "source": [
695
+ "\n",
696
+ "# # Compress the model directory into a zip file\n",
697
+ "# !zip -r distilbertmodel.zip squad-distilbert-trained/DISTILBERT_model\n",
698
+ "\n",
699
+ "# # Download the zip file to your local system\n",
700
+ "# from IPython.display import FileLink\n",
701
+ "\n",
702
+ "# # Display a link to download the file\n",
703
+ "# FileLink(r'distilbertmodel.zip')\n"
704
+ ]
705
+ },
706
+ {
707
+ "cell_type": "markdown",
708
+ "metadata": {},
709
+ "source": [
710
+ "### Post Code Summary\n",
711
+ "\n",
712
+ "In this section, we perform the initialization, training, and validation of the DistilBERT model specifically designed for question answering tasks using the `DistilBertForQuestionAnswering` class from the Hugging Face Transformers library.\n",
713
+ "\n",
714
+ "1. **Model Initialization**: \n",
715
+ " - We load the pre-trained DistilBERT model, which has been fine-tuned on the SQuAD dataset, making it well-suited for extracting answers from a given context based on a specific question. The model is initialized with a learning rate of `3e-5` to ensure stable convergence during training.\n",
716
+ "\n",
717
+ "2. **Optimizer Setup**: \n",
718
+ " - The AdamW optimizer is employed to improve weight updates during training, accounting for weight decay, which helps prevent overfitting.\n",
719
+ "\n",
720
+ "3. **Device Configuration**: \n",
721
+ " - We check for GPU availability and move the model to the appropriate device (GPU or CPU) for faster training. This is critical for handling larger datasets efficiently.\n",
722
+ "\n",
723
+ "4. **Mixed Precision Training**: \n",
724
+ " - To optimize performance and reduce memory usage, we implement mixed precision training using PyTorch's GradScaler and autocast functions. This technique allows the model to use half-precision floating-point numbers where applicable, significantly speeding up training without sacrificing much in terms of model accuracy.\n",
725
+ "\n",
726
+ "5. **Training Function**: \n",
727
+ " - The training function iterates through the training data, calculating the loss for each batch. We use the model’s outputs to compute the loss based on the start and end positions of the answers. The loss is scaled and backpropagated, and the optimizer updates the model weights.\n",
728
+ "\n",
729
+ "6. **Validation Function**: \n",
730
+ " - The validation function assesses the model's performance on a separate validation dataset. It calculates the loss and accuracy by comparing the predicted start and end positions with the true labels. This step helps gauge the model's ability to generalize beyond the training data.\n",
731
+ "\n",
732
+ "7. **Training Loop**: \n",
733
+ " - Over three epochs, we track the average training loss, validation loss, and validation accuracy. The training loss decreases over epochs, indicating that the model is learning; however, validation loss fluctuates slightly, suggesting that the model might not be fully converging and could benefit from additional training or tuning.\n",
734
+ "\n",
735
+ "8. **Model Saving**: \n",
736
+ " - After completing the training process, we save the fine-tuned model and tokenizer to a specified directory (`DISTILBERT_model`). This step ensures that the trained model can be easily loaded for inference or further training without the need to retrain from scratch.\n",
737
+ "\n",
738
+ "Overall, this implementation showcases a structured approach to fine-tuning a DistilBERT model for question answering tasks, leveraging modern techniques like mixed precision training to enhance performance and efficiency.\n"
739
+ ]
740
+ },
741
+ {
742
+ "cell_type": "markdown",
743
+ "metadata": {},
744
+ "source": [
745
+ "### Evaluation & Testing\n",
746
+ "\n"
747
+ ]
748
+ },
749
+ {
750
+ "cell_type": "code",
751
+ "execution_count": 4,
752
+ "metadata": {},
753
+ "outputs": [],
754
+ "source": [
755
+ "tokenizer=DistilBertTokenizerFast.from_pretrained('DISTILBERT_model')\n",
756
+ "model = DistilBertForQuestionAnswering.from_pretrained('DISTILBERT_model')"
757
+ ]
758
+ },
759
+ {
760
+ "cell_type": "code",
761
+ "execution_count": 5,
762
+ "metadata": {
763
+ "execution": {
764
+ "iopub.execute_input": "2024-10-20T16:07:34.892291Z",
765
+ "iopub.status.busy": "2024-10-20T16:07:34.891437Z",
766
+ "iopub.status.idle": "2024-10-20T16:07:34.899630Z",
767
+ "shell.execute_reply": "2024-10-20T16:07:34.898495Z",
768
+ "shell.execute_reply.started": "2024-10-20T16:07:34.892244Z"
769
+ }
770
+ },
771
+ "outputs": [],
772
+ "source": [
773
+ "# Step 12: Prediction function\n",
774
+ "def predict(context, question):\n",
775
+ " inputs = tokenizer(question, context, max_length=256, truncation=True, padding=\"max_length\", return_tensors=\"pt\").to(device)\n",
776
+ " model.eval()\n",
777
+ " with torch.no_grad():\n",
778
+ " outputs = model(**inputs)\n",
779
+ " start_scores = outputs.start_logits\n",
780
+ " end_scores = outputs.end_logits\n",
781
+ "\n",
782
+ " start_idx = torch.argmax(start_scores)\n",
783
+ " end_idx = torch.argmax(end_scores)\n",
784
+ "\n",
785
+ " input_ids = inputs['input_ids'].squeeze().tolist()\n",
786
+ " answer_tokens = input_ids[start_idx:end_idx + 1]\n",
787
+ " answer = tokenizer.decode(answer_tokens)\n",
788
+ "\n",
789
+ " return answer\n"
790
+ ]
791
+ },
792
+ {
793
+ "cell_type": "code",
794
+ "execution_count": 8,
795
+ "metadata": {
796
+ "execution": {
797
+ "iopub.execute_input": "2024-10-20T16:09:12.435863Z",
798
+ "iopub.status.busy": "2024-10-20T16:09:12.435005Z",
799
+ "iopub.status.idle": "2024-10-20T16:09:26.610097Z",
800
+ "shell.execute_reply": "2024-10-20T16:09:26.609139Z",
801
+ "shell.execute_reply.started": "2024-10-20T16:09:12.435820Z"
802
+ }
803
+ },
804
+ "outputs": [
805
+ {
806
+ "name": "stdout",
807
+ "output_type": "stream",
808
+ "text": [
809
+ "Predicted Answer: new delhi\n"
810
+ ]
811
+ }
812
+ ],
813
+ "source": [
814
+ "context = \"India is a country located in South Asia. Its captial is New Delhi.\"\n",
815
+ "question = \"What is the capital of India?\"\n",
816
+ "\n",
817
+ "predicted_answer = predict(context, question)\n",
818
+ "print(\"Predicted Answer:\", predicted_answer)"
819
+ ]
820
+ },
821
+ {
822
+ "cell_type": "code",
823
+ "execution_count": 9,
824
+ "metadata": {
825
+ "execution": {
826
+ "iopub.execute_input": "2024-10-18T21:00:02.159304Z",
827
+ "iopub.status.busy": "2024-10-18T21:00:02.158666Z",
828
+ "iopub.status.idle": "2024-10-18T21:00:02.201810Z",
829
+ "shell.execute_reply": "2024-10-18T21:00:02.200906Z",
830
+ "shell.execute_reply.started": "2024-10-18T21:00:02.159268Z"
831
+ }
832
+ },
833
+ "outputs": [
834
+ {
835
+ "name": "stdout",
836
+ "output_type": "stream",
837
+ "text": [
838
+ "Predicted Answer: saint bernadette soubirous\n"
839
+ ]
840
+ }
841
+ ],
842
+ "source": [
843
+ "context = \"Architecturally, the school has a Catholic character. Atop the Main Building's gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \\\"Venite Ad Me Omnes\\\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.\"\n",
844
+ "question = \"To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?\"\n",
845
+ "\n",
846
+ "predicted_answer = predict(context, question)\n",
847
+ "print(\"Predicted Answer:\", predicted_answer)"
848
+ ]
849
+ },
850
+ {
851
+ "cell_type": "code",
852
+ "execution_count": 10,
853
+ "metadata": {
854
+ "execution": {
855
+ "iopub.execute_input": "2024-10-20T16:11:39.620287Z",
856
+ "iopub.status.busy": "2024-10-20T16:11:39.619610Z",
857
+ "iopub.status.idle": "2024-10-20T16:11:39.641221Z",
858
+ "shell.execute_reply": "2024-10-20T16:11:39.640332Z",
859
+ "shell.execute_reply.started": "2024-10-20T16:11:39.620243Z"
860
+ }
861
+ },
862
+ "outputs": [
863
+ {
864
+ "name": "stdout",
865
+ "output_type": "stream",
866
+ "text": [
867
+ "Predicted Answer: music has the power to inspire, heal, and entertain\n"
868
+ ]
869
+ }
870
+ ],
871
+ "source": [
872
+ "\n",
873
+ "context = '''Music is an art form whose medium is sound and silence. It is a universal language that \n",
874
+ "can evoke emotions, convey messages, and bring people together. Music has been an \n",
875
+ "integral part of human culture for centuries, with various genres and styles emerging \n",
876
+ "across the world. From classical to contemporary, music has the power to inspire, heal, \n",
877
+ "and entertain.'''\n",
878
+ "\n",
879
+ "question = \"What is the difference between Music and Harmony?\"\n",
880
+ "\n",
881
+ "predicted_answer = predict(context, question)\n",
882
+ "print(\"Predicted Answer:\", predicted_answer)"
883
+ ]
884
+ },
885
+ {
886
+ "cell_type": "code",
887
+ "execution_count": 11,
888
+ "metadata": {
889
+ "execution": {
890
+ "iopub.execute_input": "2024-10-18T21:00:02.223992Z",
891
+ "iopub.status.busy": "2024-10-18T21:00:02.223682Z",
892
+ "iopub.status.idle": "2024-10-18T21:00:02.243487Z",
893
+ "shell.execute_reply": "2024-10-18T21:00:02.242627Z",
894
+ "shell.execute_reply.started": "2024-10-18T21:00:02.223961Z"
895
+ }
896
+ },
897
+ "outputs": [
898
+ {
899
+ "name": "stdout",
900
+ "output_type": "stream",
901
+ "text": [
902
+ "Predicted Answer: california\n"
903
+ ]
904
+ }
905
+ ],
906
+ "source": [
907
+ "context = \"Pappu is from america. He is from california\"\n",
908
+ "question = \"which country is pappu from?\"\n",
909
+ "\n",
910
+ "predicted_answer = predict(context, question)\n",
911
+ "print(\"Predicted Answer:\", predicted_answer)"
912
+ ]
913
+ },
914
+ {
915
+ "cell_type": "code",
916
+ "execution_count": 48,
917
+ "metadata": {},
918
+ "outputs": [
919
+ {
920
+ "name": "stdout",
921
+ "output_type": "stream",
922
+ "text": [
923
+ "Predicted Answer: music has the power to inspire, heal, and entertain\n",
924
+ "Actual Answer: music is an art form and harmony refers to the combination of sounds.\n",
925
+ "BLEU Score: 0.2850\n",
926
+ "ROUGE-1 F1 Score: 0.3636\n",
927
+ "ROUGE-2 F1 Score: 0.0000\n",
928
+ "ROUGE-L F1 Score: 0.1818\n",
929
+ "F1 Score: 0.3636\n"
930
+ ]
931
+ }
932
+ ],
933
+ "source": [
934
+ "from nltk.translate.bleu_score import sentence_bleu\n",
935
+ "from rouge_score import rouge_scorer\n",
936
+ "\n",
937
+ "# Example inputs\n",
938
+ "context = \"\"\"Music is an art form whose medium is sound and silence. It is a universal language that \n",
939
+ "can evoke emotions, convey messages, and bring people together. Music has been an \n",
940
+ "integral part of human culture for centuries, with various genres and styles emerging \n",
941
+ "across the world. From classical to contemporary, music has the power to inspire, heal, \n",
942
+ "and entertain.\"\"\"\n",
943
+ "\n",
944
+ "question = \"What is the difference between Music and Harmony?\"\n",
945
+ "\n",
946
+ "# Define actual and predicted answers\n",
947
+ "actual_answer = \"Music is an art form and harmony refers to the combination of sounds.\"\n",
948
+ "predicted_answer = \"music has the power to inspire, heal, and entertain\"\n",
949
+ "\n",
950
+ "# Normalize answers (lowercase)\n",
951
+ "actual_answer = actual_answer.lower().strip()\n",
952
+ "predicted_answer = predicted_answer.lower().strip()\n",
953
+ "\n",
954
+ "# Calculate BLEU score\n",
955
+ "bleu_score = sentence_bleu([actual_answer.split()], predicted_answer.split(), weights=(1.0, 0.0, 0.0, 0.0))\n",
956
+ "\n",
957
+ "# Calculate ROUGE scores\n",
958
+ "scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)\n",
959
+ "rouge_scores = scorer.score(actual_answer, predicted_answer)\n",
960
+ "\n",
961
+ "# Calculate F1 score based on ROUGE-1 precision and recall\n",
962
+ "precision = rouge_scores['rouge1'].precision\n",
963
+ "recall = rouge_scores['rouge1'].recall\n",
964
+ "if precision + recall > 0: # Avoid division by zero\n",
965
+ " f1_score = 2 * (precision * recall) / (precision + recall)\n",
966
+ "else:\n",
967
+ " f1_score = 0.0\n",
968
+ "\n",
969
+ "# Print the results\n",
970
+ "print(f\"Predicted Answer: {predicted_answer}\")\n",
971
+ "print(f\"Actual Answer: {actual_answer}\")\n",
972
+ "print(f\"BLEU Score: {bleu_score:.4f}\")\n",
973
+ "print(f\"ROUGE-1 F1 Score: {rouge_scores['rouge1'].fmeasure:.4f}\")\n",
974
+ "print(f\"ROUGE-2 F1 Score: {rouge_scores['rouge2'].fmeasure:.4f}\")\n",
975
+ "print(f\"ROUGE-L F1 Score: {rouge_scores['rougeL'].fmeasure:.4f}\")\n",
976
+ "print(f\"F1 Score: {f1_score:.4f}\")\n"
977
+ ]
978
+ },
979
+ {
980
+ "cell_type": "markdown",
981
+ "metadata": {},
982
+ "source": [
983
+ "### Results Summary\n",
984
+ "\n",
985
+ "**Predicted Answer**: music has the power to inspire, heal, and entertain \n",
986
+ "**Actual Answer**: music is an art form and harmony refers to the combination of sounds. \n",
987
+ "**BLEU Score**: 0.2850 \n",
988
+ "**ROUGE-1 F1 Score**: 0.3636 \n",
989
+ "**ROUGE-2 F1 Score**: 0.0000 \n",
990
+ "**ROUGE-L F1 Score**: 0.1818 \n",
991
+ "**F1 Score**: 0.3636 \n",
992
+ "\n",
993
+ "These results indicate that DistilBERT is not performing well at the current level of fine-tuning. The low scores suggest it may require more extensive training to improve its ability to generate accurate and relevant answers.\n"
994
+ ]
995
+ },
996
+ {
997
+ "cell_type": "code",
998
+ "execution_count": null,
999
+ "metadata": {},
1000
+ "outputs": [],
1001
+ "source": []
1002
+ }
1003
+ ],
1004
+ "metadata": {
1005
+ "kaggle": {
1006
+ "accelerator": "nvidiaTeslaT4",
1007
+ "dataSources": [
1008
+ {
1009
+ "datasetId": 5902073,
1010
+ "sourceId": 9660462,
1011
+ "sourceType": "datasetVersion"
1012
+ },
1013
+ {
1014
+ "isSourceIdPinned": true,
1015
+ "modelId": 142964,
1016
+ "modelInstanceId": 119726,
1017
+ "sourceId": 141334,
1018
+ "sourceType": "modelInstanceVersion"
1019
+ }
1020
+ ],
1021
+ "dockerImageVersionId": 30787,
1022
+ "isGpuEnabled": true,
1023
+ "isInternetEnabled": true,
1024
+ "language": "python",
1025
+ "sourceType": "notebook"
1026
+ },
1027
+ "kernelspec": {
1028
+ "display_name": "Python 3 (ipykernel)",
1029
+ "language": "python",
1030
+ "name": "python3"
1031
+ },
1032
+ "language_info": {
1033
+ "codemirror_mode": {
1034
+ "name": "ipython",
1035
+ "version": 3
1036
+ },
1037
+ "file_extension": ".py",
1038
+ "mimetype": "text/x-python",
1039
+ "name": "python",
1040
+ "nbconvert_exporter": "python",
1041
+ "pygments_lexer": "ipython3",
1042
+ "version": "3.11.4"
1043
+ }
1044
+ },
1045
+ "nbformat": 4,
1046
+ "nbformat_minor": 4
1047
+ }
app.py CHANGED
@@ -1,64 +1,188 @@
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
1
+ !pip install -q gradio
2
+ import warnings
3
+ warnings.filterwarnings('ignore')
4
+
5
+ # Import necessary libraries
6
  import gradio as gr
7
+ import torch
8
+ from transformers import (
9
+ BertTokenizerFast,
10
+ BertForQuestionAnswering,
11
+ AutoTokenizer,
12
+ BartForQuestionAnswering,
13
+ DistilBertTokenizerFast,
14
+ DistilBertForQuestionAnswering
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  )
16
+ import gc
17
+
18
+ # Create a context store
19
+ context_store = []
20
+ selected_model = None # To track the selected model
21
+
22
+ # Define models and tokenizers
23
+ def load_bert_model_and_tokenizer():
24
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+ model_save_path = "LivisLiquoro/BERT_Model_Squad1.1"
26
+ model = BertForQuestionAnswering.from_pretrained(model_save_path)
27
+ tokenizer = BertTokenizerFast.from_pretrained(model_save_path)
28
+ model.eval().to(device)
29
+ gc.collect()
30
+ torch.cuda.empty_cache()
31
+ return tokenizer, model, device
32
+
33
+ def load_bart_model_and_tokenizer():
34
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
35
+ model = BartForQuestionAnswering.from_pretrained("valhalla/bart-large-finetuned-squadv1")
36
+ tokenizer = AutoTokenizer.from_pretrained("valhalla/bart-large-finetuned-squadv1")
37
+ model.eval().to(device)
38
+ gc.collect()
39
+ torch.cuda.empty_cache()
40
+ return tokenizer, model, device
41
+
42
+ def load_distilbert_model_and_tokenizer():
43
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
44
+ model_save_path = "LivisLiquoro/DistilBert_model_squad1.1"
45
+ model = DistilBertForQuestionAnswering.from_pretrained(model_save_path)
46
+ tokenizer = DistilBertTokenizerFast.from_pretrained(model_save_path)
47
+ model.eval().to(device)
48
+ gc.collect()
49
+ torch.cuda.empty_cache()
50
+ return tokenizer, model, device
51
+
52
+ def clean_answer(tokens):
53
+ """
54
+ Clean the tokens by removing special tokens like [SEP], [CLS], and fixing token fragments.
55
+ """
56
+ cleaned_tokens = []
57
+ for token in tokens:
58
+ if token in ['[SEP]', '[CLS]']:
59
+ continue # Skip special tokens
60
+ token = token.replace('##', '') # Remove '##' prefix
61
+ if token: # Only add non-empty tokens
62
+ cleaned_tokens.append(token)
63
+
64
+ return tokenizer.convert_tokens_to_string(cleaned_tokens).strip() or None
65
+
66
+ def generate_answer(context, question):
67
+ max_attempts = 50 # Set maximum attempts for generating answers
68
+ attempts = 0
69
+ best_answer = None
70
+
71
+ # Adjusting the context chunking method
72
+ max_length = 512
73
+ chunks = [context[i:i + max_length] for i in range(0, len(context), max_length)]
74
+
75
+ while attempts < max_attempts:
76
+ attempts += 1
77
+ for chunk in chunks:
78
+ inputs = tokenizer(chunk, question, return_tensors='pt', truncation=True, max_length=max_length).to(device)
79
+
80
+ with torch.no_grad():
81
+ outputs = model(**inputs)
82
+ answer_start = torch.argmax(outputs.start_logits)
83
+ answer_end = torch.argmax(outputs.end_logits) + 1
84
+
85
+ if answer_start < answer_end:
86
+ answer = clean_answer(tokenizer.convert_ids_to_tokens(inputs['input_ids'][0][answer_start:answer_end]))
87
+
88
+ # Validate answer and ensure it's direct
89
+ if answer and answer.lower() != "no valid answer found":
90
+ best_answer = answer.capitalize()
91
+ break # Exit the chunk loop if a valid answer is found
92
+ if best_answer: # If an answer is found, no need to keep trying
93
+ break
94
+
95
+ if best_answer: # If a valid answer was found, exit the attempts loop
96
+ break
97
+
98
+ if best_answer:
99
+ return best_answer
100
+ else:
101
+ return "❌ No valid answer found."
102
+
103
+ # Define the Gradio interface with light theme and organized layout
104
+ def chatbot_interface():
105
+ with gr.Blocks() as demo:
106
+ # Custom CSS for light theme and layout
107
+ gr.Markdown("""
108
+ <style>
109
+ body { background-color: #f9f9f9; }
110
+ .chatbot-container { background-color: #ffffff; border-radius: 10px; padding: 20px; color: #333; font-family: Arial, sans-serif; }
111
+ .gr-button { background-color: #4CAF50; color: white; border: none; border-radius: 5px; padding: 10px 20px; font-size: 14px; cursor: pointer; }
112
+ .gr-button:hover { background-color: #45a049; }
113
+ .gr-textbox { background-color: #ffffff; color: #333; border-radius: 5px; border: 1px solid #ddd; padding: 10px; }
114
+ .gr-chatbot { background-color: #e6e6e6; border-radius: 10px; padding: 15px; color: #333; }
115
+ .footer { text-align: right; font-size: 12px; color: #777; font-style: italic; }
116
+ .note { text-align: right; font-size: 10px; color: #777; font-style: italic; position: absolute; bottom: 10px; right: 10px; }
117
+ </style>
118
+ """)
119
+
120
+ # Header
121
+ gr.Markdown("<h1 style='text-align: center; color: #4CAF50;'>EDITH: Multi-Model Question Answering Platform</h1>")
122
+ gr.Markdown("<p style='text-align: center; color: #777;'>Switch between BERT, BART, and DistilBERT models and ask questions based on the context.</p>")
123
+
124
+ context_state = gr.State()
125
+ model_choice_state = gr.State(value="BERT") # Default model is BERT
126
+
127
+ with gr.Row():
128
+ with gr.Column(scale=11): # Left panel for chatbot and question input (45%)
129
+ chatbot = gr.Chatbot(label="Chatbot")
130
+ question_input = gr.Textbox(label="Ask a Question", placeholder="Enter your question here...", lines=1)
131
+ submit_btn = gr.Button("Submit Question")
132
+
133
+ with gr.Column(scale=9): # Right panel for setting context and instructions (55%)
134
+ context_input = gr.Textbox(label="Set Context", placeholder="Enter the context here...", lines=4)
135
+ set_context_btn = gr.Button("Set Context")
136
+ clear_context_btn = gr.Button("Clear Context")
137
+
138
+ # Model selection buttons
139
+ model_selection = gr.Radio(choices=["BERT", "BART", "DistilBERT"], label="Select Model", value="BERT")
140
+ status_message = gr.Markdown("")
141
+
142
+ gr.Markdown("<strong>Instructions:</strong><br>1. Set a context.<br>2. Select the model (BERT, BART, or DistilBERT).<br>3. Ask questions based on the context.<br><br><strong>Note:</strong> <span class='note'>The BART model is pre-trained from Hugging Face. Credits to Hugging Face and the person who fine-tuned this model ('valhalla/bart-large-finetuned-squadv1')</span>")
143
+
144
+ footer = gr.Markdown("<div class='footer'>Prepared by: Team EDITH</div>")
145
+
146
+ def set_context(context):
147
+ if not context.strip():
148
+ return gr.update(), "Please enter a valid context.", None
149
+ return gr.update(visible=False), "Context has been set. You can now ask questions.", context
150
+
151
+ def clear_context():
152
+ return gr.update(visible=True), "Context has been cleared. Please set a new context.", None
153
+
154
+ def handle_question(question, history, context, model_choice):
155
+ global tokenizer, model, device
156
+
157
+ if not context:
158
+ return history, "Please set the context before asking questions."
159
+ if not question.strip():
160
+ return history, "Please enter a valid question."
161
+
162
+ # Load the selected model and tokenizer
163
+ if model_choice == "BERT":
164
+ tokenizer, model, device = load_bert_model_and_tokenizer()
165
+ model_name = "BERT"
166
+ elif model_choice == "BART":
167
+ tokenizer, model, device = load_bart_model_and_tokenizer()
168
+ model_name = "BART"
169
+ elif model_choice == "DistilBERT":
170
+ tokenizer, model, device = load_distilbert_model_and_tokenizer()
171
+ model_name = "DistilBERT"
172
+
173
+ answer = generate_answer(context, question)
174
+ history = history + [[f"👤: {question}", f"🤖 ({model_name}): {answer}"]] # Show the selected model with the answer
175
+ return history, ""
176
+
177
+ set_context_btn.click(set_context, inputs=context_input, outputs=[context_input, status_message, context_state])
178
+ clear_context_btn.click(clear_context, inputs=None, outputs=[context_input, status_message, context_state])
179
+ submit_btn.click(handle_question, inputs=[question_input, chatbot, context_state, model_selection], outputs=[chatbot, question_input])
180
+
181
+ # Enable "Enter" key to trigger the "Submit" button
182
+ question_input.submit(handle_question, inputs=[question_input, chatbot, context_state, model_selection], outputs=[chatbot, question_input])
183
 
184
+ return demo
185
 
186
+ # Run the Gradio interface
187
+ interface = chatbot_interface()
188
+ interface.launch(share=True)