{ "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-baseline-20-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%|██████████| 543572/543572 [00:09<00:00, 55944.81 examples/s]\n", "Map (num_proc=32): 100%|██████████| 108714/108714 [00:02<00:00, 41125.11 examples/s]\n", "Map (num_proc=32): 100%|██████████| 72475/72475 [00:02<00:00, 35732.98 examples/s]\n" ] } ], "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 = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-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_531148/2568515560.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-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": [ " 0%| | 0/142 [00:00 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 }