File size: 11,443 Bytes
5584c5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaForSequenceClassification(\n",
       "  (model): LlamaModel(\n",
       "    (embed_tokens): Embedding(49153, 576, padding_idx=49152)\n",
       "    (layers): ModuleList(\n",
       "      (0-29): 30 x LlamaDecoderLayer(\n",
       "        (self_attn): LlamaSdpaAttention(\n",
       "          (q_proj): Linear(in_features=576, out_features=576, bias=False)\n",
       "          (k_proj): Linear(in_features=576, out_features=192, bias=False)\n",
       "          (v_proj): Linear(in_features=576, out_features=192, bias=False)\n",
       "          (o_proj): Linear(in_features=576, out_features=576, bias=False)\n",
       "          (rotary_emb): LlamaRotaryEmbedding()\n",
       "        )\n",
       "        (mlp): LlamaMLP(\n",
       "          (gate_proj): Linear(in_features=576, out_features=1536, bias=False)\n",
       "          (up_proj): Linear(in_features=576, out_features=1536, bias=False)\n",
       "          (down_proj): Linear(in_features=1536, out_features=576, bias=False)\n",
       "          (act_fn): SiLU()\n",
       "        )\n",
       "        (input_layernorm): LlamaRMSNorm((576,), eps=1e-05)\n",
       "        (post_attention_layernorm): LlamaRMSNorm((576,), eps=1e-05)\n",
       "      )\n",
       "    )\n",
       "    (norm): LlamaRMSNorm((576,), eps=1e-05)\n",
       "    (rotary_emb): LlamaRotaryEmbedding()\n",
       "  )\n",
       "  (score): Linear(in_features=576, out_features=2, bias=False)\n",
       ")"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from transformers import GPT2Tokenizer, LlamaForSequenceClassification\n",
    "\n",
    "# Load the GPT2 tokenizer and Llama model for sequence classification\n",
    "model_path = r\"C:\\Users\\jatin\\OneDrive\\Desktop\\plagiarism-detection\\smolLM-fined-tuned-for-PLAGAIRISM-Detection\\model\"\n",
    "tokenizer = GPT2Tokenizer.from_pretrained(model_path, local_files_only=True)\n",
    "model = LlamaForSequenceClassification.from_pretrained(model_path, local_files_only=True)\n",
    "\n",
    "# Set model to evaluation mode\n",
    "model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>sentence1</th>\n",
       "      <th>sentence2</th>\n",
       "      <th>label</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>A person on a horse jumps over a broken down a...</td>\n",
       "      <td>A person is at a diner, ordering an omelette.</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>A person on a horse jumps over a broken down a...</td>\n",
       "      <td>A person is outdoors, on a horse.</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Children smiling and waving at camera</td>\n",
       "      <td>There are children present</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Children smiling and waving at camera</td>\n",
       "      <td>The kids are frowning</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>A boy is jumping on skateboard in the middle o...</td>\n",
       "      <td>The boy skates down the sidewalk.</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                           sentence1  \\\n",
       "0  A person on a horse jumps over a broken down a...   \n",
       "1  A person on a horse jumps over a broken down a...   \n",
       "2              Children smiling and waving at camera   \n",
       "3              Children smiling and waving at camera   \n",
       "4  A boy is jumping on skateboard in the middle o...   \n",
       "\n",
       "                                       sentence2  label  \n",
       "0  A person is at a diner, ordering an omelette.      0  \n",
       "1              A person is outdoors, on a horse.      1  \n",
       "2                     There are children present      1  \n",
       "3                          The kids are frowning      0  \n",
       "4              The boy skates down the sidewalk.      0  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"train_snli.txt\", delimiter='\\t', header=None, names=['sentence1', 'sentence2', 'label'])\n",
    "\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch.utils.data import Dataset, DataLoader\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "class PlagiarismDataset(Dataset):\n",
    "    def __init__(self, df, tokenizer, max_length=128):\n",
    "        self.df = df\n",
    "        self.tokenizer = tokenizer\n",
    "        self.max_length = max_length\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.df)\n",
    "\n",
    "    def __getitem__(self, index):\n",
    "        row = self.df.iloc[index]\n",
    "\n",
    "        # Ensure the sentences are strings; convert or skip if not\n",
    "        sentence1 = str(row['sentence1']) if not pd.isna(row['sentence1']) else \"\"\n",
    "        sentence2 = str(row['sentence2']) if not pd.isna(row['sentence2']) else \"\"\n",
    "\n",
    "        inputs = self.tokenizer(\n",
    "            sentence1, sentence2,\n",
    "            add_special_tokens=True,\n",
    "            max_length=self.max_length,\n",
    "            padding='max_length',\n",
    "            truncation=True,\n",
    "            return_tensors=\"pt\"\n",
    "        )\n",
    "\n",
    "        label = torch.tensor(row['label'], dtype=torch.long)\n",
    "\n",
    "        return {\n",
    "            'input_ids': inputs['input_ids'].squeeze(0),\n",
    "            'attention_mask': inputs['attention_mask'].squeeze(0),\n",
    "            'label': label\n",
    "        }\n",
    "\n",
    "def collate_fn(batch):\n",
    "    input_ids = torch.stack([item['input_ids'] for item in batch])\n",
    "    attention_masks = torch.stack([item['attention_mask'] for item in batch])\n",
    "    labels = torch.stack([item['label'] for item in batch])\n",
    "\n",
    "    return {\n",
    "        'input_ids': input_ids,\n",
    "        'attention_mask': attention_masks,\n",
    "        'label': labels\n",
    "    }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "device(type='cuda')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Assuming you have a separate test set or validation set (e.g., df_test)\n",
    "df_test = df[3_66_900:]\n",
    "# Add padding token if not already\n",
    "tokenizer.add_special_tokens({'pad_token': '[PAD]'})\n",
    "\n",
    "# Resize the model's token embeddings to fit the new tokenizer\n",
    "model.resize_token_embeddings(len(tokenizer))\n",
    "\n",
    "# Create DataLoader for the test set\n",
    "test_dataset = PlagiarismDataset(df_test, tokenizer)\n",
    "test_data_loader = DataLoader(test_dataset, batch_size=16, shuffle=False, collate_fn=collate_fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Classification Report:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "           0       1.00      1.00      1.00       236\n",
      "           1       1.00      1.00      1.00       237\n",
      "\n",
      "    accuracy                           1.00       473\n",
      "   macro avg       1.00      1.00      1.00       473\n",
      "weighted avg       1.00      1.00      1.00       473\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "# Function to evaluate model on the test set\n",
    "# Set up device\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "# Move model to the appropriate device\n",
    "model = model.to(device)\n",
    "\n",
    "# Function to evaluate the model\n",
    "def evaluate_model(model, data_loader):\n",
    "    model.eval()  # Set model to evaluation mode\n",
    "    preds_list = []\n",
    "    labels_list = []\n",
    "\n",
    "    with torch.no_grad():  # Disable gradient calculation for evaluation\n",
    "        for batch in data_loader:\n",
    "            # Move input tensors to the same device as the model\n",
    "            input_ids = batch['input_ids'].to(device)\n",
    "            attention_mask = batch['attention_mask'].to(device)\n",
    "            labels = batch['label'].to(device)\n",
    "            \n",
    "            # Get model outputs\n",
    "            outputs = model(input_ids=input_ids, attention_mask=attention_mask)\n",
    "            preds = torch.argmax(outputs.logits, dim=1)\n",
    "\n",
    "            # Append predictions and true labels to respective lists\n",
    "            preds_list.extend(preds.cpu().numpy())\n",
    "            labels_list.extend(labels.cpu().numpy())\n",
    "    \n",
    "    # Compute evaluation metrics\n",
    "    from sklearn.metrics import classification_report\n",
    "    report = classification_report(labels_list, preds_list)\n",
    "    print(\"Classification Report:\\n\", report)\n",
    "\n",
    "# Evaluate the model\n",
    "evaluate_model(model, test_data_loader)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "LLM",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}