Spaces:
Sleeping
Sleeping
File size: 16,173 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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
{
"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 T5Tokenizer \n",
"from tqdm import tqdm\n",
"\n",
"from model.t5 import T5ClassificationModel"
]
},
{
"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": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/ppak/GitHub/LLM-Enabled-Process-Map/model/t5.py:28: 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",
" state_dict = torch.load(pytorch_model_path)\n"
]
},
{
"data": {
"text/plain": [
"T5ClassificationModel(\n",
" (base_model): T5EncoderModel(\n",
" (shared): Embedding(32128, 512)\n",
" (encoder): T5Stack(\n",
" (embed_tokens): Embedding(32128, 512)\n",
" (block): ModuleList(\n",
" (0): T5Block(\n",
" (layer): ModuleList(\n",
" (0): T5LayerSelfAttention(\n",
" (SelfAttention): T5Attention(\n",
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
" (relative_attention_bias): Embedding(32, 8)\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" (1): T5LayerFF(\n",
" (DenseReluDense): T5DenseActDense(\n",
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" (act): ReLU()\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" )\n",
" )\n",
" (1-5): 5 x T5Block(\n",
" (layer): ModuleList(\n",
" (0): T5LayerSelfAttention(\n",
" (SelfAttention): T5Attention(\n",
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" (1): T5LayerFF(\n",
" (DenseReluDense): T5DenseActDense(\n",
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" (act): ReLU()\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" )\n",
" )\n",
" )\n",
" (final_layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" )\n",
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
")"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Initialize the model\n",
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-baseline-20-epochs\")\n",
"model.eval() # Set the model to evaluation mode"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"# Load dataset\n",
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
"train_dataset = dataset[\"train_baseline\"]\n",
"test_dataset = dataset[\"test_baseline\"]\n",
"validation_dataset = dataset[\"validation_baseline\"]\n",
"\n",
"# Load the tokenizer\n",
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-baseline-20-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_515237/2661568338.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": [
"T5ClassificationModel(\n",
" (base_model): T5EncoderModel(\n",
" (shared): Embedding(32128, 512)\n",
" (encoder): T5Stack(\n",
" (embed_tokens): Embedding(32128, 512)\n",
" (block): ModuleList(\n",
" (0): T5Block(\n",
" (layer): ModuleList(\n",
" (0): T5LayerSelfAttention(\n",
" (SelfAttention): T5Attention(\n",
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
" (relative_attention_bias): Embedding(32, 8)\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" (1): T5LayerFF(\n",
" (DenseReluDense): T5DenseActDense(\n",
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" (act): ReLU()\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" )\n",
" )\n",
" (1-5): 5 x T5Block(\n",
" (layer): ModuleList(\n",
" (0): T5LayerSelfAttention(\n",
" (SelfAttention): T5Attention(\n",
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" (1): T5LayerFF(\n",
" (DenseReluDense): T5DenseActDense(\n",
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" (act): ReLU()\n",
" )\n",
" (layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" )\n",
" )\n",
" )\n",
" (final_layer_norm): T5LayerNorm()\n",
" (dropout): Dropout(p=0.1, inplace=False)\n",
" )\n",
" )\n",
" (classifier): Linear(in_features=512, 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-t5-baseline-20-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%|ββββββββββ| 142/142 [02:06<00:00, 1.12it/s]"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overall Accuracy: 0.7792997584609419\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",
"\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
}
|