{ "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.scibert import SciBertClassificationModel" ] }, { "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": [ "SciBertClassificationModel(\n", " (base_model): BertModel(\n", " (embeddings): BertEmbeddings(\n", " (word_embeddings): Embedding(31090, 768, padding_idx=0)\n", " (position_embeddings): Embedding(512, 768)\n", " (token_type_embeddings): Embedding(2, 768)\n", " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " (encoder): BertEncoder(\n", " (layer): ModuleList(\n", " (0-11): 12 x BertLayer(\n", " (attention): BertAttention(\n", " (self): BertSdpaSelfAttention(\n", " (query): Linear(in_features=768, out_features=768, bias=True)\n", " (key): Linear(in_features=768, out_features=768, bias=True)\n", " (value): Linear(in_features=768, out_features=768, bias=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " (output): BertSelfOutput(\n", " (dense): Linear(in_features=768, out_features=768, bias=True)\n", " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " )\n", " (intermediate): BertIntermediate(\n", " (dense): Linear(in_features=768, out_features=3072, bias=True)\n", " (intermediate_act_fn): GELUActivation()\n", " )\n", " (output): BertOutput(\n", " (dense): Linear(in_features=3072, out_features=768, bias=True)\n", " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " )\n", " )\n", " )\n", " (pooler): BertPooler(\n", " (dense): Linear(in_features=768, out_features=768, bias=True)\n", " (activation): Tanh()\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 = SciBertClassificationModel(\"ppak10/defect-classification-scibert-baseline-05-epochs\")\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": 4, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Generating train split: 41311472 examples [00:36, 1125978.62 examples/s]\n", "Generating test split: 1739424 examples [00:01, 1126572.80 examples/s]\n", "Generating validation split: 797225 examples [00:00, 1612244.91 examples/s]\n", "Generating train_baseline split: 543572 examples [00:00, 1922772.39 examples/s]\n", "Generating test_baseline split: 108714 examples [00:00, 1808065.15 examples/s]\n", "Generating validation_baseline split: 72475 examples [00:00, 2011155.84 examples/s]\n", "Generating train_prompt split: 40767900 examples [00:34, 1185073.83 examples/s]\n", "Generating test_prompt split: 1630710 examples [00:01, 1136271.75 examples/s]\n", "Generating validation_prompt split: 724750 examples [00:00, 1768766.65 examples/s]\n", "Map (num_proc=64): 100%|██████████| 543572/543572 [00:09<00:00, 55250.96 examples/s]\n", "Map (num_proc=32): 100%|██████████| 108714/108714 [00:02<00:00, 47720.21 examples/s]\n", "Map (num_proc=32): 100%|██████████| 72475/72475 [00:01<00:00, 45154.53 examples/s]\n" ] } ], "source": [ "# Load dataset\n", "dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\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 = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-baseline-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_2733400/1395191505.py:6: 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": [ "SciBertClassificationModel(\n", " (base_model): BertModel(\n", " (embeddings): BertEmbeddings(\n", " (word_embeddings): Embedding(31090, 768, padding_idx=0)\n", " (position_embeddings): Embedding(512, 768)\n", " (token_type_embeddings): Embedding(2, 768)\n", " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " (encoder): BertEncoder(\n", " (layer): ModuleList(\n", " (0-11): 12 x BertLayer(\n", " (attention): BertAttention(\n", " (self): BertSdpaSelfAttention(\n", " (query): Linear(in_features=768, out_features=768, bias=True)\n", " (key): Linear(in_features=768, out_features=768, bias=True)\n", " (value): Linear(in_features=768, out_features=768, bias=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " (output): BertSelfOutput(\n", " (dense): Linear(in_features=768, out_features=768, bias=True)\n", " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " )\n", " (intermediate): BertIntermediate(\n", " (dense): Linear(in_features=768, out_features=3072, bias=True)\n", " (intermediate_act_fn): GELUActivation()\n", " )\n", " (output): BertOutput(\n", " (dense): Linear(in_features=3072, out_features=768, bias=True)\n", " (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n", " (dropout): Dropout(p=0.1, inplace=False)\n", " )\n", " )\n", " )\n", " )\n", " (pooler): BertPooler(\n", " (dense): Linear(in_features=768, out_features=768, bias=True)\n", " (activation): Tanh()\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-scibert-baseline-05-epochs\",\n", " repo_type=\"model\",\n", " filename=\"classification_head.pt\"\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 [08:58<00:00, 3.79s/it]\n" ] } ], "source": [ "# Ensure the model is on the GPU\n", "device = torch.device(\"cuda:1\" 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_kwargs = {}\n", "\n", " for key, value in inputs.items():\n", " if key not in [\"token_type_ids\"]:\n", " inputs_kwargs[key] = value.to(device)\n", "\n", " # print(inputs_kwargs)\n", " # inputs = {key: value.to(device) for key, value in inputs.items()}\n", "\n", " # Perform inference\n", " outputs = model(**inputs_kwargs)\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)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overall Accuracy: 0.8829734390404521\n" ] } ], "source": [ "print(f\"Overall Accuracy: {overall_accuracy}\")" ] } ], "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 }