{ "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-10-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-10-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_522464/3938343508.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-10-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.7145567436282411\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 }