File size: 12,693 Bytes
0059492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
331
332
333
334
335
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ppak/GitHub/LLM-Enabled-Process-Map/venv/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "import ast\n",
    "import numpy as np\n",
    "import random\n",
    "import torch\n",
    "\n",
    "from datasets import load_dataset\n",
    "from huggingface_hub import hf_hub_download\n",
    "from torch.utils.data import DataLoader\n",
    "from transformers import AutoTokenizer\n",
    "from tqdm import tqdm\n",
    "\n",
    "from model.distilbert import DistilBertClassificationModel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set the seed for Python's random module\n",
    "random.seed(42)\n",
    "\n",
    "# Set the seed for NumPy\n",
    "np.random.seed(42)\n",
    "\n",
    "# Set the seed for PyTorch\n",
    "torch.manual_seed(42)\n",
    "\n",
    "# Ensure reproducibility on GPUs\n",
    "if torch.cuda.is_available():\n",
    "    torch.cuda.manual_seed(42)\n",
    "    torch.cuda.manual_seed_all(42)  # For multi-GPU setups\n",
    "\n",
    "# Optional: Ensure deterministic behavior\n",
    "torch.backends.cudnn.deterministic = True\n",
    "torch.backends.cudnn.benchmark = False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DistilBertClassificationModel(\n",
       "  (base_model): DistilBertModel(\n",
       "    (embeddings): Embeddings(\n",
       "      (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
       "      (position_embeddings): Embedding(512, 768)\n",
       "      (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
       "      (dropout): Dropout(p=0.1, inplace=False)\n",
       "    )\n",
       "    (transformer): Transformer(\n",
       "      (layer): ModuleList(\n",
       "        (0-5): 6 x TransformerBlock(\n",
       "          (attention): DistilBertSdpaAttention(\n",
       "            (dropout): Dropout(p=0.1, inplace=False)\n",
       "            (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "          )\n",
       "          (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
       "          (ffn): FFN(\n",
       "            (dropout): Dropout(p=0.1, inplace=False)\n",
       "            (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
       "            (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
       "            (activation): GELUActivation()\n",
       "          )\n",
       "          (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
       "        )\n",
       "      )\n",
       "    )\n",
       "  )\n",
       "  (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
       ")"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Initialize the model\n",
    "model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-prompt-05-epochs\")\n",
    "model.eval()  # Set the model to evaluation mode"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Map (num_proc=64): 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 40767900/40767900 [11:17<00:00, 60140.26 examples/s]\n",
      "Map (num_proc=32): 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1630710/1630710 [00:30<00:00, 53153.66 examples/s]\n",
      "Map (num_proc=32): 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 724750/724750 [00:13<00:00, 52257.28 examples/s]\n"
     ]
    }
   ],
   "source": [
    "# Load dataset\n",
    "dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
    "train_dataset = dataset[\"train_prompt\"]\n",
    "test_dataset = dataset[\"test_prompt\"]\n",
    "validation_dataset = dataset[\"validation_prompt\"]\n",
    "\n",
    "# Load the tokenizer\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-prompt-05-epochs\")\n",
    "\n",
    "# Preprocessing function\n",
    "def preprocess_function(examples):\n",
    "    examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
    "    examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
    "    return tokenizer(\n",
    "        examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
    "    )\n",
    "\n",
    "train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
    "test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
    "validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# With Pretrained Weights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1607896/3376973822.py:7: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  model.classifier.load_state_dict(torch.load(classification_head_path))\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "DistilBertClassificationModel(\n",
       "  (base_model): DistilBertModel(\n",
       "    (embeddings): Embeddings(\n",
       "      (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
       "      (position_embeddings): Embedding(512, 768)\n",
       "      (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
       "      (dropout): Dropout(p=0.1, inplace=False)\n",
       "    )\n",
       "    (transformer): Transformer(\n",
       "      (layer): ModuleList(\n",
       "        (0-5): 6 x TransformerBlock(\n",
       "          (attention): DistilBertSdpaAttention(\n",
       "            (dropout): Dropout(p=0.1, inplace=False)\n",
       "            (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "            (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
       "          )\n",
       "          (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
       "          (ffn): FFN(\n",
       "            (dropout): Dropout(p=0.1, inplace=False)\n",
       "            (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
       "            (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
       "            (activation): GELUActivation()\n",
       "          )\n",
       "          (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
       "        )\n",
       "      )\n",
       "    )\n",
       "  )\n",
       "  (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
       ")"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "classification_head_path = hf_hub_download(\n",
    "    repo_id=\"ppak10/defect-classification-distilbert-prompt-05-epochs\",\n",
    "    repo_type=\"model\",\n",
    "    filename=\"classification_head.pt\"\n",
    ")\n",
    "\n",
    "model.classifier.load_state_dict(torch.load(classification_head_path))\n",
    "model.eval()  # Set the model to evaluation mode"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1416/1416 [32:38<00:00,  1.38s/it]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overall Accuracy: 0.8149261814346392\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "# Ensure the model is on the GPU\n",
    "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
    "model = model.to(device)\n",
    "\n",
    "# Define the batch size\n",
    "batch_size = 512\n",
    "\n",
    "# Create a DataLoader for the validation dataset\n",
    "validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
    "\n",
    "def label_to_classifications_batch(labels):\n",
    "    classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
    "    \n",
    "    results = []\n",
    "    for label in labels:  # Iterate over each label in the batch\n",
    "        result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
    "        results.append(result)\n",
    "    return results\n",
    "\n",
    "accuracy_total = 0\n",
    "\n",
    "# Process the validation dataset in batches\n",
    "for batch in tqdm(validation_loader):\n",
    "    texts = batch[\"text\"]\n",
    "    labels = np.array(batch[\"label\"]).T\n",
    "\n",
    "    # Move labels to GPU\n",
    "    # print(np.array(labels))\n",
    "    labels = torch.tensor(labels).to(device)\n",
    "\n",
    "    # Tokenize input for the entire batch and move to GPU\n",
    "    inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
    "    inputs = {key: value.to(device) for key, value in inputs.items()}\n",
    "\n",
    "    # Perform inference\n",
    "    outputs = model(**inputs)\n",
    "\n",
    "    # Extract logits and apply sigmoid activation for multi-label classification\n",
    "    logits = outputs[\"logits\"]\n",
    "    probs = torch.sigmoid(logits)\n",
    "\n",
    "    # Convert probabilities to one-hot encoded labels\n",
    "    preds = (probs > 0.5).int()\n",
    "    # print(preds)\n",
    "\n",
    "    # Compute accuracy for the batch\n",
    "    accuracy_per_label = (preds == labels).float().mean(dim=1)  # Mean per sample\n",
    "    accuracy_batch_mean = accuracy_per_label.mean().item()  # Mean for the batch\n",
    "\n",
    "    accuracy_total += accuracy_batch_mean * len(labels)  # Weighted addition for overall accuracy\n",
    "\n",
    "# Calculate overall accuracy\n",
    "overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
    "print(f\"Overall Accuracy: {overall_accuracy}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv",
   "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.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}