Spaces:
Sleeping
Sleeping
Adds notebooks.
Browse files- .gitignore +2 -0
- notebooks/distilbert_baseline_05_epochs.ipynb +334 -0
- notebooks/distilbert_baseline_10_epochs.ipynb +334 -0
- notebooks/distilbert_baseline_15_epochs.ipynb +334 -0
- notebooks/distilbert_baseline_20_epochs.ipynb +341 -0
- notebooks/distilbert_baseline_20_epochs_prompt_input.ipynb +343 -0
- notebooks/distilbert_baseline_25_epochs.ipynb +334 -0
- notebooks/distilbert_prompt_02_epochs.ipynb +324 -0
- notebooks/distilbert_prompt_05_epochs.ipynb +334 -0
- notebooks/inference.ipynb +313 -0
- notebooks/llama_baseline_05_epochs.ipynb +309 -0
- notebooks/llama_baseline_10_epochs.ipynb +309 -0
- notebooks/llama_baseline_15_epochs.ipynb +309 -0
- notebooks/llama_baseline_20_epochs.ipynb +309 -0
- notebooks/llama_baseline_20_epochs_prompt_input.ipynb +299 -0
- notebooks/llama_baseline_25_epochs.ipynb +318 -0
- notebooks/llama_prompt_0.5_epochs.ipynb +299 -0
- notebooks/scibert_baseline_05_epochs.ipynb +369 -0
- notebooks/scibert_baseline_10_epochs.ipynb +350 -0
- notebooks/scibert_baseline_15_epochs.ipynb +360 -0
- notebooks/scibert_baseline_20_epochs.ipynb +350 -0
- notebooks/scibert_baseline_20_epochs_prompt_input.ipynb +369 -0
- notebooks/scibert_baseline_25_epochs.ipynb +360 -0
- notebooks/scibert_prompt_02_epochs.ipynb +360 -0
- notebooks/scibert_prompt_05_epochs.ipynb +360 -0
- notebooks/t5_baseline_05_epochs.ipynb +401 -0
- notebooks/t5_baseline_10_epochs.ipynb +391 -0
- notebooks/t5_baseline_15_epochs.ipynb +391 -0
- notebooks/t5_baseline_20_epochs.ipynb +391 -0
- notebooks/t5_baseline_20_epochs_prompt_input.ipynb +401 -0
- notebooks/t5_baseline_25_epochs.ipynb +401 -0
- notebooks/t5_prompt_02_epochs.ipynb +401 -0
- notebooks/t5_prompt_05_epochs.ipynb +401 -0
- start_server.sh +1 -1
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
venv
|
2 |
+
.ipynb_checkpoints
|
notebooks/distilbert_baseline_05_epochs.ipynb
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-baseline-05-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"name": "stderr",
|
117 |
+
"output_type": "stream",
|
118 |
+
"text": [
|
119 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:10<00:00, 54345.11 examples/s]\n",
|
120 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 38478.52 examples/s]\n",
|
121 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 32866.00 examples/s]\n"
|
122 |
+
]
|
123 |
+
}
|
124 |
+
],
|
125 |
+
"source": [
|
126 |
+
"# Load dataset\n",
|
127 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
128 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
129 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
130 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
131 |
+
"\n",
|
132 |
+
"# Load the tokenizer\n",
|
133 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-baseline-05-epochs\")\n",
|
134 |
+
"\n",
|
135 |
+
"# Preprocessing function\n",
|
136 |
+
"def preprocess_function(examples):\n",
|
137 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
138 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
139 |
+
" return tokenizer(\n",
|
140 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
141 |
+
" )\n",
|
142 |
+
"\n",
|
143 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
144 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
145 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "markdown",
|
150 |
+
"metadata": {},
|
151 |
+
"source": [
|
152 |
+
"# With Pretrained Weights"
|
153 |
+
]
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"cell_type": "code",
|
157 |
+
"execution_count": 5,
|
158 |
+
"metadata": {},
|
159 |
+
"outputs": [
|
160 |
+
{
|
161 |
+
"name": "stderr",
|
162 |
+
"output_type": "stream",
|
163 |
+
"text": [
|
164 |
+
"/tmp/ipykernel_1112379/2541613902.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",
|
165 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
166 |
+
]
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"data": {
|
170 |
+
"text/plain": [
|
171 |
+
"DistilBertClassificationModel(\n",
|
172 |
+
" (base_model): DistilBertModel(\n",
|
173 |
+
" (embeddings): Embeddings(\n",
|
174 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
175 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
176 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
177 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
178 |
+
" )\n",
|
179 |
+
" (transformer): Transformer(\n",
|
180 |
+
" (layer): ModuleList(\n",
|
181 |
+
" (0-5): 6 x TransformerBlock(\n",
|
182 |
+
" (attention): DistilBertSdpaAttention(\n",
|
183 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
184 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
185 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
186 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
187 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
188 |
+
" )\n",
|
189 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
190 |
+
" (ffn): FFN(\n",
|
191 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
192 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
193 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
194 |
+
" (activation): GELUActivation()\n",
|
195 |
+
" )\n",
|
196 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" )\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" )\n",
|
201 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
202 |
+
")"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
"execution_count": 5,
|
206 |
+
"metadata": {},
|
207 |
+
"output_type": "execute_result"
|
208 |
+
}
|
209 |
+
],
|
210 |
+
"source": [
|
211 |
+
"classification_head_path = hf_hub_download(\n",
|
212 |
+
" repo_id=\"ppak10/defect-classification-distilbert-baseline-05-epochs\",\n",
|
213 |
+
" repo_type=\"model\",\n",
|
214 |
+
" filename=\"classification_head.pt\"\n",
|
215 |
+
")\n",
|
216 |
+
"\n",
|
217 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
218 |
+
"model.eval() # Set the model to evaluation mode"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
{
|
222 |
+
"cell_type": "code",
|
223 |
+
"execution_count": 6,
|
224 |
+
"metadata": {},
|
225 |
+
"outputs": [
|
226 |
+
{
|
227 |
+
"name": "stderr",
|
228 |
+
"output_type": "stream",
|
229 |
+
"text": [
|
230 |
+
"100%|ββββββββββ| 142/142 [03:17<00:00, 1.39s/it]"
|
231 |
+
]
|
232 |
+
},
|
233 |
+
{
|
234 |
+
"name": "stdout",
|
235 |
+
"output_type": "stream",
|
236 |
+
"text": [
|
237 |
+
"Overall Accuracy: 0.8422800965085446\n"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"name": "stderr",
|
242 |
+
"output_type": "stream",
|
243 |
+
"text": [
|
244 |
+
"\n"
|
245 |
+
]
|
246 |
+
}
|
247 |
+
],
|
248 |
+
"source": [
|
249 |
+
"# Ensure the model is on the GPU\n",
|
250 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
251 |
+
"model = model.to(device)\n",
|
252 |
+
"\n",
|
253 |
+
"# Define the batch size\n",
|
254 |
+
"batch_size = 512\n",
|
255 |
+
"\n",
|
256 |
+
"# Create a DataLoader for the validation dataset\n",
|
257 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
258 |
+
"\n",
|
259 |
+
"def label_to_classifications_batch(labels):\n",
|
260 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
261 |
+
" \n",
|
262 |
+
" results = []\n",
|
263 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
264 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
265 |
+
" results.append(result)\n",
|
266 |
+
" return results\n",
|
267 |
+
"\n",
|
268 |
+
"accuracy_total = 0\n",
|
269 |
+
"\n",
|
270 |
+
"# Process the validation dataset in batches\n",
|
271 |
+
"for batch in tqdm(validation_loader):\n",
|
272 |
+
" texts = batch[\"text\"]\n",
|
273 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
274 |
+
"\n",
|
275 |
+
" # Move labels to GPU\n",
|
276 |
+
" # print(np.array(labels))\n",
|
277 |
+
" labels = torch.tensor(labels).to(device)\n",
|
278 |
+
"\n",
|
279 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
280 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
281 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
282 |
+
"\n",
|
283 |
+
" # Perform inference\n",
|
284 |
+
" outputs = model(**inputs)\n",
|
285 |
+
"\n",
|
286 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
287 |
+
" logits = outputs[\"logits\"]\n",
|
288 |
+
" probs = torch.sigmoid(logits)\n",
|
289 |
+
"\n",
|
290 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
291 |
+
" preds = (probs > 0.5).int()\n",
|
292 |
+
" # print(preds)\n",
|
293 |
+
"\n",
|
294 |
+
" # Compute accuracy for the batch\n",
|
295 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
296 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
297 |
+
"\n",
|
298 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
299 |
+
"\n",
|
300 |
+
"# Calculate overall accuracy\n",
|
301 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
302 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
303 |
+
]
|
304 |
+
},
|
305 |
+
{
|
306 |
+
"cell_type": "code",
|
307 |
+
"execution_count": null,
|
308 |
+
"metadata": {},
|
309 |
+
"outputs": [],
|
310 |
+
"source": []
|
311 |
+
}
|
312 |
+
],
|
313 |
+
"metadata": {
|
314 |
+
"kernelspec": {
|
315 |
+
"display_name": "venv",
|
316 |
+
"language": "python",
|
317 |
+
"name": "python3"
|
318 |
+
},
|
319 |
+
"language_info": {
|
320 |
+
"codemirror_mode": {
|
321 |
+
"name": "ipython",
|
322 |
+
"version": 3
|
323 |
+
},
|
324 |
+
"file_extension": ".py",
|
325 |
+
"mimetype": "text/x-python",
|
326 |
+
"name": "python",
|
327 |
+
"nbconvert_exporter": "python",
|
328 |
+
"pygments_lexer": "ipython3",
|
329 |
+
"version": "3.10.12"
|
330 |
+
}
|
331 |
+
},
|
332 |
+
"nbformat": 4,
|
333 |
+
"nbformat_minor": 2
|
334 |
+
}
|
notebooks/distilbert_baseline_10_epochs.ipynb
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-baseline-10-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"name": "stderr",
|
117 |
+
"output_type": "stream",
|
118 |
+
"text": [
|
119 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:10<00:00, 52366.16 examples/s]\n",
|
120 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 42168.27 examples/s]\n",
|
121 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:01<00:00, 46148.39 examples/s]\n"
|
122 |
+
]
|
123 |
+
}
|
124 |
+
],
|
125 |
+
"source": [
|
126 |
+
"# Load dataset\n",
|
127 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
128 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
129 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
130 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
131 |
+
"\n",
|
132 |
+
"# Load the tokenizer\n",
|
133 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-baseline-10-epochs\")\n",
|
134 |
+
"\n",
|
135 |
+
"# Preprocessing function\n",
|
136 |
+
"def preprocess_function(examples):\n",
|
137 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
138 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
139 |
+
" return tokenizer(\n",
|
140 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
141 |
+
" )\n",
|
142 |
+
"\n",
|
143 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
144 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
145 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "markdown",
|
150 |
+
"metadata": {},
|
151 |
+
"source": [
|
152 |
+
"# With Pretrained Weights"
|
153 |
+
]
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"cell_type": "code",
|
157 |
+
"execution_count": 5,
|
158 |
+
"metadata": {},
|
159 |
+
"outputs": [
|
160 |
+
{
|
161 |
+
"name": "stderr",
|
162 |
+
"output_type": "stream",
|
163 |
+
"text": [
|
164 |
+
"/tmp/ipykernel_2733781/3735578472.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",
|
165 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
166 |
+
]
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"data": {
|
170 |
+
"text/plain": [
|
171 |
+
"DistilBertClassificationModel(\n",
|
172 |
+
" (base_model): DistilBertModel(\n",
|
173 |
+
" (embeddings): Embeddings(\n",
|
174 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
175 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
176 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
177 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
178 |
+
" )\n",
|
179 |
+
" (transformer): Transformer(\n",
|
180 |
+
" (layer): ModuleList(\n",
|
181 |
+
" (0-5): 6 x TransformerBlock(\n",
|
182 |
+
" (attention): DistilBertSdpaAttention(\n",
|
183 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
184 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
185 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
186 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
187 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
188 |
+
" )\n",
|
189 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
190 |
+
" (ffn): FFN(\n",
|
191 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
192 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
193 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
194 |
+
" (activation): GELUActivation()\n",
|
195 |
+
" )\n",
|
196 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" )\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" )\n",
|
201 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
202 |
+
")"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
"execution_count": 5,
|
206 |
+
"metadata": {},
|
207 |
+
"output_type": "execute_result"
|
208 |
+
}
|
209 |
+
],
|
210 |
+
"source": [
|
211 |
+
"classification_head_path = hf_hub_download(\n",
|
212 |
+
" repo_id=\"ppak10/defect-classification-distilbert-baseline-10-epochs\",\n",
|
213 |
+
" repo_type=\"model\",\n",
|
214 |
+
" filename=\"classification_head.pt\"\n",
|
215 |
+
")\n",
|
216 |
+
"\n",
|
217 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
218 |
+
"model.eval() # Set the model to evaluation mode"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
{
|
222 |
+
"cell_type": "code",
|
223 |
+
"execution_count": 6,
|
224 |
+
"metadata": {},
|
225 |
+
"outputs": [
|
226 |
+
{
|
227 |
+
"name": "stderr",
|
228 |
+
"output_type": "stream",
|
229 |
+
"text": [
|
230 |
+
"100%|ββββββββββ| 142/142 [03:25<00:00, 1.45s/it]"
|
231 |
+
]
|
232 |
+
},
|
233 |
+
{
|
234 |
+
"name": "stdout",
|
235 |
+
"output_type": "stream",
|
236 |
+
"text": [
|
237 |
+
"Overall Accuracy: 0.8775370817399921\n"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"name": "stderr",
|
242 |
+
"output_type": "stream",
|
243 |
+
"text": [
|
244 |
+
"\n"
|
245 |
+
]
|
246 |
+
}
|
247 |
+
],
|
248 |
+
"source": [
|
249 |
+
"# Ensure the model is on the GPU\n",
|
250 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
251 |
+
"model = model.to(device)\n",
|
252 |
+
"\n",
|
253 |
+
"# Define the batch size\n",
|
254 |
+
"batch_size = 512\n",
|
255 |
+
"\n",
|
256 |
+
"# Create a DataLoader for the validation dataset\n",
|
257 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
258 |
+
"\n",
|
259 |
+
"def label_to_classifications_batch(labels):\n",
|
260 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
261 |
+
" \n",
|
262 |
+
" results = []\n",
|
263 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
264 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
265 |
+
" results.append(result)\n",
|
266 |
+
" return results\n",
|
267 |
+
"\n",
|
268 |
+
"accuracy_total = 0\n",
|
269 |
+
"\n",
|
270 |
+
"# Process the validation dataset in batches\n",
|
271 |
+
"for batch in tqdm(validation_loader):\n",
|
272 |
+
" texts = batch[\"text\"]\n",
|
273 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
274 |
+
"\n",
|
275 |
+
" # Move labels to GPU\n",
|
276 |
+
" # print(np.array(labels))\n",
|
277 |
+
" labels = torch.tensor(labels).to(device)\n",
|
278 |
+
"\n",
|
279 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
280 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
281 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
282 |
+
"\n",
|
283 |
+
" # Perform inference\n",
|
284 |
+
" outputs = model(**inputs)\n",
|
285 |
+
"\n",
|
286 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
287 |
+
" logits = outputs[\"logits\"]\n",
|
288 |
+
" probs = torch.sigmoid(logits)\n",
|
289 |
+
"\n",
|
290 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
291 |
+
" preds = (probs > 0.5).int()\n",
|
292 |
+
" # print(preds)\n",
|
293 |
+
"\n",
|
294 |
+
" # Compute accuracy for the batch\n",
|
295 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
296 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
297 |
+
"\n",
|
298 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
299 |
+
"\n",
|
300 |
+
"# Calculate overall accuracy\n",
|
301 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
302 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
303 |
+
]
|
304 |
+
},
|
305 |
+
{
|
306 |
+
"cell_type": "code",
|
307 |
+
"execution_count": null,
|
308 |
+
"metadata": {},
|
309 |
+
"outputs": [],
|
310 |
+
"source": []
|
311 |
+
}
|
312 |
+
],
|
313 |
+
"metadata": {
|
314 |
+
"kernelspec": {
|
315 |
+
"display_name": "venv",
|
316 |
+
"language": "python",
|
317 |
+
"name": "python3"
|
318 |
+
},
|
319 |
+
"language_info": {
|
320 |
+
"codemirror_mode": {
|
321 |
+
"name": "ipython",
|
322 |
+
"version": 3
|
323 |
+
},
|
324 |
+
"file_extension": ".py",
|
325 |
+
"mimetype": "text/x-python",
|
326 |
+
"name": "python",
|
327 |
+
"nbconvert_exporter": "python",
|
328 |
+
"pygments_lexer": "ipython3",
|
329 |
+
"version": "3.10.12"
|
330 |
+
}
|
331 |
+
},
|
332 |
+
"nbformat": 4,
|
333 |
+
"nbformat_minor": 2
|
334 |
+
}
|
notebooks/distilbert_baseline_15_epochs.ipynb
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-baseline-15-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"name": "stderr",
|
117 |
+
"output_type": "stream",
|
118 |
+
"text": [
|
119 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:09<00:00, 56690.65 examples/s]\n",
|
120 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 36963.03 examples/s]\n",
|
121 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 31451.64 examples/s]\n"
|
122 |
+
]
|
123 |
+
}
|
124 |
+
],
|
125 |
+
"source": [
|
126 |
+
"# Load dataset\n",
|
127 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
128 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
129 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
130 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
131 |
+
"\n",
|
132 |
+
"# Load the tokenizer\n",
|
133 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-baseline-15-epochs\")\n",
|
134 |
+
"\n",
|
135 |
+
"# Preprocessing function\n",
|
136 |
+
"def preprocess_function(examples):\n",
|
137 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
138 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
139 |
+
" return tokenizer(\n",
|
140 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
141 |
+
" )\n",
|
142 |
+
"\n",
|
143 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
144 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
145 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "markdown",
|
150 |
+
"metadata": {},
|
151 |
+
"source": [
|
152 |
+
"# With Pretrained Weights"
|
153 |
+
]
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"cell_type": "code",
|
157 |
+
"execution_count": 5,
|
158 |
+
"metadata": {},
|
159 |
+
"outputs": [
|
160 |
+
{
|
161 |
+
"name": "stderr",
|
162 |
+
"output_type": "stream",
|
163 |
+
"text": [
|
164 |
+
"/tmp/ipykernel_524144/593626310.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",
|
165 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
166 |
+
]
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"data": {
|
170 |
+
"text/plain": [
|
171 |
+
"DistilBertClassificationModel(\n",
|
172 |
+
" (base_model): DistilBertModel(\n",
|
173 |
+
" (embeddings): Embeddings(\n",
|
174 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
175 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
176 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
177 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
178 |
+
" )\n",
|
179 |
+
" (transformer): Transformer(\n",
|
180 |
+
" (layer): ModuleList(\n",
|
181 |
+
" (0-5): 6 x TransformerBlock(\n",
|
182 |
+
" (attention): DistilBertSdpaAttention(\n",
|
183 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
184 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
185 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
186 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
187 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
188 |
+
" )\n",
|
189 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
190 |
+
" (ffn): FFN(\n",
|
191 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
192 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
193 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
194 |
+
" (activation): GELUActivation()\n",
|
195 |
+
" )\n",
|
196 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" )\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" )\n",
|
201 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
202 |
+
")"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
"execution_count": 5,
|
206 |
+
"metadata": {},
|
207 |
+
"output_type": "execute_result"
|
208 |
+
}
|
209 |
+
],
|
210 |
+
"source": [
|
211 |
+
"classification_head_path = hf_hub_download(\n",
|
212 |
+
" repo_id=\"ppak10/defect-classification-distilbert-baseline-15-epochs\",\n",
|
213 |
+
" repo_type=\"model\",\n",
|
214 |
+
" filename=\"classification_head.pt\"\n",
|
215 |
+
")\n",
|
216 |
+
"\n",
|
217 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
218 |
+
"model.eval() # Set the model to evaluation mode"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
{
|
222 |
+
"cell_type": "code",
|
223 |
+
"execution_count": 7,
|
224 |
+
"metadata": {},
|
225 |
+
"outputs": [
|
226 |
+
{
|
227 |
+
"name": "stderr",
|
228 |
+
"output_type": "stream",
|
229 |
+
"text": [
|
230 |
+
"100%|ββββββββββ| 142/142 [03:13<00:00, 1.36s/it]"
|
231 |
+
]
|
232 |
+
},
|
233 |
+
{
|
234 |
+
"name": "stdout",
|
235 |
+
"output_type": "stream",
|
236 |
+
"text": [
|
237 |
+
"Overall Accuracy: 0.8775370818765132\n"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"name": "stderr",
|
242 |
+
"output_type": "stream",
|
243 |
+
"text": [
|
244 |
+
"\n"
|
245 |
+
]
|
246 |
+
}
|
247 |
+
],
|
248 |
+
"source": [
|
249 |
+
"# Ensure the model is on the GPU\n",
|
250 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
251 |
+
"model = model.to(device)\n",
|
252 |
+
"\n",
|
253 |
+
"# Define the batch size\n",
|
254 |
+
"batch_size = 512\n",
|
255 |
+
"\n",
|
256 |
+
"# Create a DataLoader for the validation dataset\n",
|
257 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
258 |
+
"\n",
|
259 |
+
"def label_to_classifications_batch(labels):\n",
|
260 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
261 |
+
" \n",
|
262 |
+
" results = []\n",
|
263 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
264 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
265 |
+
" results.append(result)\n",
|
266 |
+
" return results\n",
|
267 |
+
"\n",
|
268 |
+
"accuracy_total = 0\n",
|
269 |
+
"\n",
|
270 |
+
"# Process the validation dataset in batches\n",
|
271 |
+
"for batch in tqdm(validation_loader):\n",
|
272 |
+
" texts = batch[\"text\"]\n",
|
273 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
274 |
+
"\n",
|
275 |
+
" # Move labels to GPU\n",
|
276 |
+
" # print(np.array(labels))\n",
|
277 |
+
" labels = torch.tensor(labels).to(device)\n",
|
278 |
+
"\n",
|
279 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
280 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
281 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
282 |
+
"\n",
|
283 |
+
" # Perform inference\n",
|
284 |
+
" outputs = model(**inputs)\n",
|
285 |
+
"\n",
|
286 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
287 |
+
" logits = outputs[\"logits\"]\n",
|
288 |
+
" probs = torch.sigmoid(logits)\n",
|
289 |
+
"\n",
|
290 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
291 |
+
" preds = (probs > 0.5).int()\n",
|
292 |
+
" # print(preds)\n",
|
293 |
+
"\n",
|
294 |
+
" # Compute accuracy for the batch\n",
|
295 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
296 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
297 |
+
"\n",
|
298 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
299 |
+
"\n",
|
300 |
+
"# Calculate overall accuracy\n",
|
301 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
302 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
303 |
+
]
|
304 |
+
},
|
305 |
+
{
|
306 |
+
"cell_type": "code",
|
307 |
+
"execution_count": null,
|
308 |
+
"metadata": {},
|
309 |
+
"outputs": [],
|
310 |
+
"source": []
|
311 |
+
}
|
312 |
+
],
|
313 |
+
"metadata": {
|
314 |
+
"kernelspec": {
|
315 |
+
"display_name": "venv",
|
316 |
+
"language": "python",
|
317 |
+
"name": "python3"
|
318 |
+
},
|
319 |
+
"language_info": {
|
320 |
+
"codemirror_mode": {
|
321 |
+
"name": "ipython",
|
322 |
+
"version": 3
|
323 |
+
},
|
324 |
+
"file_extension": ".py",
|
325 |
+
"mimetype": "text/x-python",
|
326 |
+
"name": "python",
|
327 |
+
"nbconvert_exporter": "python",
|
328 |
+
"pygments_lexer": "ipython3",
|
329 |
+
"version": "3.10.12"
|
330 |
+
}
|
331 |
+
},
|
332 |
+
"nbformat": 4,
|
333 |
+
"nbformat_minor": 2
|
334 |
+
}
|
notebooks/distilbert_baseline_20_epochs.ipynb
ADDED
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-baseline-20-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"name": "stderr",
|
117 |
+
"output_type": "stream",
|
118 |
+
"text": [
|
119 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:09<00:00, 55944.81 examples/s]\n",
|
120 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 41125.11 examples/s]\n",
|
121 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 35732.98 examples/s]\n"
|
122 |
+
]
|
123 |
+
}
|
124 |
+
],
|
125 |
+
"source": [
|
126 |
+
"# Load dataset\n",
|
127 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
128 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
129 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
130 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
131 |
+
"\n",
|
132 |
+
"# Load the tokenizer\n",
|
133 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-baseline-20-epochs\")\n",
|
134 |
+
"\n",
|
135 |
+
"# Preprocessing function\n",
|
136 |
+
"def preprocess_function(examples):\n",
|
137 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
138 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
139 |
+
" return tokenizer(\n",
|
140 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
141 |
+
" )\n",
|
142 |
+
"\n",
|
143 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
144 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
145 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "markdown",
|
150 |
+
"metadata": {},
|
151 |
+
"source": [
|
152 |
+
"# With Pretrained Weights"
|
153 |
+
]
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"cell_type": "code",
|
157 |
+
"execution_count": 5,
|
158 |
+
"metadata": {},
|
159 |
+
"outputs": [
|
160 |
+
{
|
161 |
+
"name": "stderr",
|
162 |
+
"output_type": "stream",
|
163 |
+
"text": [
|
164 |
+
"/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",
|
165 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
166 |
+
]
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"data": {
|
170 |
+
"text/plain": [
|
171 |
+
"DistilBertClassificationModel(\n",
|
172 |
+
" (base_model): DistilBertModel(\n",
|
173 |
+
" (embeddings): Embeddings(\n",
|
174 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
175 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
176 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
177 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
178 |
+
" )\n",
|
179 |
+
" (transformer): Transformer(\n",
|
180 |
+
" (layer): ModuleList(\n",
|
181 |
+
" (0-5): 6 x TransformerBlock(\n",
|
182 |
+
" (attention): DistilBertSdpaAttention(\n",
|
183 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
184 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
185 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
186 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
187 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
188 |
+
" )\n",
|
189 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
190 |
+
" (ffn): FFN(\n",
|
191 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
192 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
193 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
194 |
+
" (activation): GELUActivation()\n",
|
195 |
+
" )\n",
|
196 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" )\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" )\n",
|
201 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
202 |
+
")"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
"execution_count": 5,
|
206 |
+
"metadata": {},
|
207 |
+
"output_type": "execute_result"
|
208 |
+
}
|
209 |
+
],
|
210 |
+
"source": [
|
211 |
+
"classification_head_path = hf_hub_download(\n",
|
212 |
+
" repo_id=\"ppak10/defect-classification-distilbert-baseline-20-epochs\",\n",
|
213 |
+
" repo_type=\"model\",\n",
|
214 |
+
" filename=\"classification_head.pt\"\n",
|
215 |
+
")\n",
|
216 |
+
"\n",
|
217 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
218 |
+
"model.eval() # Set the model to evaluation mode"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
{
|
222 |
+
"cell_type": "code",
|
223 |
+
"execution_count": 6,
|
224 |
+
"metadata": {},
|
225 |
+
"outputs": [
|
226 |
+
{
|
227 |
+
"name": "stderr",
|
228 |
+
"output_type": "stream",
|
229 |
+
"text": [
|
230 |
+
" 0%| | 0/142 [00:00<?, ?it/s]"
|
231 |
+
]
|
232 |
+
},
|
233 |
+
{
|
234 |
+
"name": "stderr",
|
235 |
+
"output_type": "stream",
|
236 |
+
"text": [
|
237 |
+
"100%|ββββββββββ| 142/142 [03:13<00:00, 1.36s/it]"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"name": "stdout",
|
242 |
+
"output_type": "stream",
|
243 |
+
"text": [
|
244 |
+
"Overall Accuracy: 0.8829423940531259\n"
|
245 |
+
]
|
246 |
+
},
|
247 |
+
{
|
248 |
+
"name": "stderr",
|
249 |
+
"output_type": "stream",
|
250 |
+
"text": [
|
251 |
+
"\n"
|
252 |
+
]
|
253 |
+
}
|
254 |
+
],
|
255 |
+
"source": [
|
256 |
+
"# Ensure the model is on the GPU\n",
|
257 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
258 |
+
"model = model.to(device)\n",
|
259 |
+
"\n",
|
260 |
+
"# Define the batch size\n",
|
261 |
+
"batch_size = 512\n",
|
262 |
+
"\n",
|
263 |
+
"# Create a DataLoader for the validation dataset\n",
|
264 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
265 |
+
"\n",
|
266 |
+
"def label_to_classifications_batch(labels):\n",
|
267 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
268 |
+
" \n",
|
269 |
+
" results = []\n",
|
270 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
271 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
272 |
+
" results.append(result)\n",
|
273 |
+
" return results\n",
|
274 |
+
"\n",
|
275 |
+
"accuracy_total = 0\n",
|
276 |
+
"\n",
|
277 |
+
"# Process the validation dataset in batches\n",
|
278 |
+
"for batch in tqdm(validation_loader):\n",
|
279 |
+
" texts = batch[\"text\"]\n",
|
280 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
281 |
+
"\n",
|
282 |
+
" # Move labels to GPU\n",
|
283 |
+
" # print(np.array(labels))\n",
|
284 |
+
" labels = torch.tensor(labels).to(device)\n",
|
285 |
+
"\n",
|
286 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
287 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
288 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
289 |
+
"\n",
|
290 |
+
" # Perform inference\n",
|
291 |
+
" outputs = model(**inputs)\n",
|
292 |
+
"\n",
|
293 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
294 |
+
" logits = outputs[\"logits\"]\n",
|
295 |
+
" probs = torch.sigmoid(logits)\n",
|
296 |
+
"\n",
|
297 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
298 |
+
" preds = (probs > 0.5).int()\n",
|
299 |
+
" # print(preds)\n",
|
300 |
+
"\n",
|
301 |
+
" # Compute accuracy for the batch\n",
|
302 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
303 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
304 |
+
"\n",
|
305 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
306 |
+
"\n",
|
307 |
+
"# Calculate overall accuracy\n",
|
308 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
309 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
310 |
+
]
|
311 |
+
},
|
312 |
+
{
|
313 |
+
"cell_type": "code",
|
314 |
+
"execution_count": null,
|
315 |
+
"metadata": {},
|
316 |
+
"outputs": [],
|
317 |
+
"source": []
|
318 |
+
}
|
319 |
+
],
|
320 |
+
"metadata": {
|
321 |
+
"kernelspec": {
|
322 |
+
"display_name": "venv",
|
323 |
+
"language": "python",
|
324 |
+
"name": "python3"
|
325 |
+
},
|
326 |
+
"language_info": {
|
327 |
+
"codemirror_mode": {
|
328 |
+
"name": "ipython",
|
329 |
+
"version": 3
|
330 |
+
},
|
331 |
+
"file_extension": ".py",
|
332 |
+
"mimetype": "text/x-python",
|
333 |
+
"name": "python",
|
334 |
+
"nbconvert_exporter": "python",
|
335 |
+
"pygments_lexer": "ipython3",
|
336 |
+
"version": "3.10.12"
|
337 |
+
}
|
338 |
+
},
|
339 |
+
"nbformat": 4,
|
340 |
+
"nbformat_minor": 2
|
341 |
+
}
|
notebooks/distilbert_baseline_20_epochs_prompt_input.ipynb
ADDED
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-baseline-20-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"name": "stderr",
|
117 |
+
"output_type": "stream",
|
118 |
+
"text": [
|
119 |
+
"Generating train split: 41311472 examples [00:15, 2748350.87 examples/s]\n",
|
120 |
+
"Generating test split: 1739424 examples [00:00, 3490834.49 examples/s]\n",
|
121 |
+
"Generating validation split: 797225 examples [00:00, 3742202.64 examples/s]\n",
|
122 |
+
"Generating train_baseline split: 543572 examples [00:00, 5029940.88 examples/s]\n",
|
123 |
+
"Generating test_baseline split: 108714 examples [00:00, 4718282.77 examples/s]\n",
|
124 |
+
"Generating validation_baseline split: 72475 examples [00:00, 4652527.39 examples/s]\n",
|
125 |
+
"Generating train_prompt split: 40767900 examples [00:12, 3245830.79 examples/s]\n",
|
126 |
+
"Generating test_prompt split: 1630710 examples [00:00, 3315906.34 examples/s]\n",
|
127 |
+
"Generating validation_prompt split: 724750 examples [00:00, 3754920.07 examples/s]\n",
|
128 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [08:33<00:00, 79453.36 examples/s] \n",
|
129 |
+
"Map (num_proc=32): 100%|ββοΏ½οΏ½οΏ½βββββββ| 1630710/1630710 [00:53<00:00, 30227.79 examples/s]\n",
|
130 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:21<00:00, 33218.85 examples/s]\n"
|
131 |
+
]
|
132 |
+
}
|
133 |
+
],
|
134 |
+
"source": [
|
135 |
+
"# Load dataset\n",
|
136 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
137 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
138 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
139 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
140 |
+
"\n",
|
141 |
+
"# Load the tokenizer\n",
|
142 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-baseline-20-epochs\")\n",
|
143 |
+
"\n",
|
144 |
+
"# Preprocessing function\n",
|
145 |
+
"def preprocess_function(examples):\n",
|
146 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
147 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
148 |
+
" return tokenizer(\n",
|
149 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
150 |
+
" )\n",
|
151 |
+
"\n",
|
152 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
153 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
154 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
155 |
+
]
|
156 |
+
},
|
157 |
+
{
|
158 |
+
"cell_type": "markdown",
|
159 |
+
"metadata": {},
|
160 |
+
"source": [
|
161 |
+
"# With Pretrained Weights"
|
162 |
+
]
|
163 |
+
},
|
164 |
+
{
|
165 |
+
"cell_type": "code",
|
166 |
+
"execution_count": 5,
|
167 |
+
"metadata": {},
|
168 |
+
"outputs": [
|
169 |
+
{
|
170 |
+
"name": "stderr",
|
171 |
+
"output_type": "stream",
|
172 |
+
"text": [
|
173 |
+
"/tmp/ipykernel_1920285/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",
|
174 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
175 |
+
]
|
176 |
+
},
|
177 |
+
{
|
178 |
+
"data": {
|
179 |
+
"text/plain": [
|
180 |
+
"DistilBertClassificationModel(\n",
|
181 |
+
" (base_model): DistilBertModel(\n",
|
182 |
+
" (embeddings): Embeddings(\n",
|
183 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
184 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
185 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
186 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
187 |
+
" )\n",
|
188 |
+
" (transformer): Transformer(\n",
|
189 |
+
" (layer): ModuleList(\n",
|
190 |
+
" (0-5): 6 x TransformerBlock(\n",
|
191 |
+
" (attention): DistilBertSdpaAttention(\n",
|
192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
193 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
194 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
195 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
196 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
197 |
+
" )\n",
|
198 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
199 |
+
" (ffn): FFN(\n",
|
200 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
201 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
202 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
203 |
+
" (activation): GELUActivation()\n",
|
204 |
+
" )\n",
|
205 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
206 |
+
" )\n",
|
207 |
+
" )\n",
|
208 |
+
" )\n",
|
209 |
+
" )\n",
|
210 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
211 |
+
")"
|
212 |
+
]
|
213 |
+
},
|
214 |
+
"execution_count": 5,
|
215 |
+
"metadata": {},
|
216 |
+
"output_type": "execute_result"
|
217 |
+
}
|
218 |
+
],
|
219 |
+
"source": [
|
220 |
+
"classification_head_path = hf_hub_download(\n",
|
221 |
+
" repo_id=\"ppak10/defect-classification-distilbert-baseline-20-epochs\",\n",
|
222 |
+
" repo_type=\"model\",\n",
|
223 |
+
" filename=\"classification_head.pt\"\n",
|
224 |
+
")\n",
|
225 |
+
"\n",
|
226 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
227 |
+
"model.eval() # Set the model to evaluation mode"
|
228 |
+
]
|
229 |
+
},
|
230 |
+
{
|
231 |
+
"cell_type": "code",
|
232 |
+
"execution_count": 6,
|
233 |
+
"metadata": {},
|
234 |
+
"outputs": [
|
235 |
+
{
|
236 |
+
"name": "stderr",
|
237 |
+
"output_type": "stream",
|
238 |
+
"text": [
|
239 |
+
"100%|ββββββββββ| 1416/1416 [41:34<00:00, 1.76s/it]"
|
240 |
+
]
|
241 |
+
},
|
242 |
+
{
|
243 |
+
"name": "stdout",
|
244 |
+
"output_type": "stream",
|
245 |
+
"text": [
|
246 |
+
"Overall Accuracy: 0.442957916522281\n"
|
247 |
+
]
|
248 |
+
},
|
249 |
+
{
|
250 |
+
"name": "stderr",
|
251 |
+
"output_type": "stream",
|
252 |
+
"text": [
|
253 |
+
"\n"
|
254 |
+
]
|
255 |
+
}
|
256 |
+
],
|
257 |
+
"source": [
|
258 |
+
"# Ensure the model is on the GPU\n",
|
259 |
+
"device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n",
|
260 |
+
"model = model.to(device)\n",
|
261 |
+
"\n",
|
262 |
+
"# Define the batch size\n",
|
263 |
+
"batch_size = 512\n",
|
264 |
+
"\n",
|
265 |
+
"# Create a DataLoader for the validation dataset\n",
|
266 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
267 |
+
"\n",
|
268 |
+
"def label_to_classifications_batch(labels):\n",
|
269 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
270 |
+
" \n",
|
271 |
+
" results = []\n",
|
272 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
273 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
274 |
+
" results.append(result)\n",
|
275 |
+
" return results\n",
|
276 |
+
"\n",
|
277 |
+
"accuracy_total = 0\n",
|
278 |
+
"\n",
|
279 |
+
"# Process the validation dataset in batches\n",
|
280 |
+
"for batch in tqdm(validation_loader):\n",
|
281 |
+
" texts = batch[\"text\"]\n",
|
282 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
283 |
+
"\n",
|
284 |
+
" # Move labels to GPU\n",
|
285 |
+
" # print(np.array(labels))\n",
|
286 |
+
" labels = torch.tensor(labels).to(device)\n",
|
287 |
+
"\n",
|
288 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
289 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
290 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
291 |
+
"\n",
|
292 |
+
" # Perform inference\n",
|
293 |
+
" outputs = model(**inputs)\n",
|
294 |
+
"\n",
|
295 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
296 |
+
" logits = outputs[\"logits\"]\n",
|
297 |
+
" probs = torch.sigmoid(logits)\n",
|
298 |
+
"\n",
|
299 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
300 |
+
" preds = (probs > 0.5).int()\n",
|
301 |
+
" # print(preds)\n",
|
302 |
+
"\n",
|
303 |
+
" # Compute accuracy for the batch\n",
|
304 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
305 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
306 |
+
"\n",
|
307 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
308 |
+
"\n",
|
309 |
+
"# Calculate overall accuracy\n",
|
310 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
311 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
312 |
+
]
|
313 |
+
},
|
314 |
+
{
|
315 |
+
"cell_type": "code",
|
316 |
+
"execution_count": null,
|
317 |
+
"metadata": {},
|
318 |
+
"outputs": [],
|
319 |
+
"source": []
|
320 |
+
}
|
321 |
+
],
|
322 |
+
"metadata": {
|
323 |
+
"kernelspec": {
|
324 |
+
"display_name": "venv",
|
325 |
+
"language": "python",
|
326 |
+
"name": "python3"
|
327 |
+
},
|
328 |
+
"language_info": {
|
329 |
+
"codemirror_mode": {
|
330 |
+
"name": "ipython",
|
331 |
+
"version": 3
|
332 |
+
},
|
333 |
+
"file_extension": ".py",
|
334 |
+
"mimetype": "text/x-python",
|
335 |
+
"name": "python",
|
336 |
+
"nbconvert_exporter": "python",
|
337 |
+
"pygments_lexer": "ipython3",
|
338 |
+
"version": "3.10.12"
|
339 |
+
}
|
340 |
+
},
|
341 |
+
"nbformat": 4,
|
342 |
+
"nbformat_minor": 2
|
343 |
+
}
|
notebooks/distilbert_baseline_25_epochs.ipynb
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-baseline-25-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"name": "stderr",
|
117 |
+
"output_type": "stream",
|
118 |
+
"text": [
|
119 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:09<00:00, 59509.12 examples/s]\n",
|
120 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 50173.76 examples/s]\n",
|
121 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:01<00:00, 56578.02 examples/s]\n"
|
122 |
+
]
|
123 |
+
}
|
124 |
+
],
|
125 |
+
"source": [
|
126 |
+
"# Load dataset\n",
|
127 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
128 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
129 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
130 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
131 |
+
"\n",
|
132 |
+
"# Load the tokenizer\n",
|
133 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-baseline-25-epochs\")\n",
|
134 |
+
"\n",
|
135 |
+
"# Preprocessing function\n",
|
136 |
+
"def preprocess_function(examples):\n",
|
137 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
138 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
139 |
+
" return tokenizer(\n",
|
140 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
141 |
+
" )\n",
|
142 |
+
"\n",
|
143 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
144 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
145 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "markdown",
|
150 |
+
"metadata": {},
|
151 |
+
"source": [
|
152 |
+
"# With Pretrained Weights"
|
153 |
+
]
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"cell_type": "code",
|
157 |
+
"execution_count": 5,
|
158 |
+
"metadata": {},
|
159 |
+
"outputs": [
|
160 |
+
{
|
161 |
+
"name": "stderr",
|
162 |
+
"output_type": "stream",
|
163 |
+
"text": [
|
164 |
+
"/tmp/ipykernel_2059600/419091816.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",
|
165 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
166 |
+
]
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"data": {
|
170 |
+
"text/plain": [
|
171 |
+
"DistilBertClassificationModel(\n",
|
172 |
+
" (base_model): DistilBertModel(\n",
|
173 |
+
" (embeddings): Embeddings(\n",
|
174 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
175 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
176 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
177 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
178 |
+
" )\n",
|
179 |
+
" (transformer): Transformer(\n",
|
180 |
+
" (layer): ModuleList(\n",
|
181 |
+
" (0-5): 6 x TransformerBlock(\n",
|
182 |
+
" (attention): DistilBertSdpaAttention(\n",
|
183 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
184 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
185 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
186 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
187 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
188 |
+
" )\n",
|
189 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
190 |
+
" (ffn): FFN(\n",
|
191 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
192 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
193 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
194 |
+
" (activation): GELUActivation()\n",
|
195 |
+
" )\n",
|
196 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" )\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" )\n",
|
201 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
202 |
+
")"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
"execution_count": 5,
|
206 |
+
"metadata": {},
|
207 |
+
"output_type": "execute_result"
|
208 |
+
}
|
209 |
+
],
|
210 |
+
"source": [
|
211 |
+
"classification_head_path = hf_hub_download(\n",
|
212 |
+
" repo_id=\"ppak10/defect-classification-distilbert-baseline-25-epochs\",\n",
|
213 |
+
" repo_type=\"model\",\n",
|
214 |
+
" filename=\"classification_head.pt\"\n",
|
215 |
+
")\n",
|
216 |
+
"\n",
|
217 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
218 |
+
"model.eval() # Set the model to evaluation mode"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
{
|
222 |
+
"cell_type": "code",
|
223 |
+
"execution_count": 6,
|
224 |
+
"metadata": {},
|
225 |
+
"outputs": [
|
226 |
+
{
|
227 |
+
"name": "stderr",
|
228 |
+
"output_type": "stream",
|
229 |
+
"text": [
|
230 |
+
"100%|ββββββββββ| 142/142 [03:25<00:00, 1.45s/it]"
|
231 |
+
]
|
232 |
+
},
|
233 |
+
{
|
234 |
+
"name": "stdout",
|
235 |
+
"output_type": "stream",
|
236 |
+
"text": [
|
237 |
+
"Overall Accuracy: 0.8841876508376235\n"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"name": "stderr",
|
242 |
+
"output_type": "stream",
|
243 |
+
"text": [
|
244 |
+
"\n"
|
245 |
+
]
|
246 |
+
}
|
247 |
+
],
|
248 |
+
"source": [
|
249 |
+
"# Ensure the model is on the GPU\n",
|
250 |
+
"device = torch.device(\"cuda:2\" if torch.cuda.is_available() else \"cpu\")\n",
|
251 |
+
"model = model.to(device)\n",
|
252 |
+
"\n",
|
253 |
+
"# Define the batch size\n",
|
254 |
+
"batch_size = 512\n",
|
255 |
+
"\n",
|
256 |
+
"# Create a DataLoader for the validation dataset\n",
|
257 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
258 |
+
"\n",
|
259 |
+
"def label_to_classifications_batch(labels):\n",
|
260 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
261 |
+
" \n",
|
262 |
+
" results = []\n",
|
263 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
264 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
265 |
+
" results.append(result)\n",
|
266 |
+
" return results\n",
|
267 |
+
"\n",
|
268 |
+
"accuracy_total = 0\n",
|
269 |
+
"\n",
|
270 |
+
"# Process the validation dataset in batches\n",
|
271 |
+
"for batch in tqdm(validation_loader):\n",
|
272 |
+
" texts = batch[\"text\"]\n",
|
273 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
274 |
+
"\n",
|
275 |
+
" # Move labels to GPU\n",
|
276 |
+
" # print(np.array(labels))\n",
|
277 |
+
" labels = torch.tensor(labels).to(device)\n",
|
278 |
+
"\n",
|
279 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
280 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
281 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
282 |
+
"\n",
|
283 |
+
" # Perform inference\n",
|
284 |
+
" outputs = model(**inputs)\n",
|
285 |
+
"\n",
|
286 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
287 |
+
" logits = outputs[\"logits\"]\n",
|
288 |
+
" probs = torch.sigmoid(logits)\n",
|
289 |
+
"\n",
|
290 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
291 |
+
" preds = (probs > 0.5).int()\n",
|
292 |
+
" # print(preds)\n",
|
293 |
+
"\n",
|
294 |
+
" # Compute accuracy for the batch\n",
|
295 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
296 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
297 |
+
"\n",
|
298 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
299 |
+
"\n",
|
300 |
+
"# Calculate overall accuracy\n",
|
301 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
302 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
303 |
+
]
|
304 |
+
},
|
305 |
+
{
|
306 |
+
"cell_type": "code",
|
307 |
+
"execution_count": null,
|
308 |
+
"metadata": {},
|
309 |
+
"outputs": [],
|
310 |
+
"source": []
|
311 |
+
}
|
312 |
+
],
|
313 |
+
"metadata": {
|
314 |
+
"kernelspec": {
|
315 |
+
"display_name": "venv",
|
316 |
+
"language": "python",
|
317 |
+
"name": "python3"
|
318 |
+
},
|
319 |
+
"language_info": {
|
320 |
+
"codemirror_mode": {
|
321 |
+
"name": "ipython",
|
322 |
+
"version": 3
|
323 |
+
},
|
324 |
+
"file_extension": ".py",
|
325 |
+
"mimetype": "text/x-python",
|
326 |
+
"name": "python",
|
327 |
+
"nbconvert_exporter": "python",
|
328 |
+
"pygments_lexer": "ipython3",
|
329 |
+
"version": "3.10.12"
|
330 |
+
}
|
331 |
+
},
|
332 |
+
"nbformat": 4,
|
333 |
+
"nbformat_minor": 2
|
334 |
+
}
|
notebooks/distilbert_prompt_02_epochs.ipynb
ADDED
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-prompt-02-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [],
|
115 |
+
"source": [
|
116 |
+
"# Load dataset\n",
|
117 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
118 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
119 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
120 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
121 |
+
"\n",
|
122 |
+
"# Load the tokenizer\n",
|
123 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-prompt-02-epochs\")\n",
|
124 |
+
"\n",
|
125 |
+
"# Preprocessing function\n",
|
126 |
+
"def preprocess_function(examples):\n",
|
127 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
128 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
129 |
+
" return tokenizer(\n",
|
130 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
131 |
+
" )\n",
|
132 |
+
"\n",
|
133 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
134 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
135 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
136 |
+
]
|
137 |
+
},
|
138 |
+
{
|
139 |
+
"cell_type": "markdown",
|
140 |
+
"metadata": {},
|
141 |
+
"source": [
|
142 |
+
"# With Pretrained Weights"
|
143 |
+
]
|
144 |
+
},
|
145 |
+
{
|
146 |
+
"cell_type": "code",
|
147 |
+
"execution_count": 5,
|
148 |
+
"metadata": {},
|
149 |
+
"outputs": [
|
150 |
+
{
|
151 |
+
"name": "stderr",
|
152 |
+
"output_type": "stream",
|
153 |
+
"text": [
|
154 |
+
"/tmp/ipykernel_2510164/1493654193.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",
|
155 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
156 |
+
]
|
157 |
+
},
|
158 |
+
{
|
159 |
+
"data": {
|
160 |
+
"text/plain": [
|
161 |
+
"DistilBertClassificationModel(\n",
|
162 |
+
" (base_model): DistilBertModel(\n",
|
163 |
+
" (embeddings): Embeddings(\n",
|
164 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
165 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
166 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
167 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
168 |
+
" )\n",
|
169 |
+
" (transformer): Transformer(\n",
|
170 |
+
" (layer): ModuleList(\n",
|
171 |
+
" (0-5): 6 x TransformerBlock(\n",
|
172 |
+
" (attention): DistilBertSdpaAttention(\n",
|
173 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
174 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
175 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
176 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
177 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
178 |
+
" )\n",
|
179 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
180 |
+
" (ffn): FFN(\n",
|
181 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
182 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
183 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
184 |
+
" (activation): GELUActivation()\n",
|
185 |
+
" )\n",
|
186 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
187 |
+
" )\n",
|
188 |
+
" )\n",
|
189 |
+
" )\n",
|
190 |
+
" )\n",
|
191 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
192 |
+
")"
|
193 |
+
]
|
194 |
+
},
|
195 |
+
"execution_count": 5,
|
196 |
+
"metadata": {},
|
197 |
+
"output_type": "execute_result"
|
198 |
+
}
|
199 |
+
],
|
200 |
+
"source": [
|
201 |
+
"classification_head_path = hf_hub_download(\n",
|
202 |
+
" repo_id=\"ppak10/defect-classification-distilbert-prompt-02-epochs\",\n",
|
203 |
+
" repo_type=\"model\",\n",
|
204 |
+
" filename=\"classification_head.pt\"\n",
|
205 |
+
")\n",
|
206 |
+
"\n",
|
207 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
208 |
+
"model.eval() # Set the model to evaluation mode"
|
209 |
+
]
|
210 |
+
},
|
211 |
+
{
|
212 |
+
"cell_type": "code",
|
213 |
+
"execution_count": 6,
|
214 |
+
"metadata": {},
|
215 |
+
"outputs": [
|
216 |
+
{
|
217 |
+
"name": "stderr",
|
218 |
+
"output_type": "stream",
|
219 |
+
"text": [
|
220 |
+
"100%|ββββββββββ| 1416/1416 [34:28<00:00, 1.46s/it]"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"name": "stdout",
|
225 |
+
"output_type": "stream",
|
226 |
+
"text": [
|
227 |
+
"Overall Accuracy: 0.822280441532714\n"
|
228 |
+
]
|
229 |
+
},
|
230 |
+
{
|
231 |
+
"name": "stderr",
|
232 |
+
"output_type": "stream",
|
233 |
+
"text": [
|
234 |
+
"\n"
|
235 |
+
]
|
236 |
+
}
|
237 |
+
],
|
238 |
+
"source": [
|
239 |
+
"# Ensure the model is on the GPU\n",
|
240 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
241 |
+
"model = model.to(device)\n",
|
242 |
+
"\n",
|
243 |
+
"# Define the batch size\n",
|
244 |
+
"batch_size = 512\n",
|
245 |
+
"\n",
|
246 |
+
"# Create a DataLoader for the validation dataset\n",
|
247 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
248 |
+
"\n",
|
249 |
+
"def label_to_classifications_batch(labels):\n",
|
250 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
251 |
+
" \n",
|
252 |
+
" results = []\n",
|
253 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
254 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
255 |
+
" results.append(result)\n",
|
256 |
+
" return results\n",
|
257 |
+
"\n",
|
258 |
+
"accuracy_total = 0\n",
|
259 |
+
"\n",
|
260 |
+
"# Process the validation dataset in batches\n",
|
261 |
+
"for batch in tqdm(validation_loader):\n",
|
262 |
+
" texts = batch[\"text\"]\n",
|
263 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
264 |
+
"\n",
|
265 |
+
" # Move labels to GPU\n",
|
266 |
+
" # print(np.array(labels))\n",
|
267 |
+
" labels = torch.tensor(labels).to(device)\n",
|
268 |
+
"\n",
|
269 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
270 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
271 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
272 |
+
"\n",
|
273 |
+
" # Perform inference\n",
|
274 |
+
" outputs = model(**inputs)\n",
|
275 |
+
"\n",
|
276 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
277 |
+
" logits = outputs[\"logits\"]\n",
|
278 |
+
" probs = torch.sigmoid(logits)\n",
|
279 |
+
"\n",
|
280 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
281 |
+
" preds = (probs > 0.5).int()\n",
|
282 |
+
" # print(preds)\n",
|
283 |
+
"\n",
|
284 |
+
" # Compute accuracy for the batch\n",
|
285 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
286 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
287 |
+
"\n",
|
288 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
289 |
+
"\n",
|
290 |
+
"# Calculate overall accuracy\n",
|
291 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
292 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
293 |
+
]
|
294 |
+
},
|
295 |
+
{
|
296 |
+
"cell_type": "code",
|
297 |
+
"execution_count": null,
|
298 |
+
"metadata": {},
|
299 |
+
"outputs": [],
|
300 |
+
"source": []
|
301 |
+
}
|
302 |
+
],
|
303 |
+
"metadata": {
|
304 |
+
"kernelspec": {
|
305 |
+
"display_name": "venv",
|
306 |
+
"language": "python",
|
307 |
+
"name": "python3"
|
308 |
+
},
|
309 |
+
"language_info": {
|
310 |
+
"codemirror_mode": {
|
311 |
+
"name": "ipython",
|
312 |
+
"version": 3
|
313 |
+
},
|
314 |
+
"file_extension": ".py",
|
315 |
+
"mimetype": "text/x-python",
|
316 |
+
"name": "python",
|
317 |
+
"nbconvert_exporter": "python",
|
318 |
+
"pygments_lexer": "ipython3",
|
319 |
+
"version": "3.10.12"
|
320 |
+
}
|
321 |
+
},
|
322 |
+
"nbformat": 4,
|
323 |
+
"nbformat_minor": 2
|
324 |
+
}
|
notebooks/distilbert_prompt_05_epochs.ipynb
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.distilbert import DistilBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"DistilBertClassificationModel(\n",
|
66 |
+
" (base_model): DistilBertModel(\n",
|
67 |
+
" (embeddings): Embeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
71 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
72 |
+
" )\n",
|
73 |
+
" (transformer): Transformer(\n",
|
74 |
+
" (layer): ModuleList(\n",
|
75 |
+
" (0-5): 6 x TransformerBlock(\n",
|
76 |
+
" (attention): DistilBertSdpaAttention(\n",
|
77 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
78 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
79 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" )\n",
|
83 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
84 |
+
" (ffn): FFN(\n",
|
85 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
86 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
87 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
88 |
+
" (activation): GELUActivation()\n",
|
89 |
+
" )\n",
|
90 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
91 |
+
" )\n",
|
92 |
+
" )\n",
|
93 |
+
" )\n",
|
94 |
+
" )\n",
|
95 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
96 |
+
")"
|
97 |
+
]
|
98 |
+
},
|
99 |
+
"execution_count": 3,
|
100 |
+
"metadata": {},
|
101 |
+
"output_type": "execute_result"
|
102 |
+
}
|
103 |
+
],
|
104 |
+
"source": [
|
105 |
+
"# Initialize the model\n",
|
106 |
+
"model = DistilBertClassificationModel(\"ppak10/defect-classification-distilbert-prompt-05-epochs\")\n",
|
107 |
+
"model.eval() # Set the model to evaluation mode"
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"cell_type": "code",
|
112 |
+
"execution_count": 4,
|
113 |
+
"metadata": {},
|
114 |
+
"outputs": [
|
115 |
+
{
|
116 |
+
"name": "stderr",
|
117 |
+
"output_type": "stream",
|
118 |
+
"text": [
|
119 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [11:17<00:00, 60140.26 examples/s]\n",
|
120 |
+
"Map (num_proc=32): 100%|ββββββββββ| 1630710/1630710 [00:30<00:00, 53153.66 examples/s]\n",
|
121 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:13<00:00, 52257.28 examples/s]\n"
|
122 |
+
]
|
123 |
+
}
|
124 |
+
],
|
125 |
+
"source": [
|
126 |
+
"# Load dataset\n",
|
127 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
128 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
129 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
130 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
131 |
+
"\n",
|
132 |
+
"# Load the tokenizer\n",
|
133 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-distilbert-prompt-05-epochs\")\n",
|
134 |
+
"\n",
|
135 |
+
"# Preprocessing function\n",
|
136 |
+
"def preprocess_function(examples):\n",
|
137 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
138 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
139 |
+
" return tokenizer(\n",
|
140 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
141 |
+
" )\n",
|
142 |
+
"\n",
|
143 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
144 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
145 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "markdown",
|
150 |
+
"metadata": {},
|
151 |
+
"source": [
|
152 |
+
"# With Pretrained Weights"
|
153 |
+
]
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"cell_type": "code",
|
157 |
+
"execution_count": 5,
|
158 |
+
"metadata": {},
|
159 |
+
"outputs": [
|
160 |
+
{
|
161 |
+
"name": "stderr",
|
162 |
+
"output_type": "stream",
|
163 |
+
"text": [
|
164 |
+
"/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",
|
165 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
166 |
+
]
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"data": {
|
170 |
+
"text/plain": [
|
171 |
+
"DistilBertClassificationModel(\n",
|
172 |
+
" (base_model): DistilBertModel(\n",
|
173 |
+
" (embeddings): Embeddings(\n",
|
174 |
+
" (word_embeddings): Embedding(30522, 768, padding_idx=0)\n",
|
175 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
176 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
177 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
178 |
+
" )\n",
|
179 |
+
" (transformer): Transformer(\n",
|
180 |
+
" (layer): ModuleList(\n",
|
181 |
+
" (0-5): 6 x TransformerBlock(\n",
|
182 |
+
" (attention): DistilBertSdpaAttention(\n",
|
183 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
184 |
+
" (q_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
185 |
+
" (k_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
186 |
+
" (v_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
187 |
+
" (out_lin): Linear(in_features=768, out_features=768, bias=True)\n",
|
188 |
+
" )\n",
|
189 |
+
" (sa_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
190 |
+
" (ffn): FFN(\n",
|
191 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
192 |
+
" (lin1): Linear(in_features=768, out_features=3072, bias=True)\n",
|
193 |
+
" (lin2): Linear(in_features=3072, out_features=768, bias=True)\n",
|
194 |
+
" (activation): GELUActivation()\n",
|
195 |
+
" )\n",
|
196 |
+
" (output_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" )\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" )\n",
|
201 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
202 |
+
")"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
"execution_count": 5,
|
206 |
+
"metadata": {},
|
207 |
+
"output_type": "execute_result"
|
208 |
+
}
|
209 |
+
],
|
210 |
+
"source": [
|
211 |
+
"classification_head_path = hf_hub_download(\n",
|
212 |
+
" repo_id=\"ppak10/defect-classification-distilbert-prompt-05-epochs\",\n",
|
213 |
+
" repo_type=\"model\",\n",
|
214 |
+
" filename=\"classification_head.pt\"\n",
|
215 |
+
")\n",
|
216 |
+
"\n",
|
217 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
218 |
+
"model.eval() # Set the model to evaluation mode"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
{
|
222 |
+
"cell_type": "code",
|
223 |
+
"execution_count": 6,
|
224 |
+
"metadata": {},
|
225 |
+
"outputs": [
|
226 |
+
{
|
227 |
+
"name": "stderr",
|
228 |
+
"output_type": "stream",
|
229 |
+
"text": [
|
230 |
+
"100%|ββββββββββ| 1416/1416 [32:38<00:00, 1.38s/it]"
|
231 |
+
]
|
232 |
+
},
|
233 |
+
{
|
234 |
+
"name": "stdout",
|
235 |
+
"output_type": "stream",
|
236 |
+
"text": [
|
237 |
+
"Overall Accuracy: 0.8149261814346392\n"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
{
|
241 |
+
"name": "stderr",
|
242 |
+
"output_type": "stream",
|
243 |
+
"text": [
|
244 |
+
"\n"
|
245 |
+
]
|
246 |
+
}
|
247 |
+
],
|
248 |
+
"source": [
|
249 |
+
"# Ensure the model is on the GPU\n",
|
250 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
251 |
+
"model = model.to(device)\n",
|
252 |
+
"\n",
|
253 |
+
"# Define the batch size\n",
|
254 |
+
"batch_size = 512\n",
|
255 |
+
"\n",
|
256 |
+
"# Create a DataLoader for the validation dataset\n",
|
257 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
258 |
+
"\n",
|
259 |
+
"def label_to_classifications_batch(labels):\n",
|
260 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
261 |
+
" \n",
|
262 |
+
" results = []\n",
|
263 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
264 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
265 |
+
" results.append(result)\n",
|
266 |
+
" return results\n",
|
267 |
+
"\n",
|
268 |
+
"accuracy_total = 0\n",
|
269 |
+
"\n",
|
270 |
+
"# Process the validation dataset in batches\n",
|
271 |
+
"for batch in tqdm(validation_loader):\n",
|
272 |
+
" texts = batch[\"text\"]\n",
|
273 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
274 |
+
"\n",
|
275 |
+
" # Move labels to GPU\n",
|
276 |
+
" # print(np.array(labels))\n",
|
277 |
+
" labels = torch.tensor(labels).to(device)\n",
|
278 |
+
"\n",
|
279 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
280 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
281 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
282 |
+
"\n",
|
283 |
+
" # Perform inference\n",
|
284 |
+
" outputs = model(**inputs)\n",
|
285 |
+
"\n",
|
286 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
287 |
+
" logits = outputs[\"logits\"]\n",
|
288 |
+
" probs = torch.sigmoid(logits)\n",
|
289 |
+
"\n",
|
290 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
291 |
+
" preds = (probs > 0.5).int()\n",
|
292 |
+
" # print(preds)\n",
|
293 |
+
"\n",
|
294 |
+
" # Compute accuracy for the batch\n",
|
295 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
296 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
297 |
+
"\n",
|
298 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
299 |
+
"\n",
|
300 |
+
"# Calculate overall accuracy\n",
|
301 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
302 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
303 |
+
]
|
304 |
+
},
|
305 |
+
{
|
306 |
+
"cell_type": "code",
|
307 |
+
"execution_count": null,
|
308 |
+
"metadata": {},
|
309 |
+
"outputs": [],
|
310 |
+
"source": []
|
311 |
+
}
|
312 |
+
],
|
313 |
+
"metadata": {
|
314 |
+
"kernelspec": {
|
315 |
+
"display_name": "venv",
|
316 |
+
"language": "python",
|
317 |
+
"name": "python3"
|
318 |
+
},
|
319 |
+
"language_info": {
|
320 |
+
"codemirror_mode": {
|
321 |
+
"name": "ipython",
|
322 |
+
"version": 3
|
323 |
+
},
|
324 |
+
"file_extension": ".py",
|
325 |
+
"mimetype": "text/x-python",
|
326 |
+
"name": "python",
|
327 |
+
"nbconvert_exporter": "python",
|
328 |
+
"pygments_lexer": "ipython3",
|
329 |
+
"version": "3.10.12"
|
330 |
+
}
|
331 |
+
},
|
332 |
+
"nbformat": 4,
|
333 |
+
"nbformat_minor": 2
|
334 |
+
}
|
notebooks/inference.ipynb
ADDED
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 3,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"import torch\n",
|
10 |
+
"\n",
|
11 |
+
"from huggingface_hub import hf_hub_download\n",
|
12 |
+
"from transformers import AutoTokenizer\n",
|
13 |
+
"\n",
|
14 |
+
"from model.distilbert import DistilBertClassificationModel\n",
|
15 |
+
"from model.llama import LlamaClassificationModel"
|
16 |
+
]
|
17 |
+
},
|
18 |
+
{
|
19 |
+
"cell_type": "code",
|
20 |
+
"execution_count": 2,
|
21 |
+
"metadata": {},
|
22 |
+
"outputs": [],
|
23 |
+
"source": [
|
24 |
+
"repo_id = \"ppak10/defect-classification-llama-baseline-25-epochs\""
|
25 |
+
]
|
26 |
+
},
|
27 |
+
{
|
28 |
+
"cell_type": "code",
|
29 |
+
"execution_count": 3,
|
30 |
+
"metadata": {},
|
31 |
+
"outputs": [
|
32 |
+
{
|
33 |
+
"name": "stdout",
|
34 |
+
"output_type": "stream",
|
35 |
+
"text": [
|
36 |
+
"LlamaConfig {\n",
|
37 |
+
" \"_attn_implementation_autoset\": true,\n",
|
38 |
+
" \"_name_or_path\": \"meta-llama/Llama-3.2-1B\",\n",
|
39 |
+
" \"architectures\": [\n",
|
40 |
+
" \"LlamaForCausalLM\"\n",
|
41 |
+
" ],\n",
|
42 |
+
" \"attention_bias\": false,\n",
|
43 |
+
" \"attention_dropout\": 0.0,\n",
|
44 |
+
" \"bos_token_id\": 128000,\n",
|
45 |
+
" \"eos_token_id\": 128001,\n",
|
46 |
+
" \"head_dim\": 64,\n",
|
47 |
+
" \"hidden_act\": \"silu\",\n",
|
48 |
+
" \"hidden_size\": 2048,\n",
|
49 |
+
" \"initializer_range\": 0.02,\n",
|
50 |
+
" \"intermediate_size\": 8192,\n",
|
51 |
+
" \"max_position_embeddings\": 131072,\n",
|
52 |
+
" \"mlp_bias\": false,\n",
|
53 |
+
" \"model_type\": \"llama\",\n",
|
54 |
+
" \"num_attention_heads\": 32,\n",
|
55 |
+
" \"num_hidden_layers\": 16,\n",
|
56 |
+
" \"num_key_value_heads\": 8,\n",
|
57 |
+
" \"pretraining_tp\": 1,\n",
|
58 |
+
" \"rms_norm_eps\": 1e-05,\n",
|
59 |
+
" \"rope_scaling\": {\n",
|
60 |
+
" \"factor\": 32.0,\n",
|
61 |
+
" \"high_freq_factor\": 4.0,\n",
|
62 |
+
" \"low_freq_factor\": 1.0,\n",
|
63 |
+
" \"original_max_position_embeddings\": 8192,\n",
|
64 |
+
" \"rope_type\": \"llama3\"\n",
|
65 |
+
" },\n",
|
66 |
+
" \"rope_theta\": 500000.0,\n",
|
67 |
+
" \"tie_word_embeddings\": true,\n",
|
68 |
+
" \"torch_dtype\": \"bfloat16\",\n",
|
69 |
+
" \"transformers_version\": \"4.47.0\",\n",
|
70 |
+
" \"use_cache\": true,\n",
|
71 |
+
" \"vocab_size\": 128256\n",
|
72 |
+
"}\n",
|
73 |
+
"\n"
|
74 |
+
]
|
75 |
+
},
|
76 |
+
{
|
77 |
+
"name": "stderr",
|
78 |
+
"output_type": "stream",
|
79 |
+
"text": [
|
80 |
+
"/tmp/ipykernel_3716586/1335258174.py:14: 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",
|
81 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
82 |
+
]
|
83 |
+
},
|
84 |
+
{
|
85 |
+
"data": {
|
86 |
+
"text/plain": [
|
87 |
+
"LlamaClassificationModel(\n",
|
88 |
+
" (base_model): LlamaModel(\n",
|
89 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
90 |
+
" (layers): ModuleList(\n",
|
91 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
92 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
93 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
94 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
95 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
97 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
98 |
+
" )\n",
|
99 |
+
" (mlp): LlamaMLP(\n",
|
100 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
101 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
102 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
103 |
+
" (act_fn): SiLU()\n",
|
104 |
+
" )\n",
|
105 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
106 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
107 |
+
" )\n",
|
108 |
+
" )\n",
|
109 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
110 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
111 |
+
" )\n",
|
112 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
113 |
+
")"
|
114 |
+
]
|
115 |
+
},
|
116 |
+
"execution_count": 3,
|
117 |
+
"metadata": {},
|
118 |
+
"output_type": "execute_result"
|
119 |
+
}
|
120 |
+
],
|
121 |
+
"source": [
|
122 |
+
"# Initialize the model\n",
|
123 |
+
"# model = DistilBertClassificationModel(repo_id)\n",
|
124 |
+
"model = LlamaClassificationModel()\n",
|
125 |
+
"\n",
|
126 |
+
"# Load the tokenizer\n",
|
127 |
+
"tokenizer = AutoTokenizer.from_pretrained(repo_id)\n",
|
128 |
+
"\n",
|
129 |
+
"classification_head_path = hf_hub_download(\n",
|
130 |
+
" repo_id=repo_id,\n",
|
131 |
+
" repo_type=\"model\",\n",
|
132 |
+
" filename=\"classification_head.pt\"\n",
|
133 |
+
")\n",
|
134 |
+
"\n",
|
135 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
136 |
+
"model.eval() # Set the model to evaluation mode"
|
137 |
+
]
|
138 |
+
},
|
139 |
+
{
|
140 |
+
"cell_type": "code",
|
141 |
+
"execution_count": 56,
|
142 |
+
"metadata": {},
|
143 |
+
"outputs": [
|
144 |
+
{
|
145 |
+
"name": "stdout",
|
146 |
+
"output_type": "stream",
|
147 |
+
"text": [
|
148 |
+
"tensor([[1, 0, 0, 0]], dtype=torch.int32)\n"
|
149 |
+
]
|
150 |
+
}
|
151 |
+
],
|
152 |
+
"source": [
|
153 |
+
"# text = \"What defects would occur with a beam size of 100 microns, a power of 500 W, a velocity of 100 mm/s and layer height of 10 microns and a hatch spacing of 10 microns for Ti-6Al-4V\"\n",
|
154 |
+
"# text = \"SS316L[SEP]500 W[SEP]10.0 mm/s[SEP]500.0 microns[SEP]500.0 microns[SEP]100.0 microns\"\n",
|
155 |
+
"text = \"SS316L[SEP]250.0 W[SEP]280.0 mm/s[SEP][SEP]950.0 microns[SEP]600.0 microns\"\n",
|
156 |
+
"\n",
|
157 |
+
"# Ensure the model is on the GPU\n",
|
158 |
+
"# device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
159 |
+
"device = \"cpu\"\n",
|
160 |
+
"model = model.to(device)\n",
|
161 |
+
"\n",
|
162 |
+
"# Tokenize input for the entire batch and move to GPU\n",
|
163 |
+
"inputs = tokenizer(text, return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
164 |
+
"inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
165 |
+
"\n",
|
166 |
+
"# Perform inference\n",
|
167 |
+
"outputs = model(**inputs)\n",
|
168 |
+
"\n",
|
169 |
+
"# Extract logits and apply sigmoid activation for multi-label classification\n",
|
170 |
+
"logits = outputs[\"logits\"]\n",
|
171 |
+
"probs = torch.sigmoid(logits)\n",
|
172 |
+
"\n",
|
173 |
+
"# Convert probabilities to one-hot encoded labels\n",
|
174 |
+
"preds = (probs > 0.5).int()\n",
|
175 |
+
"\n",
|
176 |
+
"# None, keyhole, lack of fusion, balling\n",
|
177 |
+
"print(preds)"
|
178 |
+
]
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"cell_type": "code",
|
182 |
+
"execution_count": 1,
|
183 |
+
"metadata": {},
|
184 |
+
"outputs": [
|
185 |
+
{
|
186 |
+
"name": "stderr",
|
187 |
+
"output_type": "stream",
|
188 |
+
"text": [
|
189 |
+
"/mnt/am/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",
|
190 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
191 |
+
]
|
192 |
+
}
|
193 |
+
],
|
194 |
+
"source": [
|
195 |
+
"import torch.nn as nn\n",
|
196 |
+
"from transformers import PreTrainedModel\n",
|
197 |
+
"\n",
|
198 |
+
"class PretrainedLlamaClassificationModel(PreTrainedModel):\n",
|
199 |
+
" def __init__(self, config):\n",
|
200 |
+
" super().__init__(config)\n",
|
201 |
+
" self.base_model = AutoModel.from_pretrained(config.model_path, config=config)\n",
|
202 |
+
" self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n",
|
203 |
+
" self.config = config\n",
|
204 |
+
"\n",
|
205 |
+
" def forward(self, input_ids, attention_mask, labels=None):\n",
|
206 |
+
" outputs = self.base_model(input_ids=input_ids, attention_mask=attention_mask)\n",
|
207 |
+
" summed_representation = outputs.last_hidden_state.sum(dim=1)\n",
|
208 |
+
" logits = self.classifier(summed_representation)\n",
|
209 |
+
" loss = None\n",
|
210 |
+
" if labels is not None:\n",
|
211 |
+
" loss_fn = nn.BCEWithLogitsLoss()\n",
|
212 |
+
" loss = loss_fn(logits, labels.float())\n",
|
213 |
+
" return {\"loss\": loss, \"logits\": logits}\n"
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"cell_type": "code",
|
218 |
+
"execution_count": 1,
|
219 |
+
"metadata": {},
|
220 |
+
"outputs": [
|
221 |
+
{
|
222 |
+
"name": "stderr",
|
223 |
+
"output_type": "stream",
|
224 |
+
"text": [
|
225 |
+
"/mnt/am/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",
|
226 |
+
" from .autonotebook import tqdm as notebook_tqdm\n",
|
227 |
+
"Some weights of LlamaModel were not initialized from the model checkpoint at ppak10/defect-classification-llama-baseline-25-epochs and are newly initialized: ['embed_tokens.weight', 'layers.0.input_layernorm.weight', 'layers.0.mlp.down_proj.weight', 'layers.0.mlp.gate_proj.weight', 'layers.0.mlp.up_proj.weight', 'layers.0.post_attention_layernorm.weight', 'layers.0.self_attn.k_proj.weight', 'layers.0.self_attn.o_proj.weight', 'layers.0.self_attn.q_proj.weight', 'layers.0.self_attn.v_proj.weight', 'layers.1.input_layernorm.weight', 'layers.1.mlp.down_proj.weight', 'layers.1.mlp.gate_proj.weight', 'layers.1.mlp.up_proj.weight', 'layers.1.post_attention_layernorm.weight', 'layers.1.self_attn.k_proj.weight', 'layers.1.self_attn.o_proj.weight', 'layers.1.self_attn.q_proj.weight', 'layers.1.self_attn.v_proj.weight', 'layers.10.input_layernorm.weight', 'layers.10.mlp.down_proj.weight', 'layers.10.mlp.gate_proj.weight', 'layers.10.mlp.up_proj.weight', 'layers.10.post_attention_layernorm.weight', 'layers.10.self_attn.k_proj.weight', 'layers.10.self_attn.o_proj.weight', 'layers.10.self_attn.q_proj.weight', 'layers.10.self_attn.v_proj.weight', 'layers.11.input_layernorm.weight', 'layers.11.mlp.down_proj.weight', 'layers.11.mlp.gate_proj.weight', 'layers.11.mlp.up_proj.weight', 'layers.11.post_attention_layernorm.weight', 'layers.11.self_attn.k_proj.weight', 'layers.11.self_attn.o_proj.weight', 'layers.11.self_attn.q_proj.weight', 'layers.11.self_attn.v_proj.weight', 'layers.12.input_layernorm.weight', 'layers.12.mlp.down_proj.weight', 'layers.12.mlp.gate_proj.weight', 'layers.12.mlp.up_proj.weight', 'layers.12.post_attention_layernorm.weight', 'layers.12.self_attn.k_proj.weight', 'layers.12.self_attn.o_proj.weight', 'layers.12.self_attn.q_proj.weight', 'layers.12.self_attn.v_proj.weight', 'layers.13.input_layernorm.weight', 'layers.13.mlp.down_proj.weight', 'layers.13.mlp.gate_proj.weight', 'layers.13.mlp.up_proj.weight', 'layers.13.post_attention_layernorm.weight', 'layers.13.self_attn.k_proj.weight', 'layers.13.self_attn.o_proj.weight', 'layers.13.self_attn.q_proj.weight', 'layers.13.self_attn.v_proj.weight', 'layers.14.input_layernorm.weight', 'layers.14.mlp.down_proj.weight', 'layers.14.mlp.gate_proj.weight', 'layers.14.mlp.up_proj.weight', 'layers.14.post_attention_layernorm.weight', 'layers.14.self_attn.k_proj.weight', 'layers.14.self_attn.o_proj.weight', 'layers.14.self_attn.q_proj.weight', 'layers.14.self_attn.v_proj.weight', 'layers.15.input_layernorm.weight', 'layers.15.mlp.down_proj.weight', 'layers.15.mlp.gate_proj.weight', 'layers.15.mlp.up_proj.weight', 'layers.15.post_attention_layernorm.weight', 'layers.15.self_attn.k_proj.weight', 'layers.15.self_attn.o_proj.weight', 'layers.15.self_attn.q_proj.weight', 'layers.15.self_attn.v_proj.weight', 'layers.16.input_layernorm.weight', 'layers.16.mlp.down_proj.weight', 'layers.16.mlp.gate_proj.weight', 'layers.16.mlp.up_proj.weight', 'layers.16.post_attention_layernorm.weight', 'layers.16.self_attn.k_proj.weight', 'layers.16.self_attn.o_proj.weight', 'layers.16.self_attn.q_proj.weight', 'layers.16.self_attn.v_proj.weight', 'layers.17.input_layernorm.weight', 'layers.17.mlp.down_proj.weight', 'layers.17.mlp.gate_proj.weight', 'layers.17.mlp.up_proj.weight', 'layers.17.post_attention_layernorm.weight', 'layers.17.self_attn.k_proj.weight', 'layers.17.self_attn.o_proj.weight', 'layers.17.self_attn.q_proj.weight', 'layers.17.self_attn.v_proj.weight', 'layers.18.input_layernorm.weight', 'layers.18.mlp.down_proj.weight', 'layers.18.mlp.gate_proj.weight', 'layers.18.mlp.up_proj.weight', 'layers.18.post_attention_layernorm.weight', 'layers.18.self_attn.k_proj.weight', 'layers.18.self_attn.o_proj.weight', 'layers.18.self_attn.q_proj.weight', 'layers.18.self_attn.v_proj.weight', 'layers.19.input_layernorm.weight', 'layers.19.mlp.down_proj.weight', 'layers.19.mlp.gate_proj.weight', 'layers.19.mlp.up_proj.weight', 'layers.19.post_attention_layernorm.weight', 'layers.19.self_attn.k_proj.weight', 'layers.19.self_attn.o_proj.weight', 'layers.19.self_attn.q_proj.weight', 'layers.19.self_attn.v_proj.weight', 'layers.2.input_layernorm.weight', 'layers.2.mlp.down_proj.weight', 'layers.2.mlp.gate_proj.weight', 'layers.2.mlp.up_proj.weight', 'layers.2.post_attention_layernorm.weight', 'layers.2.self_attn.k_proj.weight', 'layers.2.self_attn.o_proj.weight', 'layers.2.self_attn.q_proj.weight', 'layers.2.self_attn.v_proj.weight', 'layers.20.input_layernorm.weight', 'layers.20.mlp.down_proj.weight', 'layers.20.mlp.gate_proj.weight', 'layers.20.mlp.up_proj.weight', 'layers.20.post_attention_layernorm.weight', 'layers.20.self_attn.k_proj.weight', 'layers.20.self_attn.o_proj.weight', 'layers.20.self_attn.q_proj.weight', 'layers.20.self_attn.v_proj.weight', 'layers.21.input_layernorm.weight', 'layers.21.mlp.down_proj.weight', 'layers.21.mlp.gate_proj.weight', 'layers.21.mlp.up_proj.weight', 'layers.21.post_attention_layernorm.weight', 'layers.21.self_attn.k_proj.weight', 'layers.21.self_attn.o_proj.weight', 'layers.21.self_attn.q_proj.weight', 'layers.21.self_attn.v_proj.weight', 'layers.22.input_layernorm.weight', 'layers.22.mlp.down_proj.weight', 'layers.22.mlp.gate_proj.weight', 'layers.22.mlp.up_proj.weight', 'layers.22.post_attention_layernorm.weight', 'layers.22.self_attn.k_proj.weight', 'layers.22.self_attn.o_proj.weight', 'layers.22.self_attn.q_proj.weight', 'layers.22.self_attn.v_proj.weight', 'layers.23.input_layernorm.weight', 'layers.23.mlp.down_proj.weight', 'layers.23.mlp.gate_proj.weight', 'layers.23.mlp.up_proj.weight', 'layers.23.post_attention_layernorm.weight', 'layers.23.self_attn.k_proj.weight', 'layers.23.self_attn.o_proj.weight', 'layers.23.self_attn.q_proj.weight', 'layers.23.self_attn.v_proj.weight', 'layers.24.input_layernorm.weight', 'layers.24.mlp.down_proj.weight', 'layers.24.mlp.gate_proj.weight', 'layers.24.mlp.up_proj.weight', 'layers.24.post_attention_layernorm.weight', 'layers.24.self_attn.k_proj.weight', 'layers.24.self_attn.o_proj.weight', 'layers.24.self_attn.q_proj.weight', 'layers.24.self_attn.v_proj.weight', 'layers.25.input_layernorm.weight', 'layers.25.mlp.down_proj.weight', 'layers.25.mlp.gate_proj.weight', 'layers.25.mlp.up_proj.weight', 'layers.25.post_attention_layernorm.weight', 'layers.25.self_attn.k_proj.weight', 'layers.25.self_attn.o_proj.weight', 'layers.25.self_attn.q_proj.weight', 'layers.25.self_attn.v_proj.weight', 'layers.26.input_layernorm.weight', 'layers.26.mlp.down_proj.weight', 'layers.26.mlp.gate_proj.weight', 'layers.26.mlp.up_proj.weight', 'layers.26.post_attention_layernorm.weight', 'layers.26.self_attn.k_proj.weight', 'layers.26.self_attn.o_proj.weight', 'layers.26.self_attn.q_proj.weight', 'layers.26.self_attn.v_proj.weight', 'layers.27.input_layernorm.weight', 'layers.27.mlp.down_proj.weight', 'layers.27.mlp.gate_proj.weight', 'layers.27.mlp.up_proj.weight', 'layers.27.post_attention_layernorm.weight', 'layers.27.self_attn.k_proj.weight', 'layers.27.self_attn.o_proj.weight', 'layers.27.self_attn.q_proj.weight', 'layers.27.self_attn.v_proj.weight', 'layers.28.input_layernorm.weight', 'layers.28.mlp.down_proj.weight', 'layers.28.mlp.gate_proj.weight', 'layers.28.mlp.up_proj.weight', 'layers.28.post_attention_layernorm.weight', 'layers.28.self_attn.k_proj.weight', 'layers.28.self_attn.o_proj.weight', 'layers.28.self_attn.q_proj.weight', 'layers.28.self_attn.v_proj.weight', 'layers.29.input_layernorm.weight', 'layers.29.mlp.down_proj.weight', 'layers.29.mlp.gate_proj.weight', 'layers.29.mlp.up_proj.weight', 'layers.29.post_attention_layernorm.weight', 'layers.29.self_attn.k_proj.weight', 'layers.29.self_attn.o_proj.weight', 'layers.29.self_attn.q_proj.weight', 'layers.29.self_attn.v_proj.weight', 'layers.3.input_layernorm.weight', 'layers.3.mlp.down_proj.weight', 'layers.3.mlp.gate_proj.weight', 'layers.3.mlp.up_proj.weight', 'layers.3.post_attention_layernorm.weight', 'layers.3.self_attn.k_proj.weight', 'layers.3.self_attn.o_proj.weight', 'layers.3.self_attn.q_proj.weight', 'layers.3.self_attn.v_proj.weight', 'layers.30.input_layernorm.weight', 'layers.30.mlp.down_proj.weight', 'layers.30.mlp.gate_proj.weight', 'layers.30.mlp.up_proj.weight', 'layers.30.post_attention_layernorm.weight', 'layers.30.self_attn.k_proj.weight', 'layers.30.self_attn.o_proj.weight', 'layers.30.self_attn.q_proj.weight', 'layers.30.self_attn.v_proj.weight', 'layers.31.input_layernorm.weight', 'layers.31.mlp.down_proj.weight', 'layers.31.mlp.gate_proj.weight', 'layers.31.mlp.up_proj.weight', 'layers.31.post_attention_layernorm.weight', 'layers.31.self_attn.k_proj.weight', 'layers.31.self_attn.o_proj.weight', 'layers.31.self_attn.q_proj.weight', 'layers.31.self_attn.v_proj.weight', 'layers.4.input_layernorm.weight', 'layers.4.mlp.down_proj.weight', 'layers.4.mlp.gate_proj.weight', 'layers.4.mlp.up_proj.weight', 'layers.4.post_attention_layernorm.weight', 'layers.4.self_attn.k_proj.weight', 'layers.4.self_attn.o_proj.weight', 'layers.4.self_attn.q_proj.weight', 'layers.4.self_attn.v_proj.weight', 'layers.5.input_layernorm.weight', 'layers.5.mlp.down_proj.weight', 'layers.5.mlp.gate_proj.weight', 'layers.5.mlp.up_proj.weight', 'layers.5.post_attention_layernorm.weight', 'layers.5.self_attn.k_proj.weight', 'layers.5.self_attn.o_proj.weight', 'layers.5.self_attn.q_proj.weight', 'layers.5.self_attn.v_proj.weight', 'layers.6.input_layernorm.weight', 'layers.6.mlp.down_proj.weight', 'layers.6.mlp.gate_proj.weight', 'layers.6.mlp.up_proj.weight', 'layers.6.post_attention_layernorm.weight', 'layers.6.self_attn.k_proj.weight', 'layers.6.self_attn.o_proj.weight', 'layers.6.self_attn.q_proj.weight', 'layers.6.self_attn.v_proj.weight', 'layers.7.input_layernorm.weight', 'layers.7.mlp.down_proj.weight', 'layers.7.mlp.gate_proj.weight', 'layers.7.mlp.up_proj.weight', 'layers.7.post_attention_layernorm.weight', 'layers.7.self_attn.k_proj.weight', 'layers.7.self_attn.o_proj.weight', 'layers.7.self_attn.q_proj.weight', 'layers.7.self_attn.v_proj.weight', 'layers.8.input_layernorm.weight', 'layers.8.mlp.down_proj.weight', 'layers.8.mlp.gate_proj.weight', 'layers.8.mlp.up_proj.weight', 'layers.8.post_attention_layernorm.weight', 'layers.8.self_attn.k_proj.weight', 'layers.8.self_attn.o_proj.weight', 'layers.8.self_attn.q_proj.weight', 'layers.8.self_attn.v_proj.weight', 'layers.9.input_layernorm.weight', 'layers.9.mlp.down_proj.weight', 'layers.9.mlp.gate_proj.weight', 'layers.9.mlp.up_proj.weight', 'layers.9.post_attention_layernorm.weight', 'layers.9.self_attn.k_proj.weight', 'layers.9.self_attn.o_proj.weight', 'layers.9.self_attn.q_proj.weight', 'layers.9.self_attn.v_proj.weight', 'norm.weight']\n",
|
228 |
+
"You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n"
|
229 |
+
]
|
230 |
+
}
|
231 |
+
],
|
232 |
+
"source": [
|
233 |
+
"from transformers import AutoModel, pipeline\n",
|
234 |
+
"\n",
|
235 |
+
"repo_id = \"ppak10/defect-classification-llama-baseline-25-epochs\"\n",
|
236 |
+
"model = AutoModel.from_pretrained(repo_id)\n",
|
237 |
+
"# tokenizer = AutoTokenizer.from_pretrained(repo_id)\n",
|
238 |
+
"\n",
|
239 |
+
"# classification_pipeline = pipeline(\"text-classification\", model=model, tokenizer=tokenizer)\n",
|
240 |
+
"# result = classification_pipeline(\"Test input text\")\n",
|
241 |
+
"# print(result)\n"
|
242 |
+
]
|
243 |
+
},
|
244 |
+
{
|
245 |
+
"cell_type": "code",
|
246 |
+
"execution_count": 2,
|
247 |
+
"metadata": {},
|
248 |
+
"outputs": [
|
249 |
+
{
|
250 |
+
"name": "stdout",
|
251 |
+
"output_type": "stream",
|
252 |
+
"text": [
|
253 |
+
"LlamaModel(\n",
|
254 |
+
" (embed_tokens): Embedding(32000, 2048)\n",
|
255 |
+
" (layers): ModuleList(\n",
|
256 |
+
" (0-31): 32 x LlamaDecoderLayer(\n",
|
257 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
258 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
259 |
+
" (k_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
260 |
+
" (v_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
261 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
262 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
263 |
+
" )\n",
|
264 |
+
" (mlp): LlamaMLP(\n",
|
265 |
+
" (gate_proj): Linear(in_features=2048, out_features=11008, bias=False)\n",
|
266 |
+
" (up_proj): Linear(in_features=2048, out_features=11008, bias=False)\n",
|
267 |
+
" (down_proj): Linear(in_features=11008, out_features=2048, bias=False)\n",
|
268 |
+
" (act_fn): SiLU()\n",
|
269 |
+
" )\n",
|
270 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-06)\n",
|
271 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-06)\n",
|
272 |
+
" )\n",
|
273 |
+
" )\n",
|
274 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-06)\n",
|
275 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
276 |
+
")\n"
|
277 |
+
]
|
278 |
+
}
|
279 |
+
],
|
280 |
+
"source": [
|
281 |
+
"print(model)"
|
282 |
+
]
|
283 |
+
},
|
284 |
+
{
|
285 |
+
"cell_type": "code",
|
286 |
+
"execution_count": null,
|
287 |
+
"metadata": {},
|
288 |
+
"outputs": [],
|
289 |
+
"source": []
|
290 |
+
}
|
291 |
+
],
|
292 |
+
"metadata": {
|
293 |
+
"kernelspec": {
|
294 |
+
"display_name": "venv",
|
295 |
+
"language": "python",
|
296 |
+
"name": "python3"
|
297 |
+
},
|
298 |
+
"language_info": {
|
299 |
+
"codemirror_mode": {
|
300 |
+
"name": "ipython",
|
301 |
+
"version": 3
|
302 |
+
},
|
303 |
+
"file_extension": ".py",
|
304 |
+
"mimetype": "text/x-python",
|
305 |
+
"name": "python",
|
306 |
+
"nbconvert_exporter": "python",
|
307 |
+
"pygments_lexer": "ipython3",
|
308 |
+
"version": "3.10.12"
|
309 |
+
}
|
310 |
+
},
|
311 |
+
"nbformat": 4,
|
312 |
+
"nbformat_minor": 2
|
313 |
+
}
|
notebooks/llama_baseline_05_epochs.ipynb
ADDED
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.llama import LlamaClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"LlamaClassificationModel(\n",
|
66 |
+
" (base_model): LlamaModel(\n",
|
67 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
68 |
+
" (layers): ModuleList(\n",
|
69 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
70 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
71 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
72 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
73 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
74 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
75 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
76 |
+
" )\n",
|
77 |
+
" (mlp): LlamaMLP(\n",
|
78 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
79 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
80 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
81 |
+
" (act_fn): SiLU()\n",
|
82 |
+
" )\n",
|
83 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
84 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
85 |
+
" )\n",
|
86 |
+
" )\n",
|
87 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
88 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
89 |
+
" )\n",
|
90 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
91 |
+
")"
|
92 |
+
]
|
93 |
+
},
|
94 |
+
"execution_count": 3,
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "execute_result"
|
97 |
+
}
|
98 |
+
],
|
99 |
+
"source": [
|
100 |
+
"# Initialize the model\n",
|
101 |
+
"model = LlamaClassificationModel()\n",
|
102 |
+
"model.eval() # Set the model to evaluation mode"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 4,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [
|
110 |
+
{
|
111 |
+
"name": "stderr",
|
112 |
+
"output_type": "stream",
|
113 |
+
"text": [
|
114 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:12<00:00, 44648.57 examples/s]\n",
|
115 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 38232.89 examples/s]\n",
|
116 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 33138.38 examples/s]\n"
|
117 |
+
]
|
118 |
+
}
|
119 |
+
],
|
120 |
+
"source": [
|
121 |
+
"# Load dataset\n",
|
122 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
123 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
124 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
125 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
126 |
+
"\n",
|
127 |
+
"# Load the tokenizer\n",
|
128 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-llama-baseline-05-epochs\")\n",
|
129 |
+
"\n",
|
130 |
+
"# Preprocessing function\n",
|
131 |
+
"def preprocess_function(examples):\n",
|
132 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
133 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
134 |
+
" return tokenizer(\n",
|
135 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
136 |
+
" )\n",
|
137 |
+
"\n",
|
138 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
139 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
140 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
141 |
+
]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"cell_type": "code",
|
145 |
+
"execution_count": 5,
|
146 |
+
"metadata": {},
|
147 |
+
"outputs": [
|
148 |
+
{
|
149 |
+
"name": "stderr",
|
150 |
+
"output_type": "stream",
|
151 |
+
"text": [
|
152 |
+
"/tmp/ipykernel_3633453/4171752512.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",
|
153 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
154 |
+
]
|
155 |
+
},
|
156 |
+
{
|
157 |
+
"data": {
|
158 |
+
"text/plain": [
|
159 |
+
"LlamaClassificationModel(\n",
|
160 |
+
" (base_model): LlamaModel(\n",
|
161 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
162 |
+
" (layers): ModuleList(\n",
|
163 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
164 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
165 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
166 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
167 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
168 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
169 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
170 |
+
" )\n",
|
171 |
+
" (mlp): LlamaMLP(\n",
|
172 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
173 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
174 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
175 |
+
" (act_fn): SiLU()\n",
|
176 |
+
" )\n",
|
177 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
178 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
179 |
+
" )\n",
|
180 |
+
" )\n",
|
181 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
182 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
183 |
+
" )\n",
|
184 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
185 |
+
")"
|
186 |
+
]
|
187 |
+
},
|
188 |
+
"execution_count": 5,
|
189 |
+
"metadata": {},
|
190 |
+
"output_type": "execute_result"
|
191 |
+
}
|
192 |
+
],
|
193 |
+
"source": [
|
194 |
+
"classification_head_path = hf_hub_download(\n",
|
195 |
+
" repo_id=\"ppak10/defect-classification-llama-baseline-05-epochs\",\n",
|
196 |
+
" repo_type=\"model\",\n",
|
197 |
+
" filename=\"classification_head.pt\"\n",
|
198 |
+
")\n",
|
199 |
+
"\n",
|
200 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
201 |
+
"model.eval() # Set the model to evaluation mode"
|
202 |
+
]
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"cell_type": "code",
|
206 |
+
"execution_count": 6,
|
207 |
+
"metadata": {},
|
208 |
+
"outputs": [
|
209 |
+
{
|
210 |
+
"name": "stderr",
|
211 |
+
"output_type": "stream",
|
212 |
+
"text": [
|
213 |
+
"100%|ββββββββββ| 1133/1133 [1:20:49<00:00, 4.28s/it]"
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"name": "stdout",
|
218 |
+
"output_type": "stream",
|
219 |
+
"text": [
|
220 |
+
"Overall Accuracy: 0.8918489134151305\n"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"name": "stderr",
|
225 |
+
"output_type": "stream",
|
226 |
+
"text": [
|
227 |
+
"\n"
|
228 |
+
]
|
229 |
+
}
|
230 |
+
],
|
231 |
+
"source": [
|
232 |
+
"# Ensure the model is on the GPU\n",
|
233 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
234 |
+
"model = model.to(device)\n",
|
235 |
+
"\n",
|
236 |
+
"# Define the batch size\n",
|
237 |
+
"batch_size = 64\n",
|
238 |
+
"\n",
|
239 |
+
"# Create a DataLoader for the validation dataset\n",
|
240 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
241 |
+
"\n",
|
242 |
+
"def label_to_classifications_batch(labels):\n",
|
243 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
244 |
+
" \n",
|
245 |
+
" results = []\n",
|
246 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
247 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
248 |
+
" results.append(result)\n",
|
249 |
+
" return results\n",
|
250 |
+
"\n",
|
251 |
+
"accuracy_total = 0\n",
|
252 |
+
"\n",
|
253 |
+
"# Process the validation dataset in batches\n",
|
254 |
+
"for batch in tqdm(validation_loader):\n",
|
255 |
+
" texts = batch[\"text\"]\n",
|
256 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
257 |
+
"\n",
|
258 |
+
" # Move labels to GPU\n",
|
259 |
+
" # print(np.array(labels))\n",
|
260 |
+
" labels = torch.tensor(labels).to(device)\n",
|
261 |
+
"\n",
|
262 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
263 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
264 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
265 |
+
"\n",
|
266 |
+
" # Perform inference\n",
|
267 |
+
" outputs = model(**inputs)\n",
|
268 |
+
"\n",
|
269 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
270 |
+
" logits = outputs[\"logits\"]\n",
|
271 |
+
" probs = torch.sigmoid(logits)\n",
|
272 |
+
"\n",
|
273 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
274 |
+
" preds = (probs > 0.5).int()\n",
|
275 |
+
"\n",
|
276 |
+
" # Compute accuracy for the batch\n",
|
277 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
278 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
279 |
+
"\n",
|
280 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
281 |
+
"\n",
|
282 |
+
"# Calculate overall accuracy\n",
|
283 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
284 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
285 |
+
]
|
286 |
+
}
|
287 |
+
],
|
288 |
+
"metadata": {
|
289 |
+
"kernelspec": {
|
290 |
+
"display_name": "venv",
|
291 |
+
"language": "python",
|
292 |
+
"name": "python3"
|
293 |
+
},
|
294 |
+
"language_info": {
|
295 |
+
"codemirror_mode": {
|
296 |
+
"name": "ipython",
|
297 |
+
"version": 3
|
298 |
+
},
|
299 |
+
"file_extension": ".py",
|
300 |
+
"mimetype": "text/x-python",
|
301 |
+
"name": "python",
|
302 |
+
"nbconvert_exporter": "python",
|
303 |
+
"pygments_lexer": "ipython3",
|
304 |
+
"version": "3.10.16"
|
305 |
+
}
|
306 |
+
},
|
307 |
+
"nbformat": 4,
|
308 |
+
"nbformat_minor": 2
|
309 |
+
}
|
notebooks/llama_baseline_10_epochs.ipynb
ADDED
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.llama import LlamaClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"LlamaClassificationModel(\n",
|
66 |
+
" (base_model): LlamaModel(\n",
|
67 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
68 |
+
" (layers): ModuleList(\n",
|
69 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
70 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
71 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
72 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
73 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
74 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
75 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
76 |
+
" )\n",
|
77 |
+
" (mlp): LlamaMLP(\n",
|
78 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
79 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
80 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
81 |
+
" (act_fn): SiLU()\n",
|
82 |
+
" )\n",
|
83 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
84 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
85 |
+
" )\n",
|
86 |
+
" )\n",
|
87 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
88 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
89 |
+
" )\n",
|
90 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
91 |
+
")"
|
92 |
+
]
|
93 |
+
},
|
94 |
+
"execution_count": 3,
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "execute_result"
|
97 |
+
}
|
98 |
+
],
|
99 |
+
"source": [
|
100 |
+
"# Initialize the model\n",
|
101 |
+
"model = LlamaClassificationModel()\n",
|
102 |
+
"model.eval() # Set the model to evaluation mode"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 4,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [
|
110 |
+
{
|
111 |
+
"name": "stderr",
|
112 |
+
"output_type": "stream",
|
113 |
+
"text": [
|
114 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:12<00:00, 43017.09 examples/s]\n",
|
115 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 39711.28 examples/s]\n",
|
116 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 36221.05 examples/s]\n"
|
117 |
+
]
|
118 |
+
}
|
119 |
+
],
|
120 |
+
"source": [
|
121 |
+
"# Load dataset\n",
|
122 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
123 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
124 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
125 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
126 |
+
"\n",
|
127 |
+
"# Load the tokenizer\n",
|
128 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-llama-baseline-10-epochs\")\n",
|
129 |
+
"\n",
|
130 |
+
"# Preprocessing function\n",
|
131 |
+
"def preprocess_function(examples):\n",
|
132 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
133 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
134 |
+
" return tokenizer(\n",
|
135 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
136 |
+
" )\n",
|
137 |
+
"\n",
|
138 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
139 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
140 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
141 |
+
]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"cell_type": "code",
|
145 |
+
"execution_count": 5,
|
146 |
+
"metadata": {},
|
147 |
+
"outputs": [
|
148 |
+
{
|
149 |
+
"name": "stderr",
|
150 |
+
"output_type": "stream",
|
151 |
+
"text": [
|
152 |
+
"/tmp/ipykernel_1196615/2213215181.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",
|
153 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
154 |
+
]
|
155 |
+
},
|
156 |
+
{
|
157 |
+
"data": {
|
158 |
+
"text/plain": [
|
159 |
+
"LlamaClassificationModel(\n",
|
160 |
+
" (base_model): LlamaModel(\n",
|
161 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
162 |
+
" (layers): ModuleList(\n",
|
163 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
164 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
165 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
166 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
167 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
168 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
169 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
170 |
+
" )\n",
|
171 |
+
" (mlp): LlamaMLP(\n",
|
172 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
173 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
174 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
175 |
+
" (act_fn): SiLU()\n",
|
176 |
+
" )\n",
|
177 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
178 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
179 |
+
" )\n",
|
180 |
+
" )\n",
|
181 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
182 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
183 |
+
" )\n",
|
184 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
185 |
+
")"
|
186 |
+
]
|
187 |
+
},
|
188 |
+
"execution_count": 5,
|
189 |
+
"metadata": {},
|
190 |
+
"output_type": "execute_result"
|
191 |
+
}
|
192 |
+
],
|
193 |
+
"source": [
|
194 |
+
"classification_head_path = hf_hub_download(\n",
|
195 |
+
" repo_id=\"ppak10/defect-classification-llama-baseline-10-epochs\",\n",
|
196 |
+
" repo_type=\"model\",\n",
|
197 |
+
" filename=\"classification_head.pt\"\n",
|
198 |
+
")\n",
|
199 |
+
"\n",
|
200 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
201 |
+
"model.eval() # Set the model to evaluation mode"
|
202 |
+
]
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"cell_type": "code",
|
206 |
+
"execution_count": 6,
|
207 |
+
"metadata": {},
|
208 |
+
"outputs": [
|
209 |
+
{
|
210 |
+
"name": "stderr",
|
211 |
+
"output_type": "stream",
|
212 |
+
"text": [
|
213 |
+
"100%|ββββββββββ| 1133/1133 [37:36<00:00, 1.99s/it]"
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"name": "stdout",
|
218 |
+
"output_type": "stream",
|
219 |
+
"text": [
|
220 |
+
"Overall Accuracy: 0.9166954122119297\n"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"name": "stderr",
|
225 |
+
"output_type": "stream",
|
226 |
+
"text": [
|
227 |
+
"\n"
|
228 |
+
]
|
229 |
+
}
|
230 |
+
],
|
231 |
+
"source": [
|
232 |
+
"# Ensure the model is on the GPU\n",
|
233 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
234 |
+
"model = model.to(device)\n",
|
235 |
+
"\n",
|
236 |
+
"# Define the batch size\n",
|
237 |
+
"batch_size = 64\n",
|
238 |
+
"\n",
|
239 |
+
"# Create a DataLoader for the validation dataset\n",
|
240 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
241 |
+
"\n",
|
242 |
+
"def label_to_classifications_batch(labels):\n",
|
243 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
244 |
+
" \n",
|
245 |
+
" results = []\n",
|
246 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
247 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
248 |
+
" results.append(result)\n",
|
249 |
+
" return results\n",
|
250 |
+
"\n",
|
251 |
+
"accuracy_total = 0\n",
|
252 |
+
"\n",
|
253 |
+
"# Process the validation dataset in batches\n",
|
254 |
+
"for batch in tqdm(validation_loader):\n",
|
255 |
+
" texts = batch[\"text\"]\n",
|
256 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
257 |
+
"\n",
|
258 |
+
" # Move labels to GPU\n",
|
259 |
+
" # print(np.array(labels))\n",
|
260 |
+
" labels = torch.tensor(labels).to(device)\n",
|
261 |
+
"\n",
|
262 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
263 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
264 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
265 |
+
"\n",
|
266 |
+
" # Perform inference\n",
|
267 |
+
" outputs = model(**inputs)\n",
|
268 |
+
"\n",
|
269 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
270 |
+
" logits = outputs[\"logits\"]\n",
|
271 |
+
" probs = torch.sigmoid(logits)\n",
|
272 |
+
"\n",
|
273 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
274 |
+
" preds = (probs > 0.5).int()\n",
|
275 |
+
"\n",
|
276 |
+
" # Compute accuracy for the batch\n",
|
277 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
278 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
279 |
+
"\n",
|
280 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
281 |
+
"\n",
|
282 |
+
"# Calculate overall accuracy\n",
|
283 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
284 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
285 |
+
]
|
286 |
+
}
|
287 |
+
],
|
288 |
+
"metadata": {
|
289 |
+
"kernelspec": {
|
290 |
+
"display_name": "venv",
|
291 |
+
"language": "python",
|
292 |
+
"name": "python3"
|
293 |
+
},
|
294 |
+
"language_info": {
|
295 |
+
"codemirror_mode": {
|
296 |
+
"name": "ipython",
|
297 |
+
"version": 3
|
298 |
+
},
|
299 |
+
"file_extension": ".py",
|
300 |
+
"mimetype": "text/x-python",
|
301 |
+
"name": "python",
|
302 |
+
"nbconvert_exporter": "python",
|
303 |
+
"pygments_lexer": "ipython3",
|
304 |
+
"version": "3.10.16"
|
305 |
+
}
|
306 |
+
},
|
307 |
+
"nbformat": 4,
|
308 |
+
"nbformat_minor": 2
|
309 |
+
}
|
notebooks/llama_baseline_15_epochs.ipynb
ADDED
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.llama import LlamaClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"LlamaClassificationModel(\n",
|
66 |
+
" (base_model): LlamaModel(\n",
|
67 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
68 |
+
" (layers): ModuleList(\n",
|
69 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
70 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
71 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
72 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
73 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
74 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
75 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
76 |
+
" )\n",
|
77 |
+
" (mlp): LlamaMLP(\n",
|
78 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
79 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
80 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
81 |
+
" (act_fn): SiLU()\n",
|
82 |
+
" )\n",
|
83 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
84 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
85 |
+
" )\n",
|
86 |
+
" )\n",
|
87 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
88 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
89 |
+
" )\n",
|
90 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
91 |
+
")"
|
92 |
+
]
|
93 |
+
},
|
94 |
+
"execution_count": 3,
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "execute_result"
|
97 |
+
}
|
98 |
+
],
|
99 |
+
"source": [
|
100 |
+
"# Initialize the model\n",
|
101 |
+
"model = LlamaClassificationModel()\n",
|
102 |
+
"model.eval() # Set the model to evaluation mode"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 4,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [
|
110 |
+
{
|
111 |
+
"name": "stderr",
|
112 |
+
"output_type": "stream",
|
113 |
+
"text": [
|
114 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:03<00:00, 176364.88 examples/s]\n",
|
115 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:01<00:00, 97846.27 examples/s] \n",
|
116 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:00<00:00, 101934.72 examples/s]\n"
|
117 |
+
]
|
118 |
+
}
|
119 |
+
],
|
120 |
+
"source": [
|
121 |
+
"# Load dataset\n",
|
122 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
123 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
124 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
125 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
126 |
+
"\n",
|
127 |
+
"# Load the tokenizer\n",
|
128 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-llama-baseline-15-epochs\")\n",
|
129 |
+
"\n",
|
130 |
+
"# Preprocessing function\n",
|
131 |
+
"def preprocess_function(examples):\n",
|
132 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
133 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
134 |
+
" return tokenizer(\n",
|
135 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
136 |
+
" )\n",
|
137 |
+
"\n",
|
138 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
139 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
140 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
141 |
+
]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"cell_type": "code",
|
145 |
+
"execution_count": 5,
|
146 |
+
"metadata": {},
|
147 |
+
"outputs": [
|
148 |
+
{
|
149 |
+
"name": "stderr",
|
150 |
+
"output_type": "stream",
|
151 |
+
"text": [
|
152 |
+
"/tmp/ipykernel_523735/825480179.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",
|
153 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
154 |
+
]
|
155 |
+
},
|
156 |
+
{
|
157 |
+
"data": {
|
158 |
+
"text/plain": [
|
159 |
+
"LlamaClassificationModel(\n",
|
160 |
+
" (base_model): LlamaModel(\n",
|
161 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
162 |
+
" (layers): ModuleList(\n",
|
163 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
164 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
165 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
166 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
167 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
168 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
169 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
170 |
+
" )\n",
|
171 |
+
" (mlp): LlamaMLP(\n",
|
172 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
173 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
174 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
175 |
+
" (act_fn): SiLU()\n",
|
176 |
+
" )\n",
|
177 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
178 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
179 |
+
" )\n",
|
180 |
+
" )\n",
|
181 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
182 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
183 |
+
" )\n",
|
184 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
185 |
+
")"
|
186 |
+
]
|
187 |
+
},
|
188 |
+
"execution_count": 5,
|
189 |
+
"metadata": {},
|
190 |
+
"output_type": "execute_result"
|
191 |
+
}
|
192 |
+
],
|
193 |
+
"source": [
|
194 |
+
"classification_head_path = hf_hub_download(\n",
|
195 |
+
" repo_id=\"ppak10/defect-classification-llama-baseline-15-epochs\",\n",
|
196 |
+
" repo_type=\"model\",\n",
|
197 |
+
" filename=\"classification_head.pt\"\n",
|
198 |
+
")\n",
|
199 |
+
"\n",
|
200 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
201 |
+
"model.eval() # Set the model to evaluation mode"
|
202 |
+
]
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"cell_type": "code",
|
206 |
+
"execution_count": 6,
|
207 |
+
"metadata": {},
|
208 |
+
"outputs": [
|
209 |
+
{
|
210 |
+
"name": "stderr",
|
211 |
+
"output_type": "stream",
|
212 |
+
"text": [
|
213 |
+
"100%|ββββββββββ| 1133/1133 [28:26<00:00, 1.51s/it]"
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"name": "stdout",
|
218 |
+
"output_type": "stream",
|
219 |
+
"text": [
|
220 |
+
"Overall Accuracy: 0.9294101414289011\n"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"name": "stderr",
|
225 |
+
"output_type": "stream",
|
226 |
+
"text": [
|
227 |
+
"\n"
|
228 |
+
]
|
229 |
+
}
|
230 |
+
],
|
231 |
+
"source": [
|
232 |
+
"# Ensure the model is on the GPU\n",
|
233 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
234 |
+
"model = model.to(device)\n",
|
235 |
+
"\n",
|
236 |
+
"# Define the batch size\n",
|
237 |
+
"batch_size = 64\n",
|
238 |
+
"\n",
|
239 |
+
"# Create a DataLoader for the validation dataset\n",
|
240 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
241 |
+
"\n",
|
242 |
+
"def label_to_classifications_batch(labels):\n",
|
243 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
244 |
+
" \n",
|
245 |
+
" results = []\n",
|
246 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
247 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
248 |
+
" results.append(result)\n",
|
249 |
+
" return results\n",
|
250 |
+
"\n",
|
251 |
+
"accuracy_total = 0\n",
|
252 |
+
"\n",
|
253 |
+
"# Process the validation dataset in batches\n",
|
254 |
+
"for batch in tqdm(validation_loader):\n",
|
255 |
+
" texts = batch[\"text\"]\n",
|
256 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
257 |
+
"\n",
|
258 |
+
" # Move labels to GPU\n",
|
259 |
+
" # print(np.array(labels))\n",
|
260 |
+
" labels = torch.tensor(labels).to(device)\n",
|
261 |
+
"\n",
|
262 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
263 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
264 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
265 |
+
"\n",
|
266 |
+
" # Perform inference\n",
|
267 |
+
" outputs = model(**inputs)\n",
|
268 |
+
"\n",
|
269 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
270 |
+
" logits = outputs[\"logits\"]\n",
|
271 |
+
" probs = torch.sigmoid(logits)\n",
|
272 |
+
"\n",
|
273 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
274 |
+
" preds = (probs > 0.5).int()\n",
|
275 |
+
"\n",
|
276 |
+
" # Compute accuracy for the batch\n",
|
277 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
278 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
279 |
+
"\n",
|
280 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
281 |
+
"\n",
|
282 |
+
"# Calculate overall accuracy\n",
|
283 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
284 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
285 |
+
]
|
286 |
+
}
|
287 |
+
],
|
288 |
+
"metadata": {
|
289 |
+
"kernelspec": {
|
290 |
+
"display_name": "venv",
|
291 |
+
"language": "python",
|
292 |
+
"name": "python3"
|
293 |
+
},
|
294 |
+
"language_info": {
|
295 |
+
"codemirror_mode": {
|
296 |
+
"name": "ipython",
|
297 |
+
"version": 3
|
298 |
+
},
|
299 |
+
"file_extension": ".py",
|
300 |
+
"mimetype": "text/x-python",
|
301 |
+
"name": "python",
|
302 |
+
"nbconvert_exporter": "python",
|
303 |
+
"pygments_lexer": "ipython3",
|
304 |
+
"version": "3.10.12"
|
305 |
+
}
|
306 |
+
},
|
307 |
+
"nbformat": 4,
|
308 |
+
"nbformat_minor": 2
|
309 |
+
}
|
notebooks/llama_baseline_20_epochs.ipynb
ADDED
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.llama import LlamaClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"LlamaClassificationModel(\n",
|
66 |
+
" (base_model): LlamaModel(\n",
|
67 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
68 |
+
" (layers): ModuleList(\n",
|
69 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
70 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
71 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
72 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
73 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
74 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
75 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
76 |
+
" )\n",
|
77 |
+
" (mlp): LlamaMLP(\n",
|
78 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
79 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
80 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
81 |
+
" (act_fn): SiLU()\n",
|
82 |
+
" )\n",
|
83 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
84 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
85 |
+
" )\n",
|
86 |
+
" )\n",
|
87 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
88 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
89 |
+
" )\n",
|
90 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
91 |
+
")"
|
92 |
+
]
|
93 |
+
},
|
94 |
+
"execution_count": 3,
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "execute_result"
|
97 |
+
}
|
98 |
+
],
|
99 |
+
"source": [
|
100 |
+
"# Initialize the model\n",
|
101 |
+
"model = LlamaClassificationModel()\n",
|
102 |
+
"model.eval() # Set the model to evaluation mode"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 4,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [
|
110 |
+
{
|
111 |
+
"name": "stderr",
|
112 |
+
"output_type": "stream",
|
113 |
+
"text": [
|
114 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:12<00:00, 42630.89 examples/s]\n",
|
115 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 38759.75 examples/s]\n",
|
116 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 33709.45 examples/s]\n"
|
117 |
+
]
|
118 |
+
}
|
119 |
+
],
|
120 |
+
"source": [
|
121 |
+
"# Load dataset\n",
|
122 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
123 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
124 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
125 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
126 |
+
"\n",
|
127 |
+
"# Load the tokenizer\n",
|
128 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-llama-baseline-20-epochs\")\n",
|
129 |
+
"\n",
|
130 |
+
"# Preprocessing function\n",
|
131 |
+
"def preprocess_function(examples):\n",
|
132 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
133 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
134 |
+
" return tokenizer(\n",
|
135 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
136 |
+
" )\n",
|
137 |
+
"\n",
|
138 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
139 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
140 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
141 |
+
]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"cell_type": "code",
|
145 |
+
"execution_count": 5,
|
146 |
+
"metadata": {},
|
147 |
+
"outputs": [
|
148 |
+
{
|
149 |
+
"name": "stderr",
|
150 |
+
"output_type": "stream",
|
151 |
+
"text": [
|
152 |
+
"/tmp/ipykernel_2476361/1294288660.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",
|
153 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
154 |
+
]
|
155 |
+
},
|
156 |
+
{
|
157 |
+
"data": {
|
158 |
+
"text/plain": [
|
159 |
+
"LlamaClassificationModel(\n",
|
160 |
+
" (base_model): LlamaModel(\n",
|
161 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
162 |
+
" (layers): ModuleList(\n",
|
163 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
164 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
165 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
166 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
167 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
168 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
169 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
170 |
+
" )\n",
|
171 |
+
" (mlp): LlamaMLP(\n",
|
172 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
173 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
174 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
175 |
+
" (act_fn): SiLU()\n",
|
176 |
+
" )\n",
|
177 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
178 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
179 |
+
" )\n",
|
180 |
+
" )\n",
|
181 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
182 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
183 |
+
" )\n",
|
184 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
185 |
+
")"
|
186 |
+
]
|
187 |
+
},
|
188 |
+
"execution_count": 5,
|
189 |
+
"metadata": {},
|
190 |
+
"output_type": "execute_result"
|
191 |
+
}
|
192 |
+
],
|
193 |
+
"source": [
|
194 |
+
"classification_head_path = hf_hub_download(\n",
|
195 |
+
" repo_id=\"ppak10/defect-classification-llama-baseline-20-epochs\",\n",
|
196 |
+
" repo_type=\"model\",\n",
|
197 |
+
" filename=\"classification_head.pt\"\n",
|
198 |
+
")\n",
|
199 |
+
"\n",
|
200 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
201 |
+
"model.eval() # Set the model to evaluation mode"
|
202 |
+
]
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"cell_type": "code",
|
206 |
+
"execution_count": 6,
|
207 |
+
"metadata": {},
|
208 |
+
"outputs": [
|
209 |
+
{
|
210 |
+
"name": "stderr",
|
211 |
+
"output_type": "stream",
|
212 |
+
"text": [
|
213 |
+
"100%|ββββββββββ| 1133/1133 [1:00:48<00:00, 3.22s/it]"
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"name": "stdout",
|
218 |
+
"output_type": "stream",
|
219 |
+
"text": [
|
220 |
+
"Overall Accuracy: 0.9301931700606969\n"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"name": "stderr",
|
225 |
+
"output_type": "stream",
|
226 |
+
"text": [
|
227 |
+
"\n"
|
228 |
+
]
|
229 |
+
}
|
230 |
+
],
|
231 |
+
"source": [
|
232 |
+
"# Ensure the model is on the GPU\n",
|
233 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
234 |
+
"model = model.to(device)\n",
|
235 |
+
"\n",
|
236 |
+
"# Define the batch size\n",
|
237 |
+
"batch_size = 64\n",
|
238 |
+
"\n",
|
239 |
+
"# Create a DataLoader for the validation dataset\n",
|
240 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
241 |
+
"\n",
|
242 |
+
"def label_to_classifications_batch(labels):\n",
|
243 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
244 |
+
" \n",
|
245 |
+
" results = []\n",
|
246 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
247 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
248 |
+
" results.append(result)\n",
|
249 |
+
" return results\n",
|
250 |
+
"\n",
|
251 |
+
"accuracy_total = 0\n",
|
252 |
+
"\n",
|
253 |
+
"# Process the validation dataset in batches\n",
|
254 |
+
"for batch in tqdm(validation_loader):\n",
|
255 |
+
" texts = batch[\"text\"]\n",
|
256 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
257 |
+
"\n",
|
258 |
+
" # Move labels to GPU\n",
|
259 |
+
" # print(np.array(labels))\n",
|
260 |
+
" labels = torch.tensor(labels).to(device)\n",
|
261 |
+
"\n",
|
262 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
263 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
264 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
265 |
+
"\n",
|
266 |
+
" # Perform inference\n",
|
267 |
+
" outputs = model(**inputs)\n",
|
268 |
+
"\n",
|
269 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
270 |
+
" logits = outputs[\"logits\"]\n",
|
271 |
+
" probs = torch.sigmoid(logits)\n",
|
272 |
+
"\n",
|
273 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
274 |
+
" preds = (probs > 0.5).int()\n",
|
275 |
+
"\n",
|
276 |
+
" # Compute accuracy for the batch\n",
|
277 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
278 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
279 |
+
"\n",
|
280 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
281 |
+
"\n",
|
282 |
+
"# Calculate overall accuracy\n",
|
283 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
284 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
285 |
+
]
|
286 |
+
}
|
287 |
+
],
|
288 |
+
"metadata": {
|
289 |
+
"kernelspec": {
|
290 |
+
"display_name": "venv",
|
291 |
+
"language": "python",
|
292 |
+
"name": "python3"
|
293 |
+
},
|
294 |
+
"language_info": {
|
295 |
+
"codemirror_mode": {
|
296 |
+
"name": "ipython",
|
297 |
+
"version": 3
|
298 |
+
},
|
299 |
+
"file_extension": ".py",
|
300 |
+
"mimetype": "text/x-python",
|
301 |
+
"name": "python",
|
302 |
+
"nbconvert_exporter": "python",
|
303 |
+
"pygments_lexer": "ipython3",
|
304 |
+
"version": "3.10.16"
|
305 |
+
}
|
306 |
+
},
|
307 |
+
"nbformat": 4,
|
308 |
+
"nbformat_minor": 2
|
309 |
+
}
|
notebooks/llama_baseline_20_epochs_prompt_input.ipynb
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.llama import LlamaClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"LlamaClassificationModel(\n",
|
66 |
+
" (base_model): LlamaModel(\n",
|
67 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
68 |
+
" (layers): ModuleList(\n",
|
69 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
70 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
71 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
72 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
73 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
74 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
75 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
76 |
+
" )\n",
|
77 |
+
" (mlp): LlamaMLP(\n",
|
78 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
79 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
80 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
81 |
+
" (act_fn): SiLU()\n",
|
82 |
+
" )\n",
|
83 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
84 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
85 |
+
" )\n",
|
86 |
+
" )\n",
|
87 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
88 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
89 |
+
" )\n",
|
90 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
91 |
+
")"
|
92 |
+
]
|
93 |
+
},
|
94 |
+
"execution_count": 3,
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "execute_result"
|
97 |
+
}
|
98 |
+
],
|
99 |
+
"source": [
|
100 |
+
"# Initialize the model\n",
|
101 |
+
"model = LlamaClassificationModel()\n",
|
102 |
+
"model.eval() # Set the model to evaluation mode"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 4,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [],
|
110 |
+
"source": [
|
111 |
+
"# Load dataset\n",
|
112 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
113 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
114 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
115 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
116 |
+
"\n",
|
117 |
+
"# Load the tokenizer\n",
|
118 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-llama-baseline-20-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# Preprocessing function\n",
|
121 |
+
"def preprocess_function(examples):\n",
|
122 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
123 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
124 |
+
" return tokenizer(\n",
|
125 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
126 |
+
" )\n",
|
127 |
+
"\n",
|
128 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
129 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
130 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
131 |
+
]
|
132 |
+
},
|
133 |
+
{
|
134 |
+
"cell_type": "code",
|
135 |
+
"execution_count": 5,
|
136 |
+
"metadata": {},
|
137 |
+
"outputs": [
|
138 |
+
{
|
139 |
+
"name": "stderr",
|
140 |
+
"output_type": "stream",
|
141 |
+
"text": [
|
142 |
+
"/tmp/ipykernel_1931069/1294288660.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",
|
143 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
144 |
+
]
|
145 |
+
},
|
146 |
+
{
|
147 |
+
"data": {
|
148 |
+
"text/plain": [
|
149 |
+
"LlamaClassificationModel(\n",
|
150 |
+
" (base_model): LlamaModel(\n",
|
151 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
152 |
+
" (layers): ModuleList(\n",
|
153 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
154 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
155 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
156 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
157 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
158 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
159 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
160 |
+
" )\n",
|
161 |
+
" (mlp): LlamaMLP(\n",
|
162 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
163 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
164 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
165 |
+
" (act_fn): SiLU()\n",
|
166 |
+
" )\n",
|
167 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
168 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
169 |
+
" )\n",
|
170 |
+
" )\n",
|
171 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
172 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
173 |
+
" )\n",
|
174 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
175 |
+
")"
|
176 |
+
]
|
177 |
+
},
|
178 |
+
"execution_count": 5,
|
179 |
+
"metadata": {},
|
180 |
+
"output_type": "execute_result"
|
181 |
+
}
|
182 |
+
],
|
183 |
+
"source": [
|
184 |
+
"classification_head_path = hf_hub_download(\n",
|
185 |
+
" repo_id=\"ppak10/defect-classification-llama-baseline-20-epochs\",\n",
|
186 |
+
" repo_type=\"model\",\n",
|
187 |
+
" filename=\"classification_head.pt\"\n",
|
188 |
+
")\n",
|
189 |
+
"\n",
|
190 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
191 |
+
"model.eval() # Set the model to evaluation mode"
|
192 |
+
]
|
193 |
+
},
|
194 |
+
{
|
195 |
+
"cell_type": "code",
|
196 |
+
"execution_count": 6,
|
197 |
+
"metadata": {},
|
198 |
+
"outputs": [
|
199 |
+
{
|
200 |
+
"name": "stderr",
|
201 |
+
"output_type": "stream",
|
202 |
+
"text": [
|
203 |
+
"100%|ββββββββββ| 11325/11325 [6:18:13<00:00, 2.00s/it] "
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"name": "stdout",
|
208 |
+
"output_type": "stream",
|
209 |
+
"text": [
|
210 |
+
"Overall Accuracy: 0.4907985512251359\n"
|
211 |
+
]
|
212 |
+
},
|
213 |
+
{
|
214 |
+
"name": "stderr",
|
215 |
+
"output_type": "stream",
|
216 |
+
"text": [
|
217 |
+
"\n"
|
218 |
+
]
|
219 |
+
}
|
220 |
+
],
|
221 |
+
"source": [
|
222 |
+
"# Ensure the model is on the GPU\n",
|
223 |
+
"device = torch.device(\"cuda:2\" if torch.cuda.is_available() else \"cpu\")\n",
|
224 |
+
"model = model.to(device)\n",
|
225 |
+
"\n",
|
226 |
+
"# Define the batch size\n",
|
227 |
+
"batch_size = 64\n",
|
228 |
+
"\n",
|
229 |
+
"# Create a DataLoader for the validation dataset\n",
|
230 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
231 |
+
"\n",
|
232 |
+
"def label_to_classifications_batch(labels):\n",
|
233 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
234 |
+
" \n",
|
235 |
+
" results = []\n",
|
236 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
237 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
238 |
+
" results.append(result)\n",
|
239 |
+
" return results\n",
|
240 |
+
"\n",
|
241 |
+
"accuracy_total = 0\n",
|
242 |
+
"\n",
|
243 |
+
"# Process the validation dataset in batches\n",
|
244 |
+
"for batch in tqdm(validation_loader):\n",
|
245 |
+
" texts = batch[\"text\"]\n",
|
246 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
247 |
+
"\n",
|
248 |
+
" # Move labels to GPU\n",
|
249 |
+
" # print(np.array(labels))\n",
|
250 |
+
" labels = torch.tensor(labels).to(device)\n",
|
251 |
+
"\n",
|
252 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
253 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
254 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
255 |
+
"\n",
|
256 |
+
" # Perform inference\n",
|
257 |
+
" outputs = model(**inputs)\n",
|
258 |
+
"\n",
|
259 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
260 |
+
" logits = outputs[\"logits\"]\n",
|
261 |
+
" probs = torch.sigmoid(logits)\n",
|
262 |
+
"\n",
|
263 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
264 |
+
" preds = (probs > 0.5).int()\n",
|
265 |
+
"\n",
|
266 |
+
" # Compute accuracy for the batch\n",
|
267 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
268 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
269 |
+
"\n",
|
270 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
271 |
+
"\n",
|
272 |
+
"# Calculate overall accuracy\n",
|
273 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
274 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
275 |
+
]
|
276 |
+
}
|
277 |
+
],
|
278 |
+
"metadata": {
|
279 |
+
"kernelspec": {
|
280 |
+
"display_name": "venv",
|
281 |
+
"language": "python",
|
282 |
+
"name": "python3"
|
283 |
+
},
|
284 |
+
"language_info": {
|
285 |
+
"codemirror_mode": {
|
286 |
+
"name": "ipython",
|
287 |
+
"version": 3
|
288 |
+
},
|
289 |
+
"file_extension": ".py",
|
290 |
+
"mimetype": "text/x-python",
|
291 |
+
"name": "python",
|
292 |
+
"nbconvert_exporter": "python",
|
293 |
+
"pygments_lexer": "ipython3",
|
294 |
+
"version": "3.10.12"
|
295 |
+
}
|
296 |
+
},
|
297 |
+
"nbformat": 4,
|
298 |
+
"nbformat_minor": 2
|
299 |
+
}
|
notebooks/llama_baseline_25_epochs.ipynb
ADDED
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.llama import LlamaClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"LlamaClassificationModel(\n",
|
66 |
+
" (base_model): LlamaModel(\n",
|
67 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
68 |
+
" (layers): ModuleList(\n",
|
69 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
70 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
71 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
72 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
73 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
74 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
75 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
76 |
+
" )\n",
|
77 |
+
" (mlp): LlamaMLP(\n",
|
78 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
79 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
80 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
81 |
+
" (act_fn): SiLU()\n",
|
82 |
+
" )\n",
|
83 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
84 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
85 |
+
" )\n",
|
86 |
+
" )\n",
|
87 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
88 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
89 |
+
" )\n",
|
90 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
91 |
+
")"
|
92 |
+
]
|
93 |
+
},
|
94 |
+
"execution_count": 3,
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "execute_result"
|
97 |
+
}
|
98 |
+
],
|
99 |
+
"source": [
|
100 |
+
"# Initialize the model\n",
|
101 |
+
"model = LlamaClassificationModel()\n",
|
102 |
+
"model.eval() # Set the model to evaluation mode"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 4,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [
|
110 |
+
{
|
111 |
+
"name": "stderr",
|
112 |
+
"output_type": "stream",
|
113 |
+
"text": [
|
114 |
+
"Generating train split: 100%|ββββββββββ| 41311472/41311472 [00:15<00:00, 2690478.17 examples/s]\n",
|
115 |
+
"Generating test split: 100%|ββββββββββ| 1739424/1739424 [00:00<00:00, 2484578.15 examples/s]\n",
|
116 |
+
"Generating validation split: 100%|ββββββββββ| 797225/797225 [00:00<00:00, 3545459.08 examples/s]\n",
|
117 |
+
"Generating train_baseline split: 100%|ββββββββββ| 543572/543572 [00:00<00:00, 3008760.36 examples/s]\n",
|
118 |
+
"Generating test_baseline split: 100%|ββββββββββ| 108714/108714 [00:00<00:00, 2935515.96 examples/s]\n",
|
119 |
+
"Generating validation_baseline split: 100%|ββββββββββ| 72475/72475 [00:00<00:00, 3516602.84 examples/s]\n",
|
120 |
+
"Generating train_prompt split: 100%|ββββββββββ| 40767900/40767900 [00:17<00:00, 2377759.08 examples/s]\n",
|
121 |
+
"Generating test_prompt split: 100%|ββββββββββ| 1630710/1630710 [00:00<00:00, 3067395.34 examples/s]\n",
|
122 |
+
"Generating validation_prompt split: 100%|ββββββββββ| 724750/724750 [00:00<00:00, 2854517.94 examples/s]\n",
|
123 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:02<00:00, 206327.92 examples/s]\n",
|
124 |
+
"Map (num_proc=32): 100%|οΏ½οΏ½οΏ½βββββββββ| 108714/108714 [00:00<00:00, 116935.53 examples/s]\n",
|
125 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:00<00:00, 100822.54 examples/s]\n"
|
126 |
+
]
|
127 |
+
}
|
128 |
+
],
|
129 |
+
"source": [
|
130 |
+
"# Load dataset\n",
|
131 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
132 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
133 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
134 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
135 |
+
"\n",
|
136 |
+
"# Load the tokenizer\n",
|
137 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-llama-baseline-25-epochs\")\n",
|
138 |
+
"\n",
|
139 |
+
"# Preprocessing function\n",
|
140 |
+
"def preprocess_function(examples):\n",
|
141 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
142 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
143 |
+
" return tokenizer(\n",
|
144 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
145 |
+
" )\n",
|
146 |
+
"\n",
|
147 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
148 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
149 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
150 |
+
]
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"cell_type": "code",
|
154 |
+
"execution_count": 5,
|
155 |
+
"metadata": {},
|
156 |
+
"outputs": [
|
157 |
+
{
|
158 |
+
"name": "stderr",
|
159 |
+
"output_type": "stream",
|
160 |
+
"text": [
|
161 |
+
"/tmp/ipykernel_3265701/758947514.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",
|
162 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
163 |
+
]
|
164 |
+
},
|
165 |
+
{
|
166 |
+
"data": {
|
167 |
+
"text/plain": [
|
168 |
+
"LlamaClassificationModel(\n",
|
169 |
+
" (base_model): LlamaModel(\n",
|
170 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
171 |
+
" (layers): ModuleList(\n",
|
172 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
173 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
174 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
175 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
176 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
177 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
178 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
179 |
+
" )\n",
|
180 |
+
" (mlp): LlamaMLP(\n",
|
181 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
182 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
183 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
184 |
+
" (act_fn): SiLU()\n",
|
185 |
+
" )\n",
|
186 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
187 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
188 |
+
" )\n",
|
189 |
+
" )\n",
|
190 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
191 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
192 |
+
" )\n",
|
193 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
194 |
+
")"
|
195 |
+
]
|
196 |
+
},
|
197 |
+
"execution_count": 5,
|
198 |
+
"metadata": {},
|
199 |
+
"output_type": "execute_result"
|
200 |
+
}
|
201 |
+
],
|
202 |
+
"source": [
|
203 |
+
"classification_head_path = hf_hub_download(\n",
|
204 |
+
" repo_id=\"ppak10/defect-classification-llama-baseline-25-epochs\",\n",
|
205 |
+
" repo_type=\"model\",\n",
|
206 |
+
" filename=\"classification_head.pt\"\n",
|
207 |
+
")\n",
|
208 |
+
"\n",
|
209 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
210 |
+
"model.eval() # Set the model to evaluation mode"
|
211 |
+
]
|
212 |
+
},
|
213 |
+
{
|
214 |
+
"cell_type": "code",
|
215 |
+
"execution_count": 6,
|
216 |
+
"metadata": {},
|
217 |
+
"outputs": [
|
218 |
+
{
|
219 |
+
"name": "stderr",
|
220 |
+
"output_type": "stream",
|
221 |
+
"text": [
|
222 |
+
"100%|ββββββββββ| 1133/1133 [28:21<00:00, 1.50s/it]"
|
223 |
+
]
|
224 |
+
},
|
225 |
+
{
|
226 |
+
"name": "stdout",
|
227 |
+
"output_type": "stream",
|
228 |
+
"text": [
|
229 |
+
"Overall Accuracy: 0.9368023456364264\n"
|
230 |
+
]
|
231 |
+
},
|
232 |
+
{
|
233 |
+
"name": "stderr",
|
234 |
+
"output_type": "stream",
|
235 |
+
"text": [
|
236 |
+
"\n"
|
237 |
+
]
|
238 |
+
}
|
239 |
+
],
|
240 |
+
"source": [
|
241 |
+
"# Ensure the model is on the GPU\n",
|
242 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
243 |
+
"model = model.to(device)\n",
|
244 |
+
"\n",
|
245 |
+
"# Define the batch size\n",
|
246 |
+
"batch_size = 64\n",
|
247 |
+
"\n",
|
248 |
+
"# Create a DataLoader for the validation dataset\n",
|
249 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
250 |
+
"\n",
|
251 |
+
"def label_to_classifications_batch(labels):\n",
|
252 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
253 |
+
" \n",
|
254 |
+
" results = []\n",
|
255 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
256 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
257 |
+
" results.append(result)\n",
|
258 |
+
" return results\n",
|
259 |
+
"\n",
|
260 |
+
"accuracy_total = 0\n",
|
261 |
+
"\n",
|
262 |
+
"# Process the validation dataset in batches\n",
|
263 |
+
"for batch in tqdm(validation_loader):\n",
|
264 |
+
" texts = batch[\"text\"]\n",
|
265 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
266 |
+
"\n",
|
267 |
+
" # Move labels to GPU\n",
|
268 |
+
" # print(np.array(labels))\n",
|
269 |
+
" labels = torch.tensor(labels).to(device)\n",
|
270 |
+
"\n",
|
271 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
272 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
273 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
274 |
+
"\n",
|
275 |
+
" # Perform inference\n",
|
276 |
+
" outputs = model(**inputs)\n",
|
277 |
+
"\n",
|
278 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
279 |
+
" logits = outputs[\"logits\"]\n",
|
280 |
+
" probs = torch.sigmoid(logits)\n",
|
281 |
+
"\n",
|
282 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
283 |
+
" preds = (probs > 0.5).int()\n",
|
284 |
+
"\n",
|
285 |
+
" # Compute accuracy for the batch\n",
|
286 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
287 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
288 |
+
"\n",
|
289 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
290 |
+
"\n",
|
291 |
+
"# Calculate overall accuracy\n",
|
292 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
293 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
294 |
+
]
|
295 |
+
}
|
296 |
+
],
|
297 |
+
"metadata": {
|
298 |
+
"kernelspec": {
|
299 |
+
"display_name": "venv",
|
300 |
+
"language": "python",
|
301 |
+
"name": "python3"
|
302 |
+
},
|
303 |
+
"language_info": {
|
304 |
+
"codemirror_mode": {
|
305 |
+
"name": "ipython",
|
306 |
+
"version": 3
|
307 |
+
},
|
308 |
+
"file_extension": ".py",
|
309 |
+
"mimetype": "text/x-python",
|
310 |
+
"name": "python",
|
311 |
+
"nbconvert_exporter": "python",
|
312 |
+
"pygments_lexer": "ipython3",
|
313 |
+
"version": "3.10.12"
|
314 |
+
}
|
315 |
+
},
|
316 |
+
"nbformat": 4,
|
317 |
+
"nbformat_minor": 2
|
318 |
+
}
|
notebooks/llama_prompt_0.5_epochs.ipynb
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.llama import LlamaClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"LlamaClassificationModel(\n",
|
66 |
+
" (base_model): LlamaModel(\n",
|
67 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
68 |
+
" (layers): ModuleList(\n",
|
69 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
70 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
71 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
72 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
73 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
74 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
75 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
76 |
+
" )\n",
|
77 |
+
" (mlp): LlamaMLP(\n",
|
78 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
79 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
80 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
81 |
+
" (act_fn): SiLU()\n",
|
82 |
+
" )\n",
|
83 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
84 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
85 |
+
" )\n",
|
86 |
+
" )\n",
|
87 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
88 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
89 |
+
" )\n",
|
90 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
91 |
+
")"
|
92 |
+
]
|
93 |
+
},
|
94 |
+
"execution_count": 3,
|
95 |
+
"metadata": {},
|
96 |
+
"output_type": "execute_result"
|
97 |
+
}
|
98 |
+
],
|
99 |
+
"source": [
|
100 |
+
"# Initialize the model\n",
|
101 |
+
"model = LlamaClassificationModel()\n",
|
102 |
+
"model.eval() # Set the model to evaluation mode"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "code",
|
107 |
+
"execution_count": 4,
|
108 |
+
"metadata": {},
|
109 |
+
"outputs": [],
|
110 |
+
"source": [
|
111 |
+
"# Load dataset\n",
|
112 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
113 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
114 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
115 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
116 |
+
"\n",
|
117 |
+
"# Load the tokenizer\n",
|
118 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-llama-prompt-0.5-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# Preprocessing function\n",
|
121 |
+
"def preprocess_function(examples):\n",
|
122 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
123 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
124 |
+
" return tokenizer(\n",
|
125 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
126 |
+
" )\n",
|
127 |
+
"\n",
|
128 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
129 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
130 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
131 |
+
]
|
132 |
+
},
|
133 |
+
{
|
134 |
+
"cell_type": "code",
|
135 |
+
"execution_count": 5,
|
136 |
+
"metadata": {},
|
137 |
+
"outputs": [
|
138 |
+
{
|
139 |
+
"name": "stderr",
|
140 |
+
"output_type": "stream",
|
141 |
+
"text": [
|
142 |
+
"/tmp/ipykernel_459962/2327094420.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",
|
143 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
144 |
+
]
|
145 |
+
},
|
146 |
+
{
|
147 |
+
"data": {
|
148 |
+
"text/plain": [
|
149 |
+
"LlamaClassificationModel(\n",
|
150 |
+
" (base_model): LlamaModel(\n",
|
151 |
+
" (embed_tokens): Embedding(128256, 2048)\n",
|
152 |
+
" (layers): ModuleList(\n",
|
153 |
+
" (0-15): 16 x LlamaDecoderLayer(\n",
|
154 |
+
" (self_attn): LlamaSdpaAttention(\n",
|
155 |
+
" (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
156 |
+
" (k_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
157 |
+
" (v_proj): Linear(in_features=2048, out_features=512, bias=False)\n",
|
158 |
+
" (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
|
159 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
160 |
+
" )\n",
|
161 |
+
" (mlp): LlamaMLP(\n",
|
162 |
+
" (gate_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
163 |
+
" (up_proj): Linear(in_features=2048, out_features=8192, bias=False)\n",
|
164 |
+
" (down_proj): Linear(in_features=8192, out_features=2048, bias=False)\n",
|
165 |
+
" (act_fn): SiLU()\n",
|
166 |
+
" )\n",
|
167 |
+
" (input_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
168 |
+
" (post_attention_layernorm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
169 |
+
" )\n",
|
170 |
+
" )\n",
|
171 |
+
" (norm): LlamaRMSNorm((2048,), eps=1e-05)\n",
|
172 |
+
" (rotary_emb): LlamaRotaryEmbedding()\n",
|
173 |
+
" )\n",
|
174 |
+
" (classifier): Linear(in_features=2048, out_features=4, bias=True)\n",
|
175 |
+
")"
|
176 |
+
]
|
177 |
+
},
|
178 |
+
"execution_count": 5,
|
179 |
+
"metadata": {},
|
180 |
+
"output_type": "execute_result"
|
181 |
+
}
|
182 |
+
],
|
183 |
+
"source": [
|
184 |
+
"classification_head_path = hf_hub_download(\n",
|
185 |
+
" repo_id=\"ppak10/defect-classification-llama-prompt-0.5-epochs\",\n",
|
186 |
+
" repo_type=\"model\",\n",
|
187 |
+
" filename=\"classification_head.pt\"\n",
|
188 |
+
")\n",
|
189 |
+
"\n",
|
190 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
191 |
+
"model.eval() # Set the model to evaluation mode"
|
192 |
+
]
|
193 |
+
},
|
194 |
+
{
|
195 |
+
"cell_type": "code",
|
196 |
+
"execution_count": 6,
|
197 |
+
"metadata": {},
|
198 |
+
"outputs": [
|
199 |
+
{
|
200 |
+
"name": "stderr",
|
201 |
+
"output_type": "stream",
|
202 |
+
"text": [
|
203 |
+
"100%|ββββββββββ| 1416/1416 [8:35:26<00:00, 21.84s/it] "
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"name": "stdout",
|
208 |
+
"output_type": "stream",
|
209 |
+
"text": [
|
210 |
+
"Overall Accuracy: 0.7351959296326342\n"
|
211 |
+
]
|
212 |
+
},
|
213 |
+
{
|
214 |
+
"name": "stderr",
|
215 |
+
"output_type": "stream",
|
216 |
+
"text": [
|
217 |
+
"\n"
|
218 |
+
]
|
219 |
+
}
|
220 |
+
],
|
221 |
+
"source": [
|
222 |
+
"# Ensure the model is on the GPU\n",
|
223 |
+
"device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n",
|
224 |
+
"model = model.to(device)\n",
|
225 |
+
"\n",
|
226 |
+
"# Define the batch size\n",
|
227 |
+
"batch_size = 512\n",
|
228 |
+
"\n",
|
229 |
+
"# Create a DataLoader for the validation dataset\n",
|
230 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
231 |
+
"\n",
|
232 |
+
"def label_to_classifications_batch(labels):\n",
|
233 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
234 |
+
" \n",
|
235 |
+
" results = []\n",
|
236 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
237 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
238 |
+
" results.append(result)\n",
|
239 |
+
" return results\n",
|
240 |
+
"\n",
|
241 |
+
"accuracy_total = 0\n",
|
242 |
+
"\n",
|
243 |
+
"# Process the validation dataset in batches\n",
|
244 |
+
"for batch in tqdm(validation_loader):\n",
|
245 |
+
" texts = batch[\"text\"]\n",
|
246 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
247 |
+
"\n",
|
248 |
+
" # Move labels to GPU\n",
|
249 |
+
" # print(np.array(labels))\n",
|
250 |
+
" labels = torch.tensor(labels).to(device)\n",
|
251 |
+
"\n",
|
252 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
253 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
254 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
255 |
+
"\n",
|
256 |
+
" # Perform inference\n",
|
257 |
+
" outputs = model(**inputs)\n",
|
258 |
+
"\n",
|
259 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
260 |
+
" logits = outputs[\"logits\"]\n",
|
261 |
+
" probs = torch.sigmoid(logits)\n",
|
262 |
+
"\n",
|
263 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
264 |
+
" preds = (probs > 0.5).int()\n",
|
265 |
+
"\n",
|
266 |
+
" # Compute accuracy for the batch\n",
|
267 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
268 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
269 |
+
"\n",
|
270 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
271 |
+
"\n",
|
272 |
+
"# Calculate overall accuracy\n",
|
273 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
274 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
275 |
+
]
|
276 |
+
}
|
277 |
+
],
|
278 |
+
"metadata": {
|
279 |
+
"kernelspec": {
|
280 |
+
"display_name": "venv",
|
281 |
+
"language": "python",
|
282 |
+
"name": "python3"
|
283 |
+
},
|
284 |
+
"language_info": {
|
285 |
+
"codemirror_mode": {
|
286 |
+
"name": "ipython",
|
287 |
+
"version": 3
|
288 |
+
},
|
289 |
+
"file_extension": ".py",
|
290 |
+
"mimetype": "text/x-python",
|
291 |
+
"name": "python",
|
292 |
+
"nbconvert_exporter": "python",
|
293 |
+
"pygments_lexer": "ipython3",
|
294 |
+
"version": "3.10.12"
|
295 |
+
}
|
296 |
+
},
|
297 |
+
"nbformat": 4,
|
298 |
+
"nbformat_minor": 2
|
299 |
+
}
|
notebooks/scibert_baseline_05_epochs.ipynb
ADDED
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-baseline-05-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [
|
129 |
+
{
|
130 |
+
"name": "stderr",
|
131 |
+
"output_type": "stream",
|
132 |
+
"text": [
|
133 |
+
"Generating train split: 41311472 examples [00:36, 1125978.62 examples/s]\n",
|
134 |
+
"Generating test split: 1739424 examples [00:01, 1126572.80 examples/s]\n",
|
135 |
+
"Generating validation split: 797225 examples [00:00, 1612244.91 examples/s]\n",
|
136 |
+
"Generating train_baseline split: 543572 examples [00:00, 1922772.39 examples/s]\n",
|
137 |
+
"Generating test_baseline split: 108714 examples [00:00, 1808065.15 examples/s]\n",
|
138 |
+
"Generating validation_baseline split: 72475 examples [00:00, 2011155.84 examples/s]\n",
|
139 |
+
"Generating train_prompt split: 40767900 examples [00:34, 1185073.83 examples/s]\n",
|
140 |
+
"Generating test_prompt split: 1630710 examples [00:01, 1136271.75 examples/s]\n",
|
141 |
+
"Generating validation_prompt split: 724750 examples [00:00, 1768766.65 examples/s]\n",
|
142 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:09<00:00, 55250.96 examples/s]\n",
|
143 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 47720.21 examples/s]\n",
|
144 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:01<00:00, 45154.53 examples/s]\n"
|
145 |
+
]
|
146 |
+
}
|
147 |
+
],
|
148 |
+
"source": [
|
149 |
+
"# Load dataset\n",
|
150 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
151 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
152 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
153 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
154 |
+
"\n",
|
155 |
+
"# Load the tokenizer\n",
|
156 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-baseline-05-epochs\")\n",
|
157 |
+
"\n",
|
158 |
+
"# Preprocessing function\n",
|
159 |
+
"def preprocess_function(examples):\n",
|
160 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
161 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
162 |
+
" return tokenizer(\n",
|
163 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
164 |
+
" )\n",
|
165 |
+
"\n",
|
166 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
167 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
168 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
169 |
+
]
|
170 |
+
},
|
171 |
+
{
|
172 |
+
"cell_type": "markdown",
|
173 |
+
"metadata": {},
|
174 |
+
"source": [
|
175 |
+
"# With Pretrained Weights"
|
176 |
+
]
|
177 |
+
},
|
178 |
+
{
|
179 |
+
"cell_type": "code",
|
180 |
+
"execution_count": 5,
|
181 |
+
"metadata": {},
|
182 |
+
"outputs": [
|
183 |
+
{
|
184 |
+
"name": "stderr",
|
185 |
+
"output_type": "stream",
|
186 |
+
"text": [
|
187 |
+
"/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",
|
188 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
189 |
+
]
|
190 |
+
},
|
191 |
+
{
|
192 |
+
"data": {
|
193 |
+
"text/plain": [
|
194 |
+
"SciBertClassificationModel(\n",
|
195 |
+
" (base_model): BertModel(\n",
|
196 |
+
" (embeddings): BertEmbeddings(\n",
|
197 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
198 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
199 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
200 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
201 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
202 |
+
" )\n",
|
203 |
+
" (encoder): BertEncoder(\n",
|
204 |
+
" (layer): ModuleList(\n",
|
205 |
+
" (0-11): 12 x BertLayer(\n",
|
206 |
+
" (attention): BertAttention(\n",
|
207 |
+
" (self): BertSdpaSelfAttention(\n",
|
208 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
209 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
210 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
211 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
212 |
+
" )\n",
|
213 |
+
" (output): BertSelfOutput(\n",
|
214 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
215 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
216 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
217 |
+
" )\n",
|
218 |
+
" )\n",
|
219 |
+
" (intermediate): BertIntermediate(\n",
|
220 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
221 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
222 |
+
" )\n",
|
223 |
+
" (output): BertOutput(\n",
|
224 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
225 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" )\n",
|
229 |
+
" )\n",
|
230 |
+
" )\n",
|
231 |
+
" (pooler): BertPooler(\n",
|
232 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
233 |
+
" (activation): Tanh()\n",
|
234 |
+
" )\n",
|
235 |
+
" )\n",
|
236 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
237 |
+
")"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
"execution_count": 5,
|
241 |
+
"metadata": {},
|
242 |
+
"output_type": "execute_result"
|
243 |
+
}
|
244 |
+
],
|
245 |
+
"source": [
|
246 |
+
"classification_head_path = hf_hub_download(\n",
|
247 |
+
" repo_id=\"ppak10/defect-classification-scibert-baseline-05-epochs\",\n",
|
248 |
+
" repo_type=\"model\",\n",
|
249 |
+
" filename=\"classification_head.pt\"\n",
|
250 |
+
")\n",
|
251 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
252 |
+
"model.eval() # Set the model to evaluation mode"
|
253 |
+
]
|
254 |
+
},
|
255 |
+
{
|
256 |
+
"cell_type": "code",
|
257 |
+
"execution_count": 6,
|
258 |
+
"metadata": {},
|
259 |
+
"outputs": [
|
260 |
+
{
|
261 |
+
"name": "stderr",
|
262 |
+
"output_type": "stream",
|
263 |
+
"text": [
|
264 |
+
"100%|ββββββββββ| 142/142 [08:58<00:00, 3.79s/it]\n"
|
265 |
+
]
|
266 |
+
}
|
267 |
+
],
|
268 |
+
"source": [
|
269 |
+
"# Ensure the model is on the GPU\n",
|
270 |
+
"device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n",
|
271 |
+
"model = model.to(device)\n",
|
272 |
+
"\n",
|
273 |
+
"# Define the batch size\n",
|
274 |
+
"batch_size = 512\n",
|
275 |
+
"\n",
|
276 |
+
"# Create a DataLoader for the validation dataset\n",
|
277 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
278 |
+
"\n",
|
279 |
+
"def label_to_classifications_batch(labels):\n",
|
280 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
281 |
+
" \n",
|
282 |
+
" results = []\n",
|
283 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
284 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
285 |
+
" results.append(result)\n",
|
286 |
+
" return results\n",
|
287 |
+
"\n",
|
288 |
+
"accuracy_total = 0\n",
|
289 |
+
"\n",
|
290 |
+
"# Process the validation dataset in batches\n",
|
291 |
+
"for batch in tqdm(validation_loader):\n",
|
292 |
+
" texts = batch[\"text\"]\n",
|
293 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
294 |
+
"\n",
|
295 |
+
" # Move labels to GPU\n",
|
296 |
+
" # print(np.array(labels))\n",
|
297 |
+
" labels = torch.tensor(labels).to(device)\n",
|
298 |
+
"\n",
|
299 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
300 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
301 |
+
" inputs_kwargs = {}\n",
|
302 |
+
"\n",
|
303 |
+
" for key, value in inputs.items():\n",
|
304 |
+
" if key not in [\"token_type_ids\"]:\n",
|
305 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
306 |
+
"\n",
|
307 |
+
" # print(inputs_kwargs)\n",
|
308 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
309 |
+
"\n",
|
310 |
+
" # Perform inference\n",
|
311 |
+
" outputs = model(**inputs_kwargs)\n",
|
312 |
+
"\n",
|
313 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
314 |
+
" logits = outputs[\"logits\"]\n",
|
315 |
+
" probs = torch.sigmoid(logits)\n",
|
316 |
+
"\n",
|
317 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
318 |
+
" preds = (probs > 0.5).int()\n",
|
319 |
+
"\n",
|
320 |
+
" # Compute accuracy for the batch\n",
|
321 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
322 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
323 |
+
"\n",
|
324 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
325 |
+
"\n",
|
326 |
+
"# Calculate overall accuracy\n",
|
327 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
328 |
+
]
|
329 |
+
},
|
330 |
+
{
|
331 |
+
"cell_type": "code",
|
332 |
+
"execution_count": 7,
|
333 |
+
"metadata": {},
|
334 |
+
"outputs": [
|
335 |
+
{
|
336 |
+
"name": "stdout",
|
337 |
+
"output_type": "stream",
|
338 |
+
"text": [
|
339 |
+
"Overall Accuracy: 0.8829734390404521\n"
|
340 |
+
]
|
341 |
+
}
|
342 |
+
],
|
343 |
+
"source": [
|
344 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
345 |
+
]
|
346 |
+
}
|
347 |
+
],
|
348 |
+
"metadata": {
|
349 |
+
"kernelspec": {
|
350 |
+
"display_name": "venv",
|
351 |
+
"language": "python",
|
352 |
+
"name": "python3"
|
353 |
+
},
|
354 |
+
"language_info": {
|
355 |
+
"codemirror_mode": {
|
356 |
+
"name": "ipython",
|
357 |
+
"version": 3
|
358 |
+
},
|
359 |
+
"file_extension": ".py",
|
360 |
+
"mimetype": "text/x-python",
|
361 |
+
"name": "python",
|
362 |
+
"nbconvert_exporter": "python",
|
363 |
+
"pygments_lexer": "ipython3",
|
364 |
+
"version": "3.10.12"
|
365 |
+
}
|
366 |
+
},
|
367 |
+
"nbformat": 4,
|
368 |
+
"nbformat_minor": 2
|
369 |
+
}
|
notebooks/scibert_baseline_10_epochs.ipynb
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-baseline-10-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [],
|
129 |
+
"source": [
|
130 |
+
"# Load dataset\n",
|
131 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
132 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
133 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
134 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
135 |
+
"\n",
|
136 |
+
"# Load the tokenizer\n",
|
137 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-baseline-10-epochs\")\n",
|
138 |
+
"\n",
|
139 |
+
"# Preprocessing function\n",
|
140 |
+
"def preprocess_function(examples):\n",
|
141 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
142 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
143 |
+
" return tokenizer(\n",
|
144 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
145 |
+
" )\n",
|
146 |
+
"\n",
|
147 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
148 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
149 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
150 |
+
]
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"cell_type": "markdown",
|
154 |
+
"metadata": {},
|
155 |
+
"source": [
|
156 |
+
"# With Pretrained Weights"
|
157 |
+
]
|
158 |
+
},
|
159 |
+
{
|
160 |
+
"cell_type": "code",
|
161 |
+
"execution_count": 5,
|
162 |
+
"metadata": {},
|
163 |
+
"outputs": [
|
164 |
+
{
|
165 |
+
"name": "stderr",
|
166 |
+
"output_type": "stream",
|
167 |
+
"text": [
|
168 |
+
"/tmp/ipykernel_544573/1695838043.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",
|
169 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
170 |
+
]
|
171 |
+
},
|
172 |
+
{
|
173 |
+
"data": {
|
174 |
+
"text/plain": [
|
175 |
+
"SciBertClassificationModel(\n",
|
176 |
+
" (base_model): BertModel(\n",
|
177 |
+
" (embeddings): BertEmbeddings(\n",
|
178 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
179 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
180 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
181 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
182 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
183 |
+
" )\n",
|
184 |
+
" (encoder): BertEncoder(\n",
|
185 |
+
" (layer): ModuleList(\n",
|
186 |
+
" (0-11): 12 x BertLayer(\n",
|
187 |
+
" (attention): BertAttention(\n",
|
188 |
+
" (self): BertSdpaSelfAttention(\n",
|
189 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
190 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
191 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
193 |
+
" )\n",
|
194 |
+
" (output): BertSelfOutput(\n",
|
195 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
196 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" (intermediate): BertIntermediate(\n",
|
201 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
202 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
203 |
+
" )\n",
|
204 |
+
" (output): BertOutput(\n",
|
205 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
206 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
207 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
208 |
+
" )\n",
|
209 |
+
" )\n",
|
210 |
+
" )\n",
|
211 |
+
" )\n",
|
212 |
+
" (pooler): BertPooler(\n",
|
213 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
214 |
+
" (activation): Tanh()\n",
|
215 |
+
" )\n",
|
216 |
+
" )\n",
|
217 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
218 |
+
")"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
"execution_count": 5,
|
222 |
+
"metadata": {},
|
223 |
+
"output_type": "execute_result"
|
224 |
+
}
|
225 |
+
],
|
226 |
+
"source": [
|
227 |
+
"classification_head_path = hf_hub_download(\n",
|
228 |
+
" repo_id=\"ppak10/defect-classification-scibert-baseline-10-epochs\",\n",
|
229 |
+
" repo_type=\"model\",\n",
|
230 |
+
" filename=\"classification_head.pt\"\n",
|
231 |
+
")\n",
|
232 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
233 |
+
"model.eval() # Set the model to evaluation mode"
|
234 |
+
]
|
235 |
+
},
|
236 |
+
{
|
237 |
+
"cell_type": "code",
|
238 |
+
"execution_count": 6,
|
239 |
+
"metadata": {},
|
240 |
+
"outputs": [
|
241 |
+
{
|
242 |
+
"name": "stderr",
|
243 |
+
"output_type": "stream",
|
244 |
+
"text": [
|
245 |
+
"100%|ββββββββββ| 142/142 [06:14<00:00, 2.63s/it]\n"
|
246 |
+
]
|
247 |
+
}
|
248 |
+
],
|
249 |
+
"source": [
|
250 |
+
"# Ensure the model is on the GPU\n",
|
251 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
252 |
+
"model = model.to(device)\n",
|
253 |
+
"\n",
|
254 |
+
"# Define the batch size\n",
|
255 |
+
"batch_size = 512\n",
|
256 |
+
"\n",
|
257 |
+
"# Create a DataLoader for the validation dataset\n",
|
258 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
259 |
+
"\n",
|
260 |
+
"def label_to_classifications_batch(labels):\n",
|
261 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
262 |
+
" \n",
|
263 |
+
" results = []\n",
|
264 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
265 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
266 |
+
" results.append(result)\n",
|
267 |
+
" return results\n",
|
268 |
+
"\n",
|
269 |
+
"accuracy_total = 0\n",
|
270 |
+
"\n",
|
271 |
+
"# Process the validation dataset in batches\n",
|
272 |
+
"for batch in tqdm(validation_loader):\n",
|
273 |
+
" texts = batch[\"text\"]\n",
|
274 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
275 |
+
"\n",
|
276 |
+
" # Move labels to GPU\n",
|
277 |
+
" # print(np.array(labels))\n",
|
278 |
+
" labels = torch.tensor(labels).to(device)\n",
|
279 |
+
"\n",
|
280 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
281 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
282 |
+
" inputs_kwargs = {}\n",
|
283 |
+
"\n",
|
284 |
+
" for key, value in inputs.items():\n",
|
285 |
+
" if key not in [\"token_type_ids\"]:\n",
|
286 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
287 |
+
"\n",
|
288 |
+
" # print(inputs_kwargs)\n",
|
289 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
290 |
+
"\n",
|
291 |
+
" # Perform inference\n",
|
292 |
+
" outputs = model(**inputs_kwargs)\n",
|
293 |
+
"\n",
|
294 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
295 |
+
" logits = outputs[\"logits\"]\n",
|
296 |
+
" probs = torch.sigmoid(logits)\n",
|
297 |
+
"\n",
|
298 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
299 |
+
" preds = (probs > 0.5).int()\n",
|
300 |
+
"\n",
|
301 |
+
" # Compute accuracy for the batch\n",
|
302 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
303 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
304 |
+
"\n",
|
305 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
306 |
+
"\n",
|
307 |
+
"# Calculate overall accuracy\n",
|
308 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
309 |
+
]
|
310 |
+
},
|
311 |
+
{
|
312 |
+
"cell_type": "code",
|
313 |
+
"execution_count": 7,
|
314 |
+
"metadata": {},
|
315 |
+
"outputs": [
|
316 |
+
{
|
317 |
+
"name": "stdout",
|
318 |
+
"output_type": "stream",
|
319 |
+
"text": [
|
320 |
+
"Overall Accuracy: 0.8893066573916077\n"
|
321 |
+
]
|
322 |
+
}
|
323 |
+
],
|
324 |
+
"source": [
|
325 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
326 |
+
]
|
327 |
+
}
|
328 |
+
],
|
329 |
+
"metadata": {
|
330 |
+
"kernelspec": {
|
331 |
+
"display_name": "venv",
|
332 |
+
"language": "python",
|
333 |
+
"name": "python3"
|
334 |
+
},
|
335 |
+
"language_info": {
|
336 |
+
"codemirror_mode": {
|
337 |
+
"name": "ipython",
|
338 |
+
"version": 3
|
339 |
+
},
|
340 |
+
"file_extension": ".py",
|
341 |
+
"mimetype": "text/x-python",
|
342 |
+
"name": "python",
|
343 |
+
"nbconvert_exporter": "python",
|
344 |
+
"pygments_lexer": "ipython3",
|
345 |
+
"version": "3.10.12"
|
346 |
+
}
|
347 |
+
},
|
348 |
+
"nbformat": 4,
|
349 |
+
"nbformat_minor": 2
|
350 |
+
}
|
notebooks/scibert_baseline_15_epochs.ipynb
ADDED
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-baseline-15-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [
|
129 |
+
{
|
130 |
+
"name": "stderr",
|
131 |
+
"output_type": "stream",
|
132 |
+
"text": [
|
133 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:11<00:00, 49327.24 examples/s]\n",
|
134 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:03<00:00, 34150.44 examples/s]\n",
|
135 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 28571.85 examples/s]\n"
|
136 |
+
]
|
137 |
+
}
|
138 |
+
],
|
139 |
+
"source": [
|
140 |
+
"# Load dataset\n",
|
141 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
142 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
143 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
144 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
145 |
+
"\n",
|
146 |
+
"# Load the tokenizer\n",
|
147 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-baseline-15-epochs\")\n",
|
148 |
+
"\n",
|
149 |
+
"# Preprocessing function\n",
|
150 |
+
"def preprocess_function(examples):\n",
|
151 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
152 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
153 |
+
" return tokenizer(\n",
|
154 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
155 |
+
" )\n",
|
156 |
+
"\n",
|
157 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
158 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
159 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
160 |
+
]
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"cell_type": "markdown",
|
164 |
+
"metadata": {},
|
165 |
+
"source": [
|
166 |
+
"# With Pretrained Weights"
|
167 |
+
]
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"cell_type": "code",
|
171 |
+
"execution_count": 5,
|
172 |
+
"metadata": {},
|
173 |
+
"outputs": [
|
174 |
+
{
|
175 |
+
"name": "stderr",
|
176 |
+
"output_type": "stream",
|
177 |
+
"text": [
|
178 |
+
"/tmp/ipykernel_2050937/1742867626.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",
|
179 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
180 |
+
]
|
181 |
+
},
|
182 |
+
{
|
183 |
+
"data": {
|
184 |
+
"text/plain": [
|
185 |
+
"SciBertClassificationModel(\n",
|
186 |
+
" (base_model): BertModel(\n",
|
187 |
+
" (embeddings): BertEmbeddings(\n",
|
188 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
189 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
190 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
191 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
193 |
+
" )\n",
|
194 |
+
" (encoder): BertEncoder(\n",
|
195 |
+
" (layer): ModuleList(\n",
|
196 |
+
" (0-11): 12 x BertLayer(\n",
|
197 |
+
" (attention): BertAttention(\n",
|
198 |
+
" (self): BertSdpaSelfAttention(\n",
|
199 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
200 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
201 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
202 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
203 |
+
" )\n",
|
204 |
+
" (output): BertSelfOutput(\n",
|
205 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
206 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
207 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
208 |
+
" )\n",
|
209 |
+
" )\n",
|
210 |
+
" (intermediate): BertIntermediate(\n",
|
211 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
212 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
213 |
+
" )\n",
|
214 |
+
" (output): BertOutput(\n",
|
215 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
216 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
217 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
218 |
+
" )\n",
|
219 |
+
" )\n",
|
220 |
+
" )\n",
|
221 |
+
" )\n",
|
222 |
+
" (pooler): BertPooler(\n",
|
223 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
224 |
+
" (activation): Tanh()\n",
|
225 |
+
" )\n",
|
226 |
+
" )\n",
|
227 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
228 |
+
")"
|
229 |
+
]
|
230 |
+
},
|
231 |
+
"execution_count": 5,
|
232 |
+
"metadata": {},
|
233 |
+
"output_type": "execute_result"
|
234 |
+
}
|
235 |
+
],
|
236 |
+
"source": [
|
237 |
+
"classification_head_path = hf_hub_download(\n",
|
238 |
+
" repo_id=\"ppak10/defect-classification-scibert-baseline-15-epochs\",\n",
|
239 |
+
" repo_type=\"model\",\n",
|
240 |
+
" filename=\"classification_head.pt\"\n",
|
241 |
+
")\n",
|
242 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
243 |
+
"model.eval() # Set the model to evaluation mode"
|
244 |
+
]
|
245 |
+
},
|
246 |
+
{
|
247 |
+
"cell_type": "code",
|
248 |
+
"execution_count": 6,
|
249 |
+
"metadata": {},
|
250 |
+
"outputs": [
|
251 |
+
{
|
252 |
+
"name": "stderr",
|
253 |
+
"output_type": "stream",
|
254 |
+
"text": [
|
255 |
+
"100%|ββββββββββ| 142/142 [06:16<00:00, 2.65s/it]\n"
|
256 |
+
]
|
257 |
+
}
|
258 |
+
],
|
259 |
+
"source": [
|
260 |
+
"# Ensure the model is on the GPU\n",
|
261 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
262 |
+
"model = model.to(device)\n",
|
263 |
+
"\n",
|
264 |
+
"# Define the batch size\n",
|
265 |
+
"batch_size = 512\n",
|
266 |
+
"\n",
|
267 |
+
"# Create a DataLoader for the validation dataset\n",
|
268 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
269 |
+
"\n",
|
270 |
+
"def label_to_classifications_batch(labels):\n",
|
271 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
272 |
+
" \n",
|
273 |
+
" results = []\n",
|
274 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
275 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
276 |
+
" results.append(result)\n",
|
277 |
+
" return results\n",
|
278 |
+
"\n",
|
279 |
+
"accuracy_total = 0\n",
|
280 |
+
"\n",
|
281 |
+
"# Process the validation dataset in batches\n",
|
282 |
+
"for batch in tqdm(validation_loader):\n",
|
283 |
+
" texts = batch[\"text\"]\n",
|
284 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
285 |
+
"\n",
|
286 |
+
" # Move labels to GPU\n",
|
287 |
+
" # print(np.array(labels))\n",
|
288 |
+
" labels = torch.tensor(labels).to(device)\n",
|
289 |
+
"\n",
|
290 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
291 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
292 |
+
" inputs_kwargs = {}\n",
|
293 |
+
"\n",
|
294 |
+
" for key, value in inputs.items():\n",
|
295 |
+
" if key not in [\"token_type_ids\"]:\n",
|
296 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
297 |
+
"\n",
|
298 |
+
" # print(inputs_kwargs)\n",
|
299 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
300 |
+
"\n",
|
301 |
+
" # Perform inference\n",
|
302 |
+
" outputs = model(**inputs_kwargs)\n",
|
303 |
+
"\n",
|
304 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
305 |
+
" logits = outputs[\"logits\"]\n",
|
306 |
+
" probs = torch.sigmoid(logits)\n",
|
307 |
+
"\n",
|
308 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
309 |
+
" preds = (probs > 0.5).int()\n",
|
310 |
+
"\n",
|
311 |
+
" # Compute accuracy for the batch\n",
|
312 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
313 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
314 |
+
"\n",
|
315 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
316 |
+
"\n",
|
317 |
+
"# Calculate overall accuracy\n",
|
318 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
319 |
+
]
|
320 |
+
},
|
321 |
+
{
|
322 |
+
"cell_type": "code",
|
323 |
+
"execution_count": 7,
|
324 |
+
"metadata": {},
|
325 |
+
"outputs": [
|
326 |
+
{
|
327 |
+
"name": "stdout",
|
328 |
+
"output_type": "stream",
|
329 |
+
"text": [
|
330 |
+
"Overall Accuracy: 0.889951707408855\n"
|
331 |
+
]
|
332 |
+
}
|
333 |
+
],
|
334 |
+
"source": [
|
335 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
336 |
+
]
|
337 |
+
}
|
338 |
+
],
|
339 |
+
"metadata": {
|
340 |
+
"kernelspec": {
|
341 |
+
"display_name": "venv",
|
342 |
+
"language": "python",
|
343 |
+
"name": "python3"
|
344 |
+
},
|
345 |
+
"language_info": {
|
346 |
+
"codemirror_mode": {
|
347 |
+
"name": "ipython",
|
348 |
+
"version": 3
|
349 |
+
},
|
350 |
+
"file_extension": ".py",
|
351 |
+
"mimetype": "text/x-python",
|
352 |
+
"name": "python",
|
353 |
+
"nbconvert_exporter": "python",
|
354 |
+
"pygments_lexer": "ipython3",
|
355 |
+
"version": "3.10.12"
|
356 |
+
}
|
357 |
+
},
|
358 |
+
"nbformat": 4,
|
359 |
+
"nbformat_minor": 2
|
360 |
+
}
|
notebooks/scibert_baseline_20_epochs.ipynb
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-baseline-20-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [],
|
129 |
+
"source": [
|
130 |
+
"# Load dataset\n",
|
131 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
132 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
133 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
134 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
135 |
+
"\n",
|
136 |
+
"# Load the tokenizer\n",
|
137 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-baseline-20-epochs\")\n",
|
138 |
+
"\n",
|
139 |
+
"# Preprocessing function\n",
|
140 |
+
"def preprocess_function(examples):\n",
|
141 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
142 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
143 |
+
" return tokenizer(\n",
|
144 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
145 |
+
" )\n",
|
146 |
+
"\n",
|
147 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
148 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
149 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
150 |
+
]
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"cell_type": "markdown",
|
154 |
+
"metadata": {},
|
155 |
+
"source": [
|
156 |
+
"# With Pretrained Weights"
|
157 |
+
]
|
158 |
+
},
|
159 |
+
{
|
160 |
+
"cell_type": "code",
|
161 |
+
"execution_count": 5,
|
162 |
+
"metadata": {},
|
163 |
+
"outputs": [
|
164 |
+
{
|
165 |
+
"name": "stderr",
|
166 |
+
"output_type": "stream",
|
167 |
+
"text": [
|
168 |
+
"/tmp/ipykernel_3665058/3889582946.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",
|
169 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
170 |
+
]
|
171 |
+
},
|
172 |
+
{
|
173 |
+
"data": {
|
174 |
+
"text/plain": [
|
175 |
+
"SciBertClassificationModel(\n",
|
176 |
+
" (base_model): BertModel(\n",
|
177 |
+
" (embeddings): BertEmbeddings(\n",
|
178 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
179 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
180 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
181 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
182 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
183 |
+
" )\n",
|
184 |
+
" (encoder): BertEncoder(\n",
|
185 |
+
" (layer): ModuleList(\n",
|
186 |
+
" (0-11): 12 x BertLayer(\n",
|
187 |
+
" (attention): BertAttention(\n",
|
188 |
+
" (self): BertSdpaSelfAttention(\n",
|
189 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
190 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
191 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
193 |
+
" )\n",
|
194 |
+
" (output): BertSelfOutput(\n",
|
195 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
196 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
197 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
198 |
+
" )\n",
|
199 |
+
" )\n",
|
200 |
+
" (intermediate): BertIntermediate(\n",
|
201 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
202 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
203 |
+
" )\n",
|
204 |
+
" (output): BertOutput(\n",
|
205 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
206 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
207 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
208 |
+
" )\n",
|
209 |
+
" )\n",
|
210 |
+
" )\n",
|
211 |
+
" )\n",
|
212 |
+
" (pooler): BertPooler(\n",
|
213 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
214 |
+
" (activation): Tanh()\n",
|
215 |
+
" )\n",
|
216 |
+
" )\n",
|
217 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
218 |
+
")"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
"execution_count": 5,
|
222 |
+
"metadata": {},
|
223 |
+
"output_type": "execute_result"
|
224 |
+
}
|
225 |
+
],
|
226 |
+
"source": [
|
227 |
+
"classification_head_path = hf_hub_download(\n",
|
228 |
+
" repo_id=\"ppak10/defect-classification-scibert-baseline-20-epochs\",\n",
|
229 |
+
" repo_type=\"model\",\n",
|
230 |
+
" filename=\"classification_head.pt\"\n",
|
231 |
+
")\n",
|
232 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
233 |
+
"model.eval() # Set the model to evaluation mode"
|
234 |
+
]
|
235 |
+
},
|
236 |
+
{
|
237 |
+
"cell_type": "code",
|
238 |
+
"execution_count": 6,
|
239 |
+
"metadata": {},
|
240 |
+
"outputs": [
|
241 |
+
{
|
242 |
+
"name": "stderr",
|
243 |
+
"output_type": "stream",
|
244 |
+
"text": [
|
245 |
+
"100%|ββββββββββ| 142/142 [04:11<00:00, 1.77s/it]\n"
|
246 |
+
]
|
247 |
+
}
|
248 |
+
],
|
249 |
+
"source": [
|
250 |
+
"# Ensure the model is on the GPU\n",
|
251 |
+
"device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n",
|
252 |
+
"model = model.to(device)\n",
|
253 |
+
"\n",
|
254 |
+
"# Define the batch size\n",
|
255 |
+
"batch_size = 512\n",
|
256 |
+
"\n",
|
257 |
+
"# Create a DataLoader for the validation dataset\n",
|
258 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
259 |
+
"\n",
|
260 |
+
"def label_to_classifications_batch(labels):\n",
|
261 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
262 |
+
" \n",
|
263 |
+
" results = []\n",
|
264 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
265 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
266 |
+
" results.append(result)\n",
|
267 |
+
" return results\n",
|
268 |
+
"\n",
|
269 |
+
"accuracy_total = 0\n",
|
270 |
+
"\n",
|
271 |
+
"# Process the validation dataset in batches\n",
|
272 |
+
"for batch in tqdm(validation_loader):\n",
|
273 |
+
" texts = batch[\"text\"]\n",
|
274 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
275 |
+
"\n",
|
276 |
+
" # Move labels to GPU\n",
|
277 |
+
" # print(np.array(labels))\n",
|
278 |
+
" labels = torch.tensor(labels).to(device)\n",
|
279 |
+
"\n",
|
280 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
281 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
282 |
+
" inputs_kwargs = {}\n",
|
283 |
+
"\n",
|
284 |
+
" for key, value in inputs.items():\n",
|
285 |
+
" if key not in [\"token_type_ids\"]:\n",
|
286 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
287 |
+
"\n",
|
288 |
+
" # print(inputs_kwargs)\n",
|
289 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
290 |
+
"\n",
|
291 |
+
" # Perform inference\n",
|
292 |
+
" outputs = model(**inputs_kwargs)\n",
|
293 |
+
"\n",
|
294 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
295 |
+
" logits = outputs[\"logits\"]\n",
|
296 |
+
" probs = torch.sigmoid(logits)\n",
|
297 |
+
"\n",
|
298 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
299 |
+
" preds = (probs > 0.5).int()\n",
|
300 |
+
"\n",
|
301 |
+
" # Compute accuracy for the batch\n",
|
302 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
303 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
304 |
+
"\n",
|
305 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
306 |
+
"\n",
|
307 |
+
"# Calculate overall accuracy\n",
|
308 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
309 |
+
]
|
310 |
+
},
|
311 |
+
{
|
312 |
+
"cell_type": "code",
|
313 |
+
"execution_count": 7,
|
314 |
+
"metadata": {},
|
315 |
+
"outputs": [
|
316 |
+
{
|
317 |
+
"name": "stdout",
|
318 |
+
"output_type": "stream",
|
319 |
+
"text": [
|
320 |
+
"Overall Accuracy: 0.9132286994750848\n"
|
321 |
+
]
|
322 |
+
}
|
323 |
+
],
|
324 |
+
"source": [
|
325 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
326 |
+
]
|
327 |
+
}
|
328 |
+
],
|
329 |
+
"metadata": {
|
330 |
+
"kernelspec": {
|
331 |
+
"display_name": "venv",
|
332 |
+
"language": "python",
|
333 |
+
"name": "python3"
|
334 |
+
},
|
335 |
+
"language_info": {
|
336 |
+
"codemirror_mode": {
|
337 |
+
"name": "ipython",
|
338 |
+
"version": 3
|
339 |
+
},
|
340 |
+
"file_extension": ".py",
|
341 |
+
"mimetype": "text/x-python",
|
342 |
+
"name": "python",
|
343 |
+
"nbconvert_exporter": "python",
|
344 |
+
"pygments_lexer": "ipython3",
|
345 |
+
"version": "3.10.16"
|
346 |
+
}
|
347 |
+
},
|
348 |
+
"nbformat": 4,
|
349 |
+
"nbformat_minor": 2
|
350 |
+
}
|
notebooks/scibert_baseline_20_epochs_prompt_input.ipynb
ADDED
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-baseline-20-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [
|
129 |
+
{
|
130 |
+
"name": "stderr",
|
131 |
+
"output_type": "stream",
|
132 |
+
"text": [
|
133 |
+
"Generating train split: 41311472 examples [00:41, 997169.97 examples/s] \n",
|
134 |
+
"Generating test split: 1739424 examples [00:01, 918836.85 examples/s] \n",
|
135 |
+
"Generating validation split: 797225 examples [00:01, 627668.59 examples/s]\n",
|
136 |
+
"Generating train_baseline split: 543572 examples [00:00, 836876.89 examples/s]\n",
|
137 |
+
"Generating test_baseline split: 108714 examples [00:00, 1025978.13 examples/s]\n",
|
138 |
+
"Generating validation_baseline split: 72475 examples [00:00, 1293689.84 examples/s]\n",
|
139 |
+
"Generating train_prompt split: 40767900 examples [00:48, 833108.56 examples/s] \n",
|
140 |
+
"Generating test_prompt split: 1630710 examples [00:02, 578330.81 examples/s]\n",
|
141 |
+
"Generating validation_prompt split: 724750 examples [00:01, 636304.08 examples/s]\n",
|
142 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [09:59<00:00, 67958.60 examples/s] \n",
|
143 |
+
"Map (num_proc=32): 100%|ββββββββββ| 1630710/1630710 [00:18<00:00, 87306.90 examples/s]\n",
|
144 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:07<00:00, 99302.34 examples/s] \n"
|
145 |
+
]
|
146 |
+
}
|
147 |
+
],
|
148 |
+
"source": [
|
149 |
+
"# Load dataset\n",
|
150 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
151 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
152 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
153 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
154 |
+
"\n",
|
155 |
+
"# Load the tokenizer\n",
|
156 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-baseline-20-epochs\")\n",
|
157 |
+
"\n",
|
158 |
+
"# Preprocessing function\n",
|
159 |
+
"def preprocess_function(examples):\n",
|
160 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
161 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
162 |
+
" return tokenizer(\n",
|
163 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
164 |
+
" )\n",
|
165 |
+
"\n",
|
166 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
167 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
168 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
169 |
+
]
|
170 |
+
},
|
171 |
+
{
|
172 |
+
"cell_type": "markdown",
|
173 |
+
"metadata": {},
|
174 |
+
"source": [
|
175 |
+
"# With Pretrained Weights"
|
176 |
+
]
|
177 |
+
},
|
178 |
+
{
|
179 |
+
"cell_type": "code",
|
180 |
+
"execution_count": 5,
|
181 |
+
"metadata": {},
|
182 |
+
"outputs": [
|
183 |
+
{
|
184 |
+
"name": "stderr",
|
185 |
+
"output_type": "stream",
|
186 |
+
"text": [
|
187 |
+
"/tmp/ipykernel_1922833/3889582946.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",
|
188 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
189 |
+
]
|
190 |
+
},
|
191 |
+
{
|
192 |
+
"data": {
|
193 |
+
"text/plain": [
|
194 |
+
"SciBertClassificationModel(\n",
|
195 |
+
" (base_model): BertModel(\n",
|
196 |
+
" (embeddings): BertEmbeddings(\n",
|
197 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
198 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
199 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
200 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
201 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
202 |
+
" )\n",
|
203 |
+
" (encoder): BertEncoder(\n",
|
204 |
+
" (layer): ModuleList(\n",
|
205 |
+
" (0-11): 12 x BertLayer(\n",
|
206 |
+
" (attention): BertAttention(\n",
|
207 |
+
" (self): BertSdpaSelfAttention(\n",
|
208 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
209 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
210 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
211 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
212 |
+
" )\n",
|
213 |
+
" (output): BertSelfOutput(\n",
|
214 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
215 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
216 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
217 |
+
" )\n",
|
218 |
+
" )\n",
|
219 |
+
" (intermediate): BertIntermediate(\n",
|
220 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
221 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
222 |
+
" )\n",
|
223 |
+
" (output): BertOutput(\n",
|
224 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
225 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" )\n",
|
229 |
+
" )\n",
|
230 |
+
" )\n",
|
231 |
+
" (pooler): BertPooler(\n",
|
232 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
233 |
+
" (activation): Tanh()\n",
|
234 |
+
" )\n",
|
235 |
+
" )\n",
|
236 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
237 |
+
")"
|
238 |
+
]
|
239 |
+
},
|
240 |
+
"execution_count": 5,
|
241 |
+
"metadata": {},
|
242 |
+
"output_type": "execute_result"
|
243 |
+
}
|
244 |
+
],
|
245 |
+
"source": [
|
246 |
+
"classification_head_path = hf_hub_download(\n",
|
247 |
+
" repo_id=\"ppak10/defect-classification-scibert-baseline-20-epochs\",\n",
|
248 |
+
" repo_type=\"model\",\n",
|
249 |
+
" filename=\"classification_head.pt\"\n",
|
250 |
+
")\n",
|
251 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
252 |
+
"model.eval() # Set the model to evaluation mode"
|
253 |
+
]
|
254 |
+
},
|
255 |
+
{
|
256 |
+
"cell_type": "code",
|
257 |
+
"execution_count": 6,
|
258 |
+
"metadata": {},
|
259 |
+
"outputs": [
|
260 |
+
{
|
261 |
+
"name": "stderr",
|
262 |
+
"output_type": "stream",
|
263 |
+
"text": [
|
264 |
+
"100%|ββββββββββ| 1416/1416 [56:40<00:00, 2.40s/it] \n"
|
265 |
+
]
|
266 |
+
}
|
267 |
+
],
|
268 |
+
"source": [
|
269 |
+
"# Ensure the model is on the GPU\n",
|
270 |
+
"device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n",
|
271 |
+
"model = model.to(device)\n",
|
272 |
+
"\n",
|
273 |
+
"# Define the batch size\n",
|
274 |
+
"batch_size = 512\n",
|
275 |
+
"\n",
|
276 |
+
"# Create a DataLoader for the validation dataset\n",
|
277 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
278 |
+
"\n",
|
279 |
+
"def label_to_classifications_batch(labels):\n",
|
280 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
281 |
+
" \n",
|
282 |
+
" results = []\n",
|
283 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
284 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
285 |
+
" results.append(result)\n",
|
286 |
+
" return results\n",
|
287 |
+
"\n",
|
288 |
+
"accuracy_total = 0\n",
|
289 |
+
"\n",
|
290 |
+
"# Process the validation dataset in batches\n",
|
291 |
+
"for batch in tqdm(validation_loader):\n",
|
292 |
+
" texts = batch[\"text\"]\n",
|
293 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
294 |
+
"\n",
|
295 |
+
" # Move labels to GPU\n",
|
296 |
+
" # print(np.array(labels))\n",
|
297 |
+
" labels = torch.tensor(labels).to(device)\n",
|
298 |
+
"\n",
|
299 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
300 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
301 |
+
" inputs_kwargs = {}\n",
|
302 |
+
"\n",
|
303 |
+
" for key, value in inputs.items():\n",
|
304 |
+
" if key not in [\"token_type_ids\"]:\n",
|
305 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
306 |
+
"\n",
|
307 |
+
" # print(inputs_kwargs)\n",
|
308 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
309 |
+
"\n",
|
310 |
+
" # Perform inference\n",
|
311 |
+
" outputs = model(**inputs_kwargs)\n",
|
312 |
+
"\n",
|
313 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
314 |
+
" logits = outputs[\"logits\"]\n",
|
315 |
+
" probs = torch.sigmoid(logits)\n",
|
316 |
+
"\n",
|
317 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
318 |
+
" preds = (probs > 0.5).int()\n",
|
319 |
+
"\n",
|
320 |
+
" # Compute accuracy for the batch\n",
|
321 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
322 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
323 |
+
"\n",
|
324 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
325 |
+
"\n",
|
326 |
+
"# Calculate overall accuracy\n",
|
327 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
328 |
+
]
|
329 |
+
},
|
330 |
+
{
|
331 |
+
"cell_type": "code",
|
332 |
+
"execution_count": 7,
|
333 |
+
"metadata": {},
|
334 |
+
"outputs": [
|
335 |
+
{
|
336 |
+
"name": "stdout",
|
337 |
+
"output_type": "stream",
|
338 |
+
"text": [
|
339 |
+
"Overall Accuracy: 0.6306950672505929\n"
|
340 |
+
]
|
341 |
+
}
|
342 |
+
],
|
343 |
+
"source": [
|
344 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
345 |
+
]
|
346 |
+
}
|
347 |
+
],
|
348 |
+
"metadata": {
|
349 |
+
"kernelspec": {
|
350 |
+
"display_name": "venv",
|
351 |
+
"language": "python",
|
352 |
+
"name": "python3"
|
353 |
+
},
|
354 |
+
"language_info": {
|
355 |
+
"codemirror_mode": {
|
356 |
+
"name": "ipython",
|
357 |
+
"version": 3
|
358 |
+
},
|
359 |
+
"file_extension": ".py",
|
360 |
+
"mimetype": "text/x-python",
|
361 |
+
"name": "python",
|
362 |
+
"nbconvert_exporter": "python",
|
363 |
+
"pygments_lexer": "ipython3",
|
364 |
+
"version": "3.10.12"
|
365 |
+
}
|
366 |
+
},
|
367 |
+
"nbformat": 4,
|
368 |
+
"nbformat_minor": 2
|
369 |
+
}
|
notebooks/scibert_baseline_25_epochs.ipynb
ADDED
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-baseline-25-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [
|
129 |
+
{
|
130 |
+
"name": "stderr",
|
131 |
+
"output_type": "stream",
|
132 |
+
"text": [
|
133 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:14<00:00, 38806.50 examples/s]\n",
|
134 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:03<00:00, 36051.51 examples/s]\n",
|
135 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:02<00:00, 34878.10 examples/s]\n"
|
136 |
+
]
|
137 |
+
}
|
138 |
+
],
|
139 |
+
"source": [
|
140 |
+
"# Load dataset\n",
|
141 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
142 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
143 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
144 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
145 |
+
"\n",
|
146 |
+
"# Load the tokenizer\n",
|
147 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-baseline-25-epochs\")\n",
|
148 |
+
"\n",
|
149 |
+
"# Preprocessing function\n",
|
150 |
+
"def preprocess_function(examples):\n",
|
151 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
152 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
153 |
+
" return tokenizer(\n",
|
154 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
155 |
+
" )\n",
|
156 |
+
"\n",
|
157 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
158 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
159 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
160 |
+
]
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"cell_type": "markdown",
|
164 |
+
"metadata": {},
|
165 |
+
"source": [
|
166 |
+
"# With Pretrained Weights"
|
167 |
+
]
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"cell_type": "code",
|
171 |
+
"execution_count": 5,
|
172 |
+
"metadata": {},
|
173 |
+
"outputs": [
|
174 |
+
{
|
175 |
+
"name": "stderr",
|
176 |
+
"output_type": "stream",
|
177 |
+
"text": [
|
178 |
+
"/tmp/ipykernel_416091/1536426760.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",
|
179 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
180 |
+
]
|
181 |
+
},
|
182 |
+
{
|
183 |
+
"data": {
|
184 |
+
"text/plain": [
|
185 |
+
"SciBertClassificationModel(\n",
|
186 |
+
" (base_model): BertModel(\n",
|
187 |
+
" (embeddings): BertEmbeddings(\n",
|
188 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
189 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
190 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
191 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
193 |
+
" )\n",
|
194 |
+
" (encoder): BertEncoder(\n",
|
195 |
+
" (layer): ModuleList(\n",
|
196 |
+
" (0-11): 12 x BertLayer(\n",
|
197 |
+
" (attention): BertAttention(\n",
|
198 |
+
" (self): BertSdpaSelfAttention(\n",
|
199 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
200 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
201 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
202 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
203 |
+
" )\n",
|
204 |
+
" (output): BertSelfOutput(\n",
|
205 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
206 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
207 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
208 |
+
" )\n",
|
209 |
+
" )\n",
|
210 |
+
" (intermediate): BertIntermediate(\n",
|
211 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
212 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
213 |
+
" )\n",
|
214 |
+
" (output): BertOutput(\n",
|
215 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
216 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
217 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
218 |
+
" )\n",
|
219 |
+
" )\n",
|
220 |
+
" )\n",
|
221 |
+
" )\n",
|
222 |
+
" (pooler): BertPooler(\n",
|
223 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
224 |
+
" (activation): Tanh()\n",
|
225 |
+
" )\n",
|
226 |
+
" )\n",
|
227 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
228 |
+
")"
|
229 |
+
]
|
230 |
+
},
|
231 |
+
"execution_count": 5,
|
232 |
+
"metadata": {},
|
233 |
+
"output_type": "execute_result"
|
234 |
+
}
|
235 |
+
],
|
236 |
+
"source": [
|
237 |
+
"classification_head_path = hf_hub_download(\n",
|
238 |
+
" repo_id=\"ppak10/defect-classification-scibert-baseline-25-epochs\",\n",
|
239 |
+
" repo_type=\"model\",\n",
|
240 |
+
" filename=\"classification_head.pt\"\n",
|
241 |
+
")\n",
|
242 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
243 |
+
"model.eval() # Set the model to evaluation mode"
|
244 |
+
]
|
245 |
+
},
|
246 |
+
{
|
247 |
+
"cell_type": "code",
|
248 |
+
"execution_count": 6,
|
249 |
+
"metadata": {},
|
250 |
+
"outputs": [
|
251 |
+
{
|
252 |
+
"name": "stderr",
|
253 |
+
"output_type": "stream",
|
254 |
+
"text": [
|
255 |
+
"100%|ββββββββββ| 142/142 [04:13<00:00, 1.78s/it]\n"
|
256 |
+
]
|
257 |
+
}
|
258 |
+
],
|
259 |
+
"source": [
|
260 |
+
"# Ensure the model is on the GPU\n",
|
261 |
+
"device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n",
|
262 |
+
"model = model.to(device)\n",
|
263 |
+
"\n",
|
264 |
+
"# Define the batch size\n",
|
265 |
+
"batch_size = 512\n",
|
266 |
+
"\n",
|
267 |
+
"# Create a DataLoader for the validation dataset\n",
|
268 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
269 |
+
"\n",
|
270 |
+
"def label_to_classifications_batch(labels):\n",
|
271 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
272 |
+
" \n",
|
273 |
+
" results = []\n",
|
274 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
275 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
276 |
+
" results.append(result)\n",
|
277 |
+
" return results\n",
|
278 |
+
"\n",
|
279 |
+
"accuracy_total = 0\n",
|
280 |
+
"\n",
|
281 |
+
"# Process the validation dataset in batches\n",
|
282 |
+
"for batch in tqdm(validation_loader):\n",
|
283 |
+
" texts = batch[\"text\"]\n",
|
284 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
285 |
+
"\n",
|
286 |
+
" # Move labels to GPU\n",
|
287 |
+
" # print(np.array(labels))\n",
|
288 |
+
" labels = torch.tensor(labels).to(device)\n",
|
289 |
+
"\n",
|
290 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
291 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
292 |
+
" inputs_kwargs = {}\n",
|
293 |
+
"\n",
|
294 |
+
" for key, value in inputs.items():\n",
|
295 |
+
" if key not in [\"token_type_ids\"]:\n",
|
296 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
297 |
+
"\n",
|
298 |
+
" # print(inputs_kwargs)\n",
|
299 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
300 |
+
"\n",
|
301 |
+
" # Perform inference\n",
|
302 |
+
" outputs = model(**inputs_kwargs)\n",
|
303 |
+
"\n",
|
304 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
305 |
+
" logits = outputs[\"logits\"]\n",
|
306 |
+
" probs = torch.sigmoid(logits)\n",
|
307 |
+
"\n",
|
308 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
309 |
+
" preds = (probs > 0.5).int()\n",
|
310 |
+
"\n",
|
311 |
+
" # Compute accuracy for the batch\n",
|
312 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
313 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
314 |
+
"\n",
|
315 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
316 |
+
"\n",
|
317 |
+
"# Calculate overall accuracy\n",
|
318 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
319 |
+
]
|
320 |
+
},
|
321 |
+
{
|
322 |
+
"cell_type": "code",
|
323 |
+
"execution_count": 7,
|
324 |
+
"metadata": {},
|
325 |
+
"outputs": [
|
326 |
+
{
|
327 |
+
"name": "stdout",
|
328 |
+
"output_type": "stream",
|
329 |
+
"text": [
|
330 |
+
"Overall Accuracy: 0.9088444290370027\n"
|
331 |
+
]
|
332 |
+
}
|
333 |
+
],
|
334 |
+
"source": [
|
335 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
336 |
+
]
|
337 |
+
}
|
338 |
+
],
|
339 |
+
"metadata": {
|
340 |
+
"kernelspec": {
|
341 |
+
"display_name": "venv",
|
342 |
+
"language": "python",
|
343 |
+
"name": "python3"
|
344 |
+
},
|
345 |
+
"language_info": {
|
346 |
+
"codemirror_mode": {
|
347 |
+
"name": "ipython",
|
348 |
+
"version": 3
|
349 |
+
},
|
350 |
+
"file_extension": ".py",
|
351 |
+
"mimetype": "text/x-python",
|
352 |
+
"name": "python",
|
353 |
+
"nbconvert_exporter": "python",
|
354 |
+
"pygments_lexer": "ipython3",
|
355 |
+
"version": "3.10.16"
|
356 |
+
}
|
357 |
+
},
|
358 |
+
"nbformat": 4,
|
359 |
+
"nbformat_minor": 2
|
360 |
+
}
|
notebooks/scibert_prompt_02_epochs.ipynb
ADDED
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-prompt-02-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [
|
129 |
+
{
|
130 |
+
"name": "stderr",
|
131 |
+
"output_type": "stream",
|
132 |
+
"text": [
|
133 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [05:06<00:00, 132909.94 examples/s]\n",
|
134 |
+
"Map (num_proc=32): 100%|ββββββββββ| 1630710/1630710 [00:13<00:00, 122195.41 examples/s]\n",
|
135 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:06<00:00, 119431.07 examples/s]\n"
|
136 |
+
]
|
137 |
+
}
|
138 |
+
],
|
139 |
+
"source": [
|
140 |
+
"# Load dataset\n",
|
141 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
142 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
143 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
144 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
145 |
+
"\n",
|
146 |
+
"# Load the tokenizer\n",
|
147 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-prompt-02-epochs\")\n",
|
148 |
+
"\n",
|
149 |
+
"# Preprocessing function\n",
|
150 |
+
"def preprocess_function(examples):\n",
|
151 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
152 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
153 |
+
" return tokenizer(\n",
|
154 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
155 |
+
" )\n",
|
156 |
+
"\n",
|
157 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
158 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
159 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
160 |
+
]
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"cell_type": "markdown",
|
164 |
+
"metadata": {},
|
165 |
+
"source": [
|
166 |
+
"# With Pretrained Weights"
|
167 |
+
]
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"cell_type": "code",
|
171 |
+
"execution_count": 5,
|
172 |
+
"metadata": {},
|
173 |
+
"outputs": [
|
174 |
+
{
|
175 |
+
"name": "stderr",
|
176 |
+
"output_type": "stream",
|
177 |
+
"text": [
|
178 |
+
"/tmp/ipykernel_456694/3937012942.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",
|
179 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
180 |
+
]
|
181 |
+
},
|
182 |
+
{
|
183 |
+
"data": {
|
184 |
+
"text/plain": [
|
185 |
+
"SciBertClassificationModel(\n",
|
186 |
+
" (base_model): BertModel(\n",
|
187 |
+
" (embeddings): BertEmbeddings(\n",
|
188 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
189 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
190 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
191 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
193 |
+
" )\n",
|
194 |
+
" (encoder): BertEncoder(\n",
|
195 |
+
" (layer): ModuleList(\n",
|
196 |
+
" (0-11): 12 x BertLayer(\n",
|
197 |
+
" (attention): BertAttention(\n",
|
198 |
+
" (self): BertSdpaSelfAttention(\n",
|
199 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
200 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
201 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
202 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
203 |
+
" )\n",
|
204 |
+
" (output): BertSelfOutput(\n",
|
205 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
206 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
207 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
208 |
+
" )\n",
|
209 |
+
" )\n",
|
210 |
+
" (intermediate): BertIntermediate(\n",
|
211 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
212 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
213 |
+
" )\n",
|
214 |
+
" (output): BertOutput(\n",
|
215 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
216 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
217 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
218 |
+
" )\n",
|
219 |
+
" )\n",
|
220 |
+
" )\n",
|
221 |
+
" )\n",
|
222 |
+
" (pooler): BertPooler(\n",
|
223 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
224 |
+
" (activation): Tanh()\n",
|
225 |
+
" )\n",
|
226 |
+
" )\n",
|
227 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
228 |
+
")"
|
229 |
+
]
|
230 |
+
},
|
231 |
+
"execution_count": 5,
|
232 |
+
"metadata": {},
|
233 |
+
"output_type": "execute_result"
|
234 |
+
}
|
235 |
+
],
|
236 |
+
"source": [
|
237 |
+
"classification_head_path = hf_hub_download(\n",
|
238 |
+
" repo_id=\"ppak10/defect-classification-scibert-prompt-02-epochs\",\n",
|
239 |
+
" repo_type=\"model\",\n",
|
240 |
+
" filename=\"classification_head.pt\"\n",
|
241 |
+
")\n",
|
242 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
243 |
+
"model.eval() # Set the model to evaluation mode"
|
244 |
+
]
|
245 |
+
},
|
246 |
+
{
|
247 |
+
"cell_type": "code",
|
248 |
+
"execution_count": 6,
|
249 |
+
"metadata": {},
|
250 |
+
"outputs": [
|
251 |
+
{
|
252 |
+
"name": "stderr",
|
253 |
+
"output_type": "stream",
|
254 |
+
"text": [
|
255 |
+
"100%|ββββββββββ| 1416/1416 [37:15<00:00, 1.58s/it]\n"
|
256 |
+
]
|
257 |
+
}
|
258 |
+
],
|
259 |
+
"source": [
|
260 |
+
"# Ensure the model is on the GPU\n",
|
261 |
+
"device = torch.device(\"cuda:2\" if torch.cuda.is_available() else \"cpu\")\n",
|
262 |
+
"model = model.to(device)\n",
|
263 |
+
"\n",
|
264 |
+
"# Define the batch size\n",
|
265 |
+
"batch_size = 512\n",
|
266 |
+
"\n",
|
267 |
+
"# Create a DataLoader for the validation dataset\n",
|
268 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
269 |
+
"\n",
|
270 |
+
"def label_to_classifications_batch(labels):\n",
|
271 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
272 |
+
" \n",
|
273 |
+
" results = []\n",
|
274 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
275 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
276 |
+
" results.append(result)\n",
|
277 |
+
" return results\n",
|
278 |
+
"\n",
|
279 |
+
"accuracy_total = 0\n",
|
280 |
+
"\n",
|
281 |
+
"# Process the validation dataset in batches\n",
|
282 |
+
"for batch in tqdm(validation_loader):\n",
|
283 |
+
" texts = batch[\"text\"]\n",
|
284 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
285 |
+
"\n",
|
286 |
+
" # Move labels to GPU\n",
|
287 |
+
" # print(np.array(labels))\n",
|
288 |
+
" labels = torch.tensor(labels).to(device)\n",
|
289 |
+
"\n",
|
290 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
291 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
292 |
+
" inputs_kwargs = {}\n",
|
293 |
+
"\n",
|
294 |
+
" for key, value in inputs.items():\n",
|
295 |
+
" if key not in [\"token_type_ids\"]:\n",
|
296 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
297 |
+
"\n",
|
298 |
+
" # print(inputs_kwargs)\n",
|
299 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
300 |
+
"\n",
|
301 |
+
" # Perform inference\n",
|
302 |
+
" outputs = model(**inputs_kwargs)\n",
|
303 |
+
"\n",
|
304 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
305 |
+
" logits = outputs[\"logits\"]\n",
|
306 |
+
" probs = torch.sigmoid(logits)\n",
|
307 |
+
"\n",
|
308 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
309 |
+
" preds = (probs > 0.5).int()\n",
|
310 |
+
"\n",
|
311 |
+
" # Compute accuracy for the batch\n",
|
312 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
313 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
314 |
+
"\n",
|
315 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
316 |
+
"\n",
|
317 |
+
"# Calculate overall accuracy\n",
|
318 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
319 |
+
]
|
320 |
+
},
|
321 |
+
{
|
322 |
+
"cell_type": "code",
|
323 |
+
"execution_count": 7,
|
324 |
+
"metadata": {},
|
325 |
+
"outputs": [
|
326 |
+
{
|
327 |
+
"name": "stdout",
|
328 |
+
"output_type": "stream",
|
329 |
+
"text": [
|
330 |
+
"Overall Accuracy: 0.8140765781275113\n"
|
331 |
+
]
|
332 |
+
}
|
333 |
+
],
|
334 |
+
"source": [
|
335 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
336 |
+
]
|
337 |
+
}
|
338 |
+
],
|
339 |
+
"metadata": {
|
340 |
+
"kernelspec": {
|
341 |
+
"display_name": "venv",
|
342 |
+
"language": "python",
|
343 |
+
"name": "python3"
|
344 |
+
},
|
345 |
+
"language_info": {
|
346 |
+
"codemirror_mode": {
|
347 |
+
"name": "ipython",
|
348 |
+
"version": 3
|
349 |
+
},
|
350 |
+
"file_extension": ".py",
|
351 |
+
"mimetype": "text/x-python",
|
352 |
+
"name": "python",
|
353 |
+
"nbconvert_exporter": "python",
|
354 |
+
"pygments_lexer": "ipython3",
|
355 |
+
"version": "3.10.12"
|
356 |
+
}
|
357 |
+
},
|
358 |
+
"nbformat": 4,
|
359 |
+
"nbformat_minor": 2
|
360 |
+
}
|
notebooks/scibert_prompt_05_epochs.ipynb
ADDED
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import AutoTokenizer\n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.scibert import SciBertClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"text/plain": [
|
65 |
+
"SciBertClassificationModel(\n",
|
66 |
+
" (base_model): BertModel(\n",
|
67 |
+
" (embeddings): BertEmbeddings(\n",
|
68 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
69 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
70 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
71 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
72 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
73 |
+
" )\n",
|
74 |
+
" (encoder): BertEncoder(\n",
|
75 |
+
" (layer): ModuleList(\n",
|
76 |
+
" (0-11): 12 x BertLayer(\n",
|
77 |
+
" (attention): BertAttention(\n",
|
78 |
+
" (self): BertSdpaSelfAttention(\n",
|
79 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
80 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
81 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
82 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
83 |
+
" )\n",
|
84 |
+
" (output): BertSelfOutput(\n",
|
85 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
86 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
87 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
88 |
+
" )\n",
|
89 |
+
" )\n",
|
90 |
+
" (intermediate): BertIntermediate(\n",
|
91 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
92 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
93 |
+
" )\n",
|
94 |
+
" (output): BertOutput(\n",
|
95 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
96 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
97 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
98 |
+
" )\n",
|
99 |
+
" )\n",
|
100 |
+
" )\n",
|
101 |
+
" )\n",
|
102 |
+
" (pooler): BertPooler(\n",
|
103 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
104 |
+
" (activation): Tanh()\n",
|
105 |
+
" )\n",
|
106 |
+
" )\n",
|
107 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
108 |
+
")"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
"execution_count": 3,
|
112 |
+
"metadata": {},
|
113 |
+
"output_type": "execute_result"
|
114 |
+
}
|
115 |
+
],
|
116 |
+
"source": [
|
117 |
+
"# Initialize the model\n",
|
118 |
+
"model = SciBertClassificationModel(\"ppak10/defect-classification-scibert-prompt-05-epochs\")\n",
|
119 |
+
"\n",
|
120 |
+
"# model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
121 |
+
"model.eval() # Set the model to evaluation mode"
|
122 |
+
]
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"cell_type": "code",
|
126 |
+
"execution_count": 4,
|
127 |
+
"metadata": {},
|
128 |
+
"outputs": [
|
129 |
+
{
|
130 |
+
"name": "stderr",
|
131 |
+
"output_type": "stream",
|
132 |
+
"text": [
|
133 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [16:04<00:00, 42252.07 examples/s]\n",
|
134 |
+
"Map (num_proc=32): 100%|ββββββββββ| 1630710/1630710 [00:46<00:00, 34734.26 examples/s]\n",
|
135 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:21<00:00, 33716.48 examples/s]\n"
|
136 |
+
]
|
137 |
+
}
|
138 |
+
],
|
139 |
+
"source": [
|
140 |
+
"# Load dataset\n",
|
141 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\", cache_dir=\"./.cache\")\n",
|
142 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
143 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
144 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
145 |
+
"\n",
|
146 |
+
"# Load the tokenizer\n",
|
147 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"ppak10/defect-classification-scibert-prompt-05-epochs\")\n",
|
148 |
+
"\n",
|
149 |
+
"# Preprocessing function\n",
|
150 |
+
"def preprocess_function(examples):\n",
|
151 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
152 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
153 |
+
" return tokenizer(\n",
|
154 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
155 |
+
" )\n",
|
156 |
+
"\n",
|
157 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
158 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
159 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
160 |
+
]
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"cell_type": "markdown",
|
164 |
+
"metadata": {},
|
165 |
+
"source": [
|
166 |
+
"# With Pretrained Weights"
|
167 |
+
]
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"cell_type": "code",
|
171 |
+
"execution_count": 5,
|
172 |
+
"metadata": {},
|
173 |
+
"outputs": [
|
174 |
+
{
|
175 |
+
"name": "stderr",
|
176 |
+
"output_type": "stream",
|
177 |
+
"text": [
|
178 |
+
"/tmp/ipykernel_624692/1877394519.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",
|
179 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
180 |
+
]
|
181 |
+
},
|
182 |
+
{
|
183 |
+
"data": {
|
184 |
+
"text/plain": [
|
185 |
+
"SciBertClassificationModel(\n",
|
186 |
+
" (base_model): BertModel(\n",
|
187 |
+
" (embeddings): BertEmbeddings(\n",
|
188 |
+
" (word_embeddings): Embedding(31090, 768, padding_idx=0)\n",
|
189 |
+
" (position_embeddings): Embedding(512, 768)\n",
|
190 |
+
" (token_type_embeddings): Embedding(2, 768)\n",
|
191 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
192 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
193 |
+
" )\n",
|
194 |
+
" (encoder): BertEncoder(\n",
|
195 |
+
" (layer): ModuleList(\n",
|
196 |
+
" (0-11): 12 x BertLayer(\n",
|
197 |
+
" (attention): BertAttention(\n",
|
198 |
+
" (self): BertSdpaSelfAttention(\n",
|
199 |
+
" (query): Linear(in_features=768, out_features=768, bias=True)\n",
|
200 |
+
" (key): Linear(in_features=768, out_features=768, bias=True)\n",
|
201 |
+
" (value): Linear(in_features=768, out_features=768, bias=True)\n",
|
202 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
203 |
+
" )\n",
|
204 |
+
" (output): BertSelfOutput(\n",
|
205 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
206 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
207 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
208 |
+
" )\n",
|
209 |
+
" )\n",
|
210 |
+
" (intermediate): BertIntermediate(\n",
|
211 |
+
" (dense): Linear(in_features=768, out_features=3072, bias=True)\n",
|
212 |
+
" (intermediate_act_fn): GELUActivation()\n",
|
213 |
+
" )\n",
|
214 |
+
" (output): BertOutput(\n",
|
215 |
+
" (dense): Linear(in_features=3072, out_features=768, bias=True)\n",
|
216 |
+
" (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)\n",
|
217 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
218 |
+
" )\n",
|
219 |
+
" )\n",
|
220 |
+
" )\n",
|
221 |
+
" )\n",
|
222 |
+
" (pooler): BertPooler(\n",
|
223 |
+
" (dense): Linear(in_features=768, out_features=768, bias=True)\n",
|
224 |
+
" (activation): Tanh()\n",
|
225 |
+
" )\n",
|
226 |
+
" )\n",
|
227 |
+
" (classifier): Linear(in_features=768, out_features=4, bias=True)\n",
|
228 |
+
")"
|
229 |
+
]
|
230 |
+
},
|
231 |
+
"execution_count": 5,
|
232 |
+
"metadata": {},
|
233 |
+
"output_type": "execute_result"
|
234 |
+
}
|
235 |
+
],
|
236 |
+
"source": [
|
237 |
+
"classification_head_path = hf_hub_download(\n",
|
238 |
+
" repo_id=\"ppak10/defect-classification-scibert-prompt-05-epochs\",\n",
|
239 |
+
" repo_type=\"model\",\n",
|
240 |
+
" filename=\"classification_head.pt\"\n",
|
241 |
+
")\n",
|
242 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
243 |
+
"model.eval() # Set the model to evaluation mode"
|
244 |
+
]
|
245 |
+
},
|
246 |
+
{
|
247 |
+
"cell_type": "code",
|
248 |
+
"execution_count": 6,
|
249 |
+
"metadata": {},
|
250 |
+
"outputs": [
|
251 |
+
{
|
252 |
+
"name": "stderr",
|
253 |
+
"output_type": "stream",
|
254 |
+
"text": [
|
255 |
+
"100%|ββββββββββ| 1416/1416 [43:51<00:00, 1.86s/it]\n"
|
256 |
+
]
|
257 |
+
}
|
258 |
+
],
|
259 |
+
"source": [
|
260 |
+
"# Ensure the model is on the GPU\n",
|
261 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
262 |
+
"model = model.to(device)\n",
|
263 |
+
"\n",
|
264 |
+
"# Define the batch size\n",
|
265 |
+
"batch_size = 512\n",
|
266 |
+
"\n",
|
267 |
+
"# Create a DataLoader for the validation dataset\n",
|
268 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
269 |
+
"\n",
|
270 |
+
"def label_to_classifications_batch(labels):\n",
|
271 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
272 |
+
" \n",
|
273 |
+
" results = []\n",
|
274 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
275 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
276 |
+
" results.append(result)\n",
|
277 |
+
" return results\n",
|
278 |
+
"\n",
|
279 |
+
"accuracy_total = 0\n",
|
280 |
+
"\n",
|
281 |
+
"# Process the validation dataset in batches\n",
|
282 |
+
"for batch in tqdm(validation_loader):\n",
|
283 |
+
" texts = batch[\"text\"]\n",
|
284 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
285 |
+
"\n",
|
286 |
+
" # Move labels to GPU\n",
|
287 |
+
" # print(np.array(labels))\n",
|
288 |
+
" labels = torch.tensor(labels).to(device)\n",
|
289 |
+
"\n",
|
290 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
291 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
292 |
+
" inputs_kwargs = {}\n",
|
293 |
+
"\n",
|
294 |
+
" for key, value in inputs.items():\n",
|
295 |
+
" if key not in [\"token_type_ids\"]:\n",
|
296 |
+
" inputs_kwargs[key] = value.to(device)\n",
|
297 |
+
"\n",
|
298 |
+
" # print(inputs_kwargs)\n",
|
299 |
+
" # inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
300 |
+
"\n",
|
301 |
+
" # Perform inference\n",
|
302 |
+
" outputs = model(**inputs_kwargs)\n",
|
303 |
+
"\n",
|
304 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
305 |
+
" logits = outputs[\"logits\"]\n",
|
306 |
+
" probs = torch.sigmoid(logits)\n",
|
307 |
+
"\n",
|
308 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
309 |
+
" preds = (probs > 0.5).int()\n",
|
310 |
+
"\n",
|
311 |
+
" # Compute accuracy for the batch\n",
|
312 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
313 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
314 |
+
"\n",
|
315 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
316 |
+
"\n",
|
317 |
+
"# Calculate overall accuracy\n",
|
318 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)"
|
319 |
+
]
|
320 |
+
},
|
321 |
+
{
|
322 |
+
"cell_type": "code",
|
323 |
+
"execution_count": 7,
|
324 |
+
"metadata": {},
|
325 |
+
"outputs": [
|
326 |
+
{
|
327 |
+
"name": "stdout",
|
328 |
+
"output_type": "stream",
|
329 |
+
"text": [
|
330 |
+
"Overall Accuracy: 0.8104549844781461\n"
|
331 |
+
]
|
332 |
+
}
|
333 |
+
],
|
334 |
+
"source": [
|
335 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
336 |
+
]
|
337 |
+
}
|
338 |
+
],
|
339 |
+
"metadata": {
|
340 |
+
"kernelspec": {
|
341 |
+
"display_name": "venv",
|
342 |
+
"language": "python",
|
343 |
+
"name": "python3"
|
344 |
+
},
|
345 |
+
"language_info": {
|
346 |
+
"codemirror_mode": {
|
347 |
+
"name": "ipython",
|
348 |
+
"version": 3
|
349 |
+
},
|
350 |
+
"file_extension": ".py",
|
351 |
+
"mimetype": "text/x-python",
|
352 |
+
"name": "python",
|
353 |
+
"nbconvert_exporter": "python",
|
354 |
+
"pygments_lexer": "ipython3",
|
355 |
+
"version": "3.10.16"
|
356 |
+
}
|
357 |
+
},
|
358 |
+
"nbformat": 4,
|
359 |
+
"nbformat_minor": 2
|
360 |
+
}
|
notebooks/t5_baseline_05_epochs.ipynb
ADDED
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-baseline-05-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [
|
153 |
+
{
|
154 |
+
"name": "stderr",
|
155 |
+
"output_type": "stream",
|
156 |
+
"text": [
|
157 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:10<00:00, 51066.36 examples/s]\n",
|
158 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 41882.51 examples/s]\n",
|
159 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:01<00:00, 43473.24 examples/s]\n"
|
160 |
+
]
|
161 |
+
}
|
162 |
+
],
|
163 |
+
"source": [
|
164 |
+
"# Load dataset\n",
|
165 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
166 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
167 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
168 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
169 |
+
"\n",
|
170 |
+
"# Load the tokenizer\n",
|
171 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-baseline-05-epochs\")\n",
|
172 |
+
"\n",
|
173 |
+
"# Preprocessing function\n",
|
174 |
+
"def preprocess_function(examples):\n",
|
175 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
176 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
177 |
+
" return tokenizer(\n",
|
178 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
179 |
+
" )\n",
|
180 |
+
"\n",
|
181 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
182 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
183 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
184 |
+
]
|
185 |
+
},
|
186 |
+
{
|
187 |
+
"cell_type": "markdown",
|
188 |
+
"metadata": {},
|
189 |
+
"source": [
|
190 |
+
"# With Pretrained Weights"
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"cell_type": "code",
|
195 |
+
"execution_count": 5,
|
196 |
+
"metadata": {},
|
197 |
+
"outputs": [
|
198 |
+
{
|
199 |
+
"name": "stderr",
|
200 |
+
"output_type": "stream",
|
201 |
+
"text": [
|
202 |
+
"/tmp/ipykernel_1068684/3546596680.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",
|
203 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"data": {
|
208 |
+
"text/plain": [
|
209 |
+
"T5ClassificationModel(\n",
|
210 |
+
" (base_model): T5EncoderModel(\n",
|
211 |
+
" (shared): Embedding(32128, 512)\n",
|
212 |
+
" (encoder): T5Stack(\n",
|
213 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
214 |
+
" (block): ModuleList(\n",
|
215 |
+
" (0): T5Block(\n",
|
216 |
+
" (layer): ModuleList(\n",
|
217 |
+
" (0): T5LayerSelfAttention(\n",
|
218 |
+
" (SelfAttention): T5Attention(\n",
|
219 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
220 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
221 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
222 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
223 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" (1): T5LayerFF(\n",
|
229 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
230 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
231 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
232 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
233 |
+
" (act): ReLU()\n",
|
234 |
+
" )\n",
|
235 |
+
" (layer_norm): T5LayerNorm()\n",
|
236 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
237 |
+
" )\n",
|
238 |
+
" )\n",
|
239 |
+
" )\n",
|
240 |
+
" (1-5): 5 x T5Block(\n",
|
241 |
+
" (layer): ModuleList(\n",
|
242 |
+
" (0): T5LayerSelfAttention(\n",
|
243 |
+
" (SelfAttention): T5Attention(\n",
|
244 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
245 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
246 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
247 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" (1): T5LayerFF(\n",
|
253 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
254 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
255 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" (act): ReLU()\n",
|
258 |
+
" )\n",
|
259 |
+
" (layer_norm): T5LayerNorm()\n",
|
260 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
261 |
+
" )\n",
|
262 |
+
" )\n",
|
263 |
+
" )\n",
|
264 |
+
" )\n",
|
265 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
266 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
267 |
+
" )\n",
|
268 |
+
" )\n",
|
269 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
270 |
+
")"
|
271 |
+
]
|
272 |
+
},
|
273 |
+
"execution_count": 5,
|
274 |
+
"metadata": {},
|
275 |
+
"output_type": "execute_result"
|
276 |
+
}
|
277 |
+
],
|
278 |
+
"source": [
|
279 |
+
"classification_head_path = hf_hub_download(\n",
|
280 |
+
" repo_id=\"ppak10/defect-classification-t5-baseline-05-epochs\",\n",
|
281 |
+
" repo_type=\"model\",\n",
|
282 |
+
" filename=\"classification_head.pt\"\n",
|
283 |
+
")\n",
|
284 |
+
"\n",
|
285 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
286 |
+
"model.eval() # Set the model to evaluation mode"
|
287 |
+
]
|
288 |
+
},
|
289 |
+
{
|
290 |
+
"cell_type": "code",
|
291 |
+
"execution_count": 6,
|
292 |
+
"metadata": {},
|
293 |
+
"outputs": [
|
294 |
+
{
|
295 |
+
"name": "stderr",
|
296 |
+
"output_type": "stream",
|
297 |
+
"text": [
|
298 |
+
"100%|ββββββββββ| 142/142 [02:20<00:00, 1.01it/s]"
|
299 |
+
]
|
300 |
+
},
|
301 |
+
{
|
302 |
+
"name": "stdout",
|
303 |
+
"output_type": "stream",
|
304 |
+
"text": [
|
305 |
+
"Overall Accuracy: 0.7960503621173752\n"
|
306 |
+
]
|
307 |
+
},
|
308 |
+
{
|
309 |
+
"name": "stderr",
|
310 |
+
"output_type": "stream",
|
311 |
+
"text": [
|
312 |
+
"\n"
|
313 |
+
]
|
314 |
+
}
|
315 |
+
],
|
316 |
+
"source": [
|
317 |
+
"# Ensure the model is on the GPU\n",
|
318 |
+
"device = torch.device(\"cuda:2\" if torch.cuda.is_available() else \"cpu\")\n",
|
319 |
+
"model = model.to(device)\n",
|
320 |
+
"\n",
|
321 |
+
"# Define the batch size\n",
|
322 |
+
"batch_size = 512\n",
|
323 |
+
"\n",
|
324 |
+
"# Create a DataLoader for the validation dataset\n",
|
325 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
326 |
+
"\n",
|
327 |
+
"def label_to_classifications_batch(labels):\n",
|
328 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
329 |
+
" \n",
|
330 |
+
" results = []\n",
|
331 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
332 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
333 |
+
" results.append(result)\n",
|
334 |
+
" return results\n",
|
335 |
+
"\n",
|
336 |
+
"accuracy_total = 0\n",
|
337 |
+
"\n",
|
338 |
+
"# Process the validation dataset in batches\n",
|
339 |
+
"for batch in tqdm(validation_loader):\n",
|
340 |
+
" texts = batch[\"text\"]\n",
|
341 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
342 |
+
"\n",
|
343 |
+
" # Move labels to GPU\n",
|
344 |
+
" # print(np.array(labels))\n",
|
345 |
+
" labels = torch.tensor(labels).to(device)\n",
|
346 |
+
"\n",
|
347 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
348 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
349 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
350 |
+
"\n",
|
351 |
+
" # Perform inference\n",
|
352 |
+
" outputs = model(**inputs)\n",
|
353 |
+
"\n",
|
354 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
355 |
+
" logits = outputs[\"logits\"]\n",
|
356 |
+
" probs = torch.sigmoid(logits)\n",
|
357 |
+
"\n",
|
358 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
359 |
+
" preds = (probs > 0.5).int()\n",
|
360 |
+
"\n",
|
361 |
+
" # Compute accuracy for the batch\n",
|
362 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
363 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
364 |
+
"\n",
|
365 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
366 |
+
"\n",
|
367 |
+
"# Calculate overall accuracy\n",
|
368 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
369 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
370 |
+
]
|
371 |
+
},
|
372 |
+
{
|
373 |
+
"cell_type": "code",
|
374 |
+
"execution_count": null,
|
375 |
+
"metadata": {},
|
376 |
+
"outputs": [],
|
377 |
+
"source": []
|
378 |
+
}
|
379 |
+
],
|
380 |
+
"metadata": {
|
381 |
+
"kernelspec": {
|
382 |
+
"display_name": "venv",
|
383 |
+
"language": "python",
|
384 |
+
"name": "python3"
|
385 |
+
},
|
386 |
+
"language_info": {
|
387 |
+
"codemirror_mode": {
|
388 |
+
"name": "ipython",
|
389 |
+
"version": 3
|
390 |
+
},
|
391 |
+
"file_extension": ".py",
|
392 |
+
"mimetype": "text/x-python",
|
393 |
+
"name": "python",
|
394 |
+
"nbconvert_exporter": "python",
|
395 |
+
"pygments_lexer": "ipython3",
|
396 |
+
"version": "3.10.12"
|
397 |
+
}
|
398 |
+
},
|
399 |
+
"nbformat": 4,
|
400 |
+
"nbformat_minor": 2
|
401 |
+
}
|
notebooks/t5_baseline_10_epochs.ipynb
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-baseline-10-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [],
|
153 |
+
"source": [
|
154 |
+
"# Load dataset\n",
|
155 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
156 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
157 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
158 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
159 |
+
"\n",
|
160 |
+
"# Load the tokenizer\n",
|
161 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-baseline-10-epochs\")\n",
|
162 |
+
"\n",
|
163 |
+
"# Preprocessing function\n",
|
164 |
+
"def preprocess_function(examples):\n",
|
165 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
166 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
167 |
+
" return tokenizer(\n",
|
168 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
169 |
+
" )\n",
|
170 |
+
"\n",
|
171 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
172 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
173 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
174 |
+
]
|
175 |
+
},
|
176 |
+
{
|
177 |
+
"cell_type": "markdown",
|
178 |
+
"metadata": {},
|
179 |
+
"source": [
|
180 |
+
"# With Pretrained Weights"
|
181 |
+
]
|
182 |
+
},
|
183 |
+
{
|
184 |
+
"cell_type": "code",
|
185 |
+
"execution_count": 5,
|
186 |
+
"metadata": {},
|
187 |
+
"outputs": [
|
188 |
+
{
|
189 |
+
"name": "stderr",
|
190 |
+
"output_type": "stream",
|
191 |
+
"text": [
|
192 |
+
"/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",
|
193 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
194 |
+
]
|
195 |
+
},
|
196 |
+
{
|
197 |
+
"data": {
|
198 |
+
"text/plain": [
|
199 |
+
"T5ClassificationModel(\n",
|
200 |
+
" (base_model): T5EncoderModel(\n",
|
201 |
+
" (shared): Embedding(32128, 512)\n",
|
202 |
+
" (encoder): T5Stack(\n",
|
203 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
204 |
+
" (block): ModuleList(\n",
|
205 |
+
" (0): T5Block(\n",
|
206 |
+
" (layer): ModuleList(\n",
|
207 |
+
" (0): T5LayerSelfAttention(\n",
|
208 |
+
" (SelfAttention): T5Attention(\n",
|
209 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
210 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
211 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
212 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
213 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
214 |
+
" )\n",
|
215 |
+
" (layer_norm): T5LayerNorm()\n",
|
216 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
217 |
+
" )\n",
|
218 |
+
" (1): T5LayerFF(\n",
|
219 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
220 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
221 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
222 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
223 |
+
" (act): ReLU()\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" )\n",
|
229 |
+
" )\n",
|
230 |
+
" (1-5): 5 x T5Block(\n",
|
231 |
+
" (layer): ModuleList(\n",
|
232 |
+
" (0): T5LayerSelfAttention(\n",
|
233 |
+
" (SelfAttention): T5Attention(\n",
|
234 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
235 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
236 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
237 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
238 |
+
" )\n",
|
239 |
+
" (layer_norm): T5LayerNorm()\n",
|
240 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
241 |
+
" )\n",
|
242 |
+
" (1): T5LayerFF(\n",
|
243 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
244 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
245 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
246 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
247 |
+
" (act): ReLU()\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" )\n",
|
253 |
+
" )\n",
|
254 |
+
" )\n",
|
255 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" )\n",
|
258 |
+
" )\n",
|
259 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
260 |
+
")"
|
261 |
+
]
|
262 |
+
},
|
263 |
+
"execution_count": 5,
|
264 |
+
"metadata": {},
|
265 |
+
"output_type": "execute_result"
|
266 |
+
}
|
267 |
+
],
|
268 |
+
"source": [
|
269 |
+
"classification_head_path = hf_hub_download(\n",
|
270 |
+
" repo_id=\"ppak10/defect-classification-t5-baseline-10-epochs\",\n",
|
271 |
+
" repo_type=\"model\",\n",
|
272 |
+
" filename=\"classification_head.pt\"\n",
|
273 |
+
")\n",
|
274 |
+
"\n",
|
275 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
276 |
+
"model.eval() # Set the model to evaluation mode"
|
277 |
+
]
|
278 |
+
},
|
279 |
+
{
|
280 |
+
"cell_type": "code",
|
281 |
+
"execution_count": 6,
|
282 |
+
"metadata": {},
|
283 |
+
"outputs": [
|
284 |
+
{
|
285 |
+
"name": "stderr",
|
286 |
+
"output_type": "stream",
|
287 |
+
"text": [
|
288 |
+
"100%|ββββββββββ| 142/142 [02:06<00:00, 1.12it/s]"
|
289 |
+
]
|
290 |
+
},
|
291 |
+
{
|
292 |
+
"name": "stdout",
|
293 |
+
"output_type": "stream",
|
294 |
+
"text": [
|
295 |
+
"Overall Accuracy: 0.7145567436282411\n"
|
296 |
+
]
|
297 |
+
},
|
298 |
+
{
|
299 |
+
"name": "stderr",
|
300 |
+
"output_type": "stream",
|
301 |
+
"text": [
|
302 |
+
"\n"
|
303 |
+
]
|
304 |
+
}
|
305 |
+
],
|
306 |
+
"source": [
|
307 |
+
"# Ensure the model is on the GPU\n",
|
308 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
309 |
+
"model = model.to(device)\n",
|
310 |
+
"\n",
|
311 |
+
"# Define the batch size\n",
|
312 |
+
"batch_size = 512\n",
|
313 |
+
"\n",
|
314 |
+
"# Create a DataLoader for the validation dataset\n",
|
315 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
316 |
+
"\n",
|
317 |
+
"def label_to_classifications_batch(labels):\n",
|
318 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
319 |
+
" \n",
|
320 |
+
" results = []\n",
|
321 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
322 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
323 |
+
" results.append(result)\n",
|
324 |
+
" return results\n",
|
325 |
+
"\n",
|
326 |
+
"accuracy_total = 0\n",
|
327 |
+
"\n",
|
328 |
+
"# Process the validation dataset in batches\n",
|
329 |
+
"for batch in tqdm(validation_loader):\n",
|
330 |
+
" texts = batch[\"text\"]\n",
|
331 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
332 |
+
"\n",
|
333 |
+
" # Move labels to GPU\n",
|
334 |
+
" # print(np.array(labels))\n",
|
335 |
+
" labels = torch.tensor(labels).to(device)\n",
|
336 |
+
"\n",
|
337 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
338 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
339 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
340 |
+
"\n",
|
341 |
+
" # Perform inference\n",
|
342 |
+
" outputs = model(**inputs)\n",
|
343 |
+
"\n",
|
344 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
345 |
+
" logits = outputs[\"logits\"]\n",
|
346 |
+
" probs = torch.sigmoid(logits)\n",
|
347 |
+
"\n",
|
348 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
349 |
+
" preds = (probs > 0.5).int()\n",
|
350 |
+
"\n",
|
351 |
+
" # Compute accuracy for the batch\n",
|
352 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
353 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
354 |
+
"\n",
|
355 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
356 |
+
"\n",
|
357 |
+
"# Calculate overall accuracy\n",
|
358 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
359 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
360 |
+
]
|
361 |
+
},
|
362 |
+
{
|
363 |
+
"cell_type": "code",
|
364 |
+
"execution_count": null,
|
365 |
+
"metadata": {},
|
366 |
+
"outputs": [],
|
367 |
+
"source": []
|
368 |
+
}
|
369 |
+
],
|
370 |
+
"metadata": {
|
371 |
+
"kernelspec": {
|
372 |
+
"display_name": "venv",
|
373 |
+
"language": "python",
|
374 |
+
"name": "python3"
|
375 |
+
},
|
376 |
+
"language_info": {
|
377 |
+
"codemirror_mode": {
|
378 |
+
"name": "ipython",
|
379 |
+
"version": 3
|
380 |
+
},
|
381 |
+
"file_extension": ".py",
|
382 |
+
"mimetype": "text/x-python",
|
383 |
+
"name": "python",
|
384 |
+
"nbconvert_exporter": "python",
|
385 |
+
"pygments_lexer": "ipython3",
|
386 |
+
"version": "3.10.12"
|
387 |
+
}
|
388 |
+
},
|
389 |
+
"nbformat": 4,
|
390 |
+
"nbformat_minor": 2
|
391 |
+
}
|
notebooks/t5_baseline_15_epochs.ipynb
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-baseline-15-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [],
|
153 |
+
"source": [
|
154 |
+
"# Load dataset\n",
|
155 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
156 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
157 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
158 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
159 |
+
"\n",
|
160 |
+
"# Load the tokenizer\n",
|
161 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-baseline-15-epochs\")\n",
|
162 |
+
"\n",
|
163 |
+
"# Preprocessing function\n",
|
164 |
+
"def preprocess_function(examples):\n",
|
165 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
166 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
167 |
+
" return tokenizer(\n",
|
168 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
169 |
+
" )\n",
|
170 |
+
"\n",
|
171 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
172 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
173 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
174 |
+
]
|
175 |
+
},
|
176 |
+
{
|
177 |
+
"cell_type": "markdown",
|
178 |
+
"metadata": {},
|
179 |
+
"source": [
|
180 |
+
"# With Pretrained Weights"
|
181 |
+
]
|
182 |
+
},
|
183 |
+
{
|
184 |
+
"cell_type": "code",
|
185 |
+
"execution_count": 5,
|
186 |
+
"metadata": {},
|
187 |
+
"outputs": [
|
188 |
+
{
|
189 |
+
"name": "stderr",
|
190 |
+
"output_type": "stream",
|
191 |
+
"text": [
|
192 |
+
"/tmp/ipykernel_519196/599386275.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",
|
193 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
194 |
+
]
|
195 |
+
},
|
196 |
+
{
|
197 |
+
"data": {
|
198 |
+
"text/plain": [
|
199 |
+
"T5ClassificationModel(\n",
|
200 |
+
" (base_model): T5EncoderModel(\n",
|
201 |
+
" (shared): Embedding(32128, 512)\n",
|
202 |
+
" (encoder): T5Stack(\n",
|
203 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
204 |
+
" (block): ModuleList(\n",
|
205 |
+
" (0): T5Block(\n",
|
206 |
+
" (layer): ModuleList(\n",
|
207 |
+
" (0): T5LayerSelfAttention(\n",
|
208 |
+
" (SelfAttention): T5Attention(\n",
|
209 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
210 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
211 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
212 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
213 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
214 |
+
" )\n",
|
215 |
+
" (layer_norm): T5LayerNorm()\n",
|
216 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
217 |
+
" )\n",
|
218 |
+
" (1): T5LayerFF(\n",
|
219 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
220 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
221 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
222 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
223 |
+
" (act): ReLU()\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" )\n",
|
229 |
+
" )\n",
|
230 |
+
" (1-5): 5 x T5Block(\n",
|
231 |
+
" (layer): ModuleList(\n",
|
232 |
+
" (0): T5LayerSelfAttention(\n",
|
233 |
+
" (SelfAttention): T5Attention(\n",
|
234 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
235 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
236 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
237 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
238 |
+
" )\n",
|
239 |
+
" (layer_norm): T5LayerNorm()\n",
|
240 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
241 |
+
" )\n",
|
242 |
+
" (1): T5LayerFF(\n",
|
243 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
244 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
245 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
246 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
247 |
+
" (act): ReLU()\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" )\n",
|
253 |
+
" )\n",
|
254 |
+
" )\n",
|
255 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" )\n",
|
258 |
+
" )\n",
|
259 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
260 |
+
")"
|
261 |
+
]
|
262 |
+
},
|
263 |
+
"execution_count": 5,
|
264 |
+
"metadata": {},
|
265 |
+
"output_type": "execute_result"
|
266 |
+
}
|
267 |
+
],
|
268 |
+
"source": [
|
269 |
+
"classification_head_path = hf_hub_download(\n",
|
270 |
+
" repo_id=\"ppak10/defect-classification-t5-baseline-15-epochs\",\n",
|
271 |
+
" repo_type=\"model\",\n",
|
272 |
+
" filename=\"classification_head.pt\"\n",
|
273 |
+
")\n",
|
274 |
+
"\n",
|
275 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
276 |
+
"model.eval() # Set the model to evaluation mode"
|
277 |
+
]
|
278 |
+
},
|
279 |
+
{
|
280 |
+
"cell_type": "code",
|
281 |
+
"execution_count": 6,
|
282 |
+
"metadata": {},
|
283 |
+
"outputs": [
|
284 |
+
{
|
285 |
+
"name": "stderr",
|
286 |
+
"output_type": "stream",
|
287 |
+
"text": [
|
288 |
+
"100%|ββββββββββ| 142/142 [01:58<00:00, 1.20it/s]"
|
289 |
+
]
|
290 |
+
},
|
291 |
+
{
|
292 |
+
"name": "stdout",
|
293 |
+
"output_type": "stream",
|
294 |
+
"text": [
|
295 |
+
"Overall Accuracy: 0.7642152465602866\n"
|
296 |
+
]
|
297 |
+
},
|
298 |
+
{
|
299 |
+
"name": "stderr",
|
300 |
+
"output_type": "stream",
|
301 |
+
"text": [
|
302 |
+
"\n"
|
303 |
+
]
|
304 |
+
}
|
305 |
+
],
|
306 |
+
"source": [
|
307 |
+
"# Ensure the model is on the GPU\n",
|
308 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
309 |
+
"model = model.to(device)\n",
|
310 |
+
"\n",
|
311 |
+
"# Define the batch size\n",
|
312 |
+
"batch_size = 512\n",
|
313 |
+
"\n",
|
314 |
+
"# Create a DataLoader for the validation dataset\n",
|
315 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
316 |
+
"\n",
|
317 |
+
"def label_to_classifications_batch(labels):\n",
|
318 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
319 |
+
" \n",
|
320 |
+
" results = []\n",
|
321 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
322 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
323 |
+
" results.append(result)\n",
|
324 |
+
" return results\n",
|
325 |
+
"\n",
|
326 |
+
"accuracy_total = 0\n",
|
327 |
+
"\n",
|
328 |
+
"# Process the validation dataset in batches\n",
|
329 |
+
"for batch in tqdm(validation_loader):\n",
|
330 |
+
" texts = batch[\"text\"]\n",
|
331 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
332 |
+
"\n",
|
333 |
+
" # Move labels to GPU\n",
|
334 |
+
" # print(np.array(labels))\n",
|
335 |
+
" labels = torch.tensor(labels).to(device)\n",
|
336 |
+
"\n",
|
337 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
338 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
339 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
340 |
+
"\n",
|
341 |
+
" # Perform inference\n",
|
342 |
+
" outputs = model(**inputs)\n",
|
343 |
+
"\n",
|
344 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
345 |
+
" logits = outputs[\"logits\"]\n",
|
346 |
+
" probs = torch.sigmoid(logits)\n",
|
347 |
+
"\n",
|
348 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
349 |
+
" preds = (probs > 0.5).int()\n",
|
350 |
+
"\n",
|
351 |
+
" # Compute accuracy for the batch\n",
|
352 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
353 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
354 |
+
"\n",
|
355 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
356 |
+
"\n",
|
357 |
+
"# Calculate overall accuracy\n",
|
358 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
359 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
360 |
+
]
|
361 |
+
},
|
362 |
+
{
|
363 |
+
"cell_type": "code",
|
364 |
+
"execution_count": null,
|
365 |
+
"metadata": {},
|
366 |
+
"outputs": [],
|
367 |
+
"source": []
|
368 |
+
}
|
369 |
+
],
|
370 |
+
"metadata": {
|
371 |
+
"kernelspec": {
|
372 |
+
"display_name": "venv",
|
373 |
+
"language": "python",
|
374 |
+
"name": "python3"
|
375 |
+
},
|
376 |
+
"language_info": {
|
377 |
+
"codemirror_mode": {
|
378 |
+
"name": "ipython",
|
379 |
+
"version": 3
|
380 |
+
},
|
381 |
+
"file_extension": ".py",
|
382 |
+
"mimetype": "text/x-python",
|
383 |
+
"name": "python",
|
384 |
+
"nbconvert_exporter": "python",
|
385 |
+
"pygments_lexer": "ipython3",
|
386 |
+
"version": "3.10.12"
|
387 |
+
}
|
388 |
+
},
|
389 |
+
"nbformat": 4,
|
390 |
+
"nbformat_minor": 2
|
391 |
+
}
|
notebooks/t5_baseline_20_epochs.ipynb
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-baseline-20-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [],
|
153 |
+
"source": [
|
154 |
+
"# Load dataset\n",
|
155 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
156 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
157 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
158 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
159 |
+
"\n",
|
160 |
+
"# Load the tokenizer\n",
|
161 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-baseline-20-epochs\")\n",
|
162 |
+
"\n",
|
163 |
+
"# Preprocessing function\n",
|
164 |
+
"def preprocess_function(examples):\n",
|
165 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
166 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
167 |
+
" return tokenizer(\n",
|
168 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
169 |
+
" )\n",
|
170 |
+
"\n",
|
171 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
172 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
173 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
174 |
+
]
|
175 |
+
},
|
176 |
+
{
|
177 |
+
"cell_type": "markdown",
|
178 |
+
"metadata": {},
|
179 |
+
"source": [
|
180 |
+
"# With Pretrained Weights"
|
181 |
+
]
|
182 |
+
},
|
183 |
+
{
|
184 |
+
"cell_type": "code",
|
185 |
+
"execution_count": 5,
|
186 |
+
"metadata": {},
|
187 |
+
"outputs": [
|
188 |
+
{
|
189 |
+
"name": "stderr",
|
190 |
+
"output_type": "stream",
|
191 |
+
"text": [
|
192 |
+
"/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",
|
193 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
194 |
+
]
|
195 |
+
},
|
196 |
+
{
|
197 |
+
"data": {
|
198 |
+
"text/plain": [
|
199 |
+
"T5ClassificationModel(\n",
|
200 |
+
" (base_model): T5EncoderModel(\n",
|
201 |
+
" (shared): Embedding(32128, 512)\n",
|
202 |
+
" (encoder): T5Stack(\n",
|
203 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
204 |
+
" (block): ModuleList(\n",
|
205 |
+
" (0): T5Block(\n",
|
206 |
+
" (layer): ModuleList(\n",
|
207 |
+
" (0): T5LayerSelfAttention(\n",
|
208 |
+
" (SelfAttention): T5Attention(\n",
|
209 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
210 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
211 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
212 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
213 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
214 |
+
" )\n",
|
215 |
+
" (layer_norm): T5LayerNorm()\n",
|
216 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
217 |
+
" )\n",
|
218 |
+
" (1): T5LayerFF(\n",
|
219 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
220 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
221 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
222 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
223 |
+
" (act): ReLU()\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" )\n",
|
229 |
+
" )\n",
|
230 |
+
" (1-5): 5 x T5Block(\n",
|
231 |
+
" (layer): ModuleList(\n",
|
232 |
+
" (0): T5LayerSelfAttention(\n",
|
233 |
+
" (SelfAttention): T5Attention(\n",
|
234 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
235 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
236 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
237 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
238 |
+
" )\n",
|
239 |
+
" (layer_norm): T5LayerNorm()\n",
|
240 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
241 |
+
" )\n",
|
242 |
+
" (1): T5LayerFF(\n",
|
243 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
244 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
245 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
246 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
247 |
+
" (act): ReLU()\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" )\n",
|
253 |
+
" )\n",
|
254 |
+
" )\n",
|
255 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" )\n",
|
258 |
+
" )\n",
|
259 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
260 |
+
")"
|
261 |
+
]
|
262 |
+
},
|
263 |
+
"execution_count": 5,
|
264 |
+
"metadata": {},
|
265 |
+
"output_type": "execute_result"
|
266 |
+
}
|
267 |
+
],
|
268 |
+
"source": [
|
269 |
+
"classification_head_path = hf_hub_download(\n",
|
270 |
+
" repo_id=\"ppak10/defect-classification-t5-baseline-20-epochs\",\n",
|
271 |
+
" repo_type=\"model\",\n",
|
272 |
+
" filename=\"classification_head.pt\"\n",
|
273 |
+
")\n",
|
274 |
+
"\n",
|
275 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
276 |
+
"model.eval() # Set the model to evaluation mode"
|
277 |
+
]
|
278 |
+
},
|
279 |
+
{
|
280 |
+
"cell_type": "code",
|
281 |
+
"execution_count": 6,
|
282 |
+
"metadata": {},
|
283 |
+
"outputs": [
|
284 |
+
{
|
285 |
+
"name": "stderr",
|
286 |
+
"output_type": "stream",
|
287 |
+
"text": [
|
288 |
+
"100%|ββββββββββ| 142/142 [02:06<00:00, 1.12it/s]"
|
289 |
+
]
|
290 |
+
},
|
291 |
+
{
|
292 |
+
"name": "stdout",
|
293 |
+
"output_type": "stream",
|
294 |
+
"text": [
|
295 |
+
"Overall Accuracy: 0.7792997584609419\n"
|
296 |
+
]
|
297 |
+
},
|
298 |
+
{
|
299 |
+
"name": "stderr",
|
300 |
+
"output_type": "stream",
|
301 |
+
"text": [
|
302 |
+
"\n"
|
303 |
+
]
|
304 |
+
}
|
305 |
+
],
|
306 |
+
"source": [
|
307 |
+
"# Ensure the model is on the GPU\n",
|
308 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
309 |
+
"model = model.to(device)\n",
|
310 |
+
"\n",
|
311 |
+
"# Define the batch size\n",
|
312 |
+
"batch_size = 512\n",
|
313 |
+
"\n",
|
314 |
+
"# Create a DataLoader for the validation dataset\n",
|
315 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
316 |
+
"\n",
|
317 |
+
"def label_to_classifications_batch(labels):\n",
|
318 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
319 |
+
" \n",
|
320 |
+
" results = []\n",
|
321 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
322 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
323 |
+
" results.append(result)\n",
|
324 |
+
" return results\n",
|
325 |
+
"\n",
|
326 |
+
"accuracy_total = 0\n",
|
327 |
+
"\n",
|
328 |
+
"# Process the validation dataset in batches\n",
|
329 |
+
"for batch in tqdm(validation_loader):\n",
|
330 |
+
" texts = batch[\"text\"]\n",
|
331 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
332 |
+
"\n",
|
333 |
+
" # Move labels to GPU\n",
|
334 |
+
" # print(np.array(labels))\n",
|
335 |
+
" labels = torch.tensor(labels).to(device)\n",
|
336 |
+
"\n",
|
337 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
338 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
339 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
340 |
+
"\n",
|
341 |
+
" # Perform inference\n",
|
342 |
+
" outputs = model(**inputs)\n",
|
343 |
+
"\n",
|
344 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
345 |
+
" logits = outputs[\"logits\"]\n",
|
346 |
+
" probs = torch.sigmoid(logits)\n",
|
347 |
+
"\n",
|
348 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
349 |
+
" preds = (probs > 0.5).int()\n",
|
350 |
+
"\n",
|
351 |
+
" # Compute accuracy for the batch\n",
|
352 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
353 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
354 |
+
"\n",
|
355 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
356 |
+
"\n",
|
357 |
+
"# Calculate overall accuracy\n",
|
358 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
359 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
360 |
+
]
|
361 |
+
},
|
362 |
+
{
|
363 |
+
"cell_type": "code",
|
364 |
+
"execution_count": null,
|
365 |
+
"metadata": {},
|
366 |
+
"outputs": [],
|
367 |
+
"source": []
|
368 |
+
}
|
369 |
+
],
|
370 |
+
"metadata": {
|
371 |
+
"kernelspec": {
|
372 |
+
"display_name": "venv",
|
373 |
+
"language": "python",
|
374 |
+
"name": "python3"
|
375 |
+
},
|
376 |
+
"language_info": {
|
377 |
+
"codemirror_mode": {
|
378 |
+
"name": "ipython",
|
379 |
+
"version": 3
|
380 |
+
},
|
381 |
+
"file_extension": ".py",
|
382 |
+
"mimetype": "text/x-python",
|
383 |
+
"name": "python",
|
384 |
+
"nbconvert_exporter": "python",
|
385 |
+
"pygments_lexer": "ipython3",
|
386 |
+
"version": "3.10.12"
|
387 |
+
}
|
388 |
+
},
|
389 |
+
"nbformat": 4,
|
390 |
+
"nbformat_minor": 2
|
391 |
+
}
|
notebooks/t5_baseline_20_epochs_prompt_input.ipynb
ADDED
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/mnt/am/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-baseline-20-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [
|
153 |
+
{
|
154 |
+
"name": "stderr",
|
155 |
+
"output_type": "stream",
|
156 |
+
"text": [
|
157 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [10:49<00:00, 62728.58 examples/s] \n",
|
158 |
+
"Map (num_proc=32): 100%|ββββββββββ| 1630710/1630710 [00:20<00:00, 77823.76 examples/s] \n",
|
159 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:07<00:00, 92553.48 examples/s] \n"
|
160 |
+
]
|
161 |
+
}
|
162 |
+
],
|
163 |
+
"source": [
|
164 |
+
"# Load dataset\n",
|
165 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
166 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
167 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
168 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
169 |
+
"\n",
|
170 |
+
"# Load the tokenizer\n",
|
171 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-baseline-20-epochs\")\n",
|
172 |
+
"\n",
|
173 |
+
"# Preprocessing function\n",
|
174 |
+
"def preprocess_function(examples):\n",
|
175 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
176 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
177 |
+
" return tokenizer(\n",
|
178 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
179 |
+
" )\n",
|
180 |
+
"\n",
|
181 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
182 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
183 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
184 |
+
]
|
185 |
+
},
|
186 |
+
{
|
187 |
+
"cell_type": "markdown",
|
188 |
+
"metadata": {},
|
189 |
+
"source": [
|
190 |
+
"# With Pretrained Weights"
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"cell_type": "code",
|
195 |
+
"execution_count": 5,
|
196 |
+
"metadata": {},
|
197 |
+
"outputs": [
|
198 |
+
{
|
199 |
+
"name": "stderr",
|
200 |
+
"output_type": "stream",
|
201 |
+
"text": [
|
202 |
+
"/tmp/ipykernel_1923854/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",
|
203 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"data": {
|
208 |
+
"text/plain": [
|
209 |
+
"T5ClassificationModel(\n",
|
210 |
+
" (base_model): T5EncoderModel(\n",
|
211 |
+
" (shared): Embedding(32128, 512)\n",
|
212 |
+
" (encoder): T5Stack(\n",
|
213 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
214 |
+
" (block): ModuleList(\n",
|
215 |
+
" (0): T5Block(\n",
|
216 |
+
" (layer): ModuleList(\n",
|
217 |
+
" (0): T5LayerSelfAttention(\n",
|
218 |
+
" (SelfAttention): T5Attention(\n",
|
219 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
220 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
221 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
222 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
223 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" (1): T5LayerFF(\n",
|
229 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
230 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
231 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
232 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
233 |
+
" (act): ReLU()\n",
|
234 |
+
" )\n",
|
235 |
+
" (layer_norm): T5LayerNorm()\n",
|
236 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
237 |
+
" )\n",
|
238 |
+
" )\n",
|
239 |
+
" )\n",
|
240 |
+
" (1-5): 5 x T5Block(\n",
|
241 |
+
" (layer): ModuleList(\n",
|
242 |
+
" (0): T5LayerSelfAttention(\n",
|
243 |
+
" (SelfAttention): T5Attention(\n",
|
244 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
245 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
246 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
247 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" (1): T5LayerFF(\n",
|
253 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
254 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
255 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" (act): ReLU()\n",
|
258 |
+
" )\n",
|
259 |
+
" (layer_norm): T5LayerNorm()\n",
|
260 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
261 |
+
" )\n",
|
262 |
+
" )\n",
|
263 |
+
" )\n",
|
264 |
+
" )\n",
|
265 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
266 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
267 |
+
" )\n",
|
268 |
+
" )\n",
|
269 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
270 |
+
")"
|
271 |
+
]
|
272 |
+
},
|
273 |
+
"execution_count": 5,
|
274 |
+
"metadata": {},
|
275 |
+
"output_type": "execute_result"
|
276 |
+
}
|
277 |
+
],
|
278 |
+
"source": [
|
279 |
+
"classification_head_path = hf_hub_download(\n",
|
280 |
+
" repo_id=\"ppak10/defect-classification-t5-baseline-20-epochs\",\n",
|
281 |
+
" repo_type=\"model\",\n",
|
282 |
+
" filename=\"classification_head.pt\"\n",
|
283 |
+
")\n",
|
284 |
+
"\n",
|
285 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
286 |
+
"model.eval() # Set the model to evaluation mode"
|
287 |
+
]
|
288 |
+
},
|
289 |
+
{
|
290 |
+
"cell_type": "code",
|
291 |
+
"execution_count": 6,
|
292 |
+
"metadata": {},
|
293 |
+
"outputs": [
|
294 |
+
{
|
295 |
+
"name": "stderr",
|
296 |
+
"output_type": "stream",
|
297 |
+
"text": [
|
298 |
+
"100%|ββββββββββ| 1416/1416 [30:46<00:00, 1.30s/it]"
|
299 |
+
]
|
300 |
+
},
|
301 |
+
{
|
302 |
+
"name": "stdout",
|
303 |
+
"output_type": "stream",
|
304 |
+
"text": [
|
305 |
+
"Overall Accuracy: 0.7313918592589359\n"
|
306 |
+
]
|
307 |
+
},
|
308 |
+
{
|
309 |
+
"name": "stderr",
|
310 |
+
"output_type": "stream",
|
311 |
+
"text": [
|
312 |
+
"\n"
|
313 |
+
]
|
314 |
+
}
|
315 |
+
],
|
316 |
+
"source": [
|
317 |
+
"# Ensure the model is on the GPU\n",
|
318 |
+
"device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n",
|
319 |
+
"model = model.to(device)\n",
|
320 |
+
"\n",
|
321 |
+
"# Define the batch size\n",
|
322 |
+
"batch_size = 512\n",
|
323 |
+
"\n",
|
324 |
+
"# Create a DataLoader for the validation dataset\n",
|
325 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
326 |
+
"\n",
|
327 |
+
"def label_to_classifications_batch(labels):\n",
|
328 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
329 |
+
" \n",
|
330 |
+
" results = []\n",
|
331 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
332 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
333 |
+
" results.append(result)\n",
|
334 |
+
" return results\n",
|
335 |
+
"\n",
|
336 |
+
"accuracy_total = 0\n",
|
337 |
+
"\n",
|
338 |
+
"# Process the validation dataset in batches\n",
|
339 |
+
"for batch in tqdm(validation_loader):\n",
|
340 |
+
" texts = batch[\"text\"]\n",
|
341 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
342 |
+
"\n",
|
343 |
+
" # Move labels to GPU\n",
|
344 |
+
" # print(np.array(labels))\n",
|
345 |
+
" labels = torch.tensor(labels).to(device)\n",
|
346 |
+
"\n",
|
347 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
348 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
349 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
350 |
+
"\n",
|
351 |
+
" # Perform inference\n",
|
352 |
+
" outputs = model(**inputs)\n",
|
353 |
+
"\n",
|
354 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
355 |
+
" logits = outputs[\"logits\"]\n",
|
356 |
+
" probs = torch.sigmoid(logits)\n",
|
357 |
+
"\n",
|
358 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
359 |
+
" preds = (probs > 0.5).int()\n",
|
360 |
+
"\n",
|
361 |
+
" # Compute accuracy for the batch\n",
|
362 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
363 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
364 |
+
"\n",
|
365 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
366 |
+
"\n",
|
367 |
+
"# Calculate overall accuracy\n",
|
368 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
369 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
370 |
+
]
|
371 |
+
},
|
372 |
+
{
|
373 |
+
"cell_type": "code",
|
374 |
+
"execution_count": null,
|
375 |
+
"metadata": {},
|
376 |
+
"outputs": [],
|
377 |
+
"source": []
|
378 |
+
}
|
379 |
+
],
|
380 |
+
"metadata": {
|
381 |
+
"kernelspec": {
|
382 |
+
"display_name": "venv",
|
383 |
+
"language": "python",
|
384 |
+
"name": "python3"
|
385 |
+
},
|
386 |
+
"language_info": {
|
387 |
+
"codemirror_mode": {
|
388 |
+
"name": "ipython",
|
389 |
+
"version": 3
|
390 |
+
},
|
391 |
+
"file_extension": ".py",
|
392 |
+
"mimetype": "text/x-python",
|
393 |
+
"name": "python",
|
394 |
+
"nbconvert_exporter": "python",
|
395 |
+
"pygments_lexer": "ipython3",
|
396 |
+
"version": "3.10.12"
|
397 |
+
}
|
398 |
+
},
|
399 |
+
"nbformat": 4,
|
400 |
+
"nbformat_minor": 2
|
401 |
+
}
|
notebooks/t5_baseline_25_epochs.ipynb
ADDED
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-baseline-25-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [
|
153 |
+
{
|
154 |
+
"name": "stderr",
|
155 |
+
"output_type": "stream",
|
156 |
+
"text": [
|
157 |
+
"Map (num_proc=64): 100%|ββββββββββ| 543572/543572 [00:10<00:00, 53549.86 examples/s]\n",
|
158 |
+
"Map (num_proc=32): 100%|ββββββββββ| 108714/108714 [00:02<00:00, 45774.82 examples/s]\n",
|
159 |
+
"Map (num_proc=32): 100%|ββββββββββ| 72475/72475 [00:01<00:00, 44539.64 examples/s]\n"
|
160 |
+
]
|
161 |
+
}
|
162 |
+
],
|
163 |
+
"source": [
|
164 |
+
"# Load dataset\n",
|
165 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
166 |
+
"train_dataset = dataset[\"train_baseline\"]\n",
|
167 |
+
"test_dataset = dataset[\"test_baseline\"]\n",
|
168 |
+
"validation_dataset = dataset[\"validation_baseline\"]\n",
|
169 |
+
"\n",
|
170 |
+
"# Load the tokenizer\n",
|
171 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-baseline-25-epochs\")\n",
|
172 |
+
"\n",
|
173 |
+
"# Preprocessing function\n",
|
174 |
+
"def preprocess_function(examples):\n",
|
175 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
176 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
177 |
+
" return tokenizer(\n",
|
178 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
179 |
+
" )\n",
|
180 |
+
"\n",
|
181 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
182 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
183 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
184 |
+
]
|
185 |
+
},
|
186 |
+
{
|
187 |
+
"cell_type": "markdown",
|
188 |
+
"metadata": {},
|
189 |
+
"source": [
|
190 |
+
"# With Pretrained Weights"
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"cell_type": "code",
|
195 |
+
"execution_count": 6,
|
196 |
+
"metadata": {},
|
197 |
+
"outputs": [
|
198 |
+
{
|
199 |
+
"name": "stderr",
|
200 |
+
"output_type": "stream",
|
201 |
+
"text": [
|
202 |
+
"/tmp/ipykernel_564737/1234403580.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",
|
203 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"data": {
|
208 |
+
"text/plain": [
|
209 |
+
"T5ClassificationModel(\n",
|
210 |
+
" (base_model): T5EncoderModel(\n",
|
211 |
+
" (shared): Embedding(32128, 512)\n",
|
212 |
+
" (encoder): T5Stack(\n",
|
213 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
214 |
+
" (block): ModuleList(\n",
|
215 |
+
" (0): T5Block(\n",
|
216 |
+
" (layer): ModuleList(\n",
|
217 |
+
" (0): T5LayerSelfAttention(\n",
|
218 |
+
" (SelfAttention): T5Attention(\n",
|
219 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
220 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
221 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
222 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
223 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" (1): T5LayerFF(\n",
|
229 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
230 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
231 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
232 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
233 |
+
" (act): ReLU()\n",
|
234 |
+
" )\n",
|
235 |
+
" (layer_norm): T5LayerNorm()\n",
|
236 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
237 |
+
" )\n",
|
238 |
+
" )\n",
|
239 |
+
" )\n",
|
240 |
+
" (1-5): 5 x T5Block(\n",
|
241 |
+
" (layer): ModuleList(\n",
|
242 |
+
" (0): T5LayerSelfAttention(\n",
|
243 |
+
" (SelfAttention): T5Attention(\n",
|
244 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
245 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
246 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
247 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" (1): T5LayerFF(\n",
|
253 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
254 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
255 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" (act): ReLU()\n",
|
258 |
+
" )\n",
|
259 |
+
" (layer_norm): T5LayerNorm()\n",
|
260 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
261 |
+
" )\n",
|
262 |
+
" )\n",
|
263 |
+
" )\n",
|
264 |
+
" )\n",
|
265 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
266 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
267 |
+
" )\n",
|
268 |
+
" )\n",
|
269 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
270 |
+
")"
|
271 |
+
]
|
272 |
+
},
|
273 |
+
"execution_count": 6,
|
274 |
+
"metadata": {},
|
275 |
+
"output_type": "execute_result"
|
276 |
+
}
|
277 |
+
],
|
278 |
+
"source": [
|
279 |
+
"classification_head_path = hf_hub_download(\n",
|
280 |
+
" repo_id=\"ppak10/defect-classification-t5-baseline-25-epochs\",\n",
|
281 |
+
" repo_type=\"model\",\n",
|
282 |
+
" filename=\"classification_head.pt\"\n",
|
283 |
+
")\n",
|
284 |
+
"\n",
|
285 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
286 |
+
"model.eval() # Set the model to evaluation mode"
|
287 |
+
]
|
288 |
+
},
|
289 |
+
{
|
290 |
+
"cell_type": "code",
|
291 |
+
"execution_count": 7,
|
292 |
+
"metadata": {},
|
293 |
+
"outputs": [
|
294 |
+
{
|
295 |
+
"name": "stderr",
|
296 |
+
"output_type": "stream",
|
297 |
+
"text": [
|
298 |
+
"100%|ββββββββββ| 142/142 [03:50<00:00, 1.63s/it]"
|
299 |
+
]
|
300 |
+
},
|
301 |
+
{
|
302 |
+
"name": "stdout",
|
303 |
+
"output_type": "stream",
|
304 |
+
"text": [
|
305 |
+
"Overall Accuracy: 0.7141462572536291\n"
|
306 |
+
]
|
307 |
+
},
|
308 |
+
{
|
309 |
+
"name": "stderr",
|
310 |
+
"output_type": "stream",
|
311 |
+
"text": [
|
312 |
+
"\n"
|
313 |
+
]
|
314 |
+
}
|
315 |
+
],
|
316 |
+
"source": [
|
317 |
+
"# Ensure the model is on the GPU\n",
|
318 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
319 |
+
"model = model.to(device)\n",
|
320 |
+
"\n",
|
321 |
+
"# Define the batch size\n",
|
322 |
+
"batch_size = 512\n",
|
323 |
+
"\n",
|
324 |
+
"# Create a DataLoader for the validation dataset\n",
|
325 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
326 |
+
"\n",
|
327 |
+
"def label_to_classifications_batch(labels):\n",
|
328 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
329 |
+
" \n",
|
330 |
+
" results = []\n",
|
331 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
332 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
333 |
+
" results.append(result)\n",
|
334 |
+
" return results\n",
|
335 |
+
"\n",
|
336 |
+
"accuracy_total = 0\n",
|
337 |
+
"\n",
|
338 |
+
"# Process the validation dataset in batches\n",
|
339 |
+
"for batch in tqdm(validation_loader):\n",
|
340 |
+
" texts = batch[\"text\"]\n",
|
341 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
342 |
+
"\n",
|
343 |
+
" # Move labels to GPU\n",
|
344 |
+
" # print(np.array(labels))\n",
|
345 |
+
" labels = torch.tensor(labels).to(device)\n",
|
346 |
+
"\n",
|
347 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
348 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
349 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
350 |
+
"\n",
|
351 |
+
" # Perform inference\n",
|
352 |
+
" outputs = model(**inputs)\n",
|
353 |
+
"\n",
|
354 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
355 |
+
" logits = outputs[\"logits\"]\n",
|
356 |
+
" probs = torch.sigmoid(logits)\n",
|
357 |
+
"\n",
|
358 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
359 |
+
" preds = (probs > 0.5).int()\n",
|
360 |
+
"\n",
|
361 |
+
" # Compute accuracy for the batch\n",
|
362 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
363 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
364 |
+
"\n",
|
365 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
366 |
+
"\n",
|
367 |
+
"# Calculate overall accuracy\n",
|
368 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
369 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
370 |
+
]
|
371 |
+
},
|
372 |
+
{
|
373 |
+
"cell_type": "code",
|
374 |
+
"execution_count": null,
|
375 |
+
"metadata": {},
|
376 |
+
"outputs": [],
|
377 |
+
"source": []
|
378 |
+
}
|
379 |
+
],
|
380 |
+
"metadata": {
|
381 |
+
"kernelspec": {
|
382 |
+
"display_name": "venv",
|
383 |
+
"language": "python",
|
384 |
+
"name": "python3"
|
385 |
+
},
|
386 |
+
"language_info": {
|
387 |
+
"codemirror_mode": {
|
388 |
+
"name": "ipython",
|
389 |
+
"version": 3
|
390 |
+
},
|
391 |
+
"file_extension": ".py",
|
392 |
+
"mimetype": "text/x-python",
|
393 |
+
"name": "python",
|
394 |
+
"nbconvert_exporter": "python",
|
395 |
+
"pygments_lexer": "ipython3",
|
396 |
+
"version": "3.10.12"
|
397 |
+
}
|
398 |
+
},
|
399 |
+
"nbformat": 4,
|
400 |
+
"nbformat_minor": 2
|
401 |
+
}
|
notebooks/t5_prompt_02_epochs.ipynb
ADDED
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/mnt/am/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/mnt/am/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-prompt-02-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [
|
153 |
+
{
|
154 |
+
"name": "stderr",
|
155 |
+
"output_type": "stream",
|
156 |
+
"text": [
|
157 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [04:22<00:00, 155050.79 examples/s]\n",
|
158 |
+
"Map (num_proc=32): 100%|ββββββββββ| 1630710/1630710 [00:16<00:00, 100029.00 examples/s]\n",
|
159 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:07<00:00, 101785.47 examples/s]\n"
|
160 |
+
]
|
161 |
+
}
|
162 |
+
],
|
163 |
+
"source": [
|
164 |
+
"# Load dataset\n",
|
165 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
166 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
167 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
168 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
169 |
+
"\n",
|
170 |
+
"# Load the tokenizer\n",
|
171 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-prompt-02-epochs\")\n",
|
172 |
+
"\n",
|
173 |
+
"# Preprocessing function\n",
|
174 |
+
"def preprocess_function(examples):\n",
|
175 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
176 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
177 |
+
" return tokenizer(\n",
|
178 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
179 |
+
" )\n",
|
180 |
+
"\n",
|
181 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
182 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
183 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
184 |
+
]
|
185 |
+
},
|
186 |
+
{
|
187 |
+
"cell_type": "markdown",
|
188 |
+
"metadata": {},
|
189 |
+
"source": [
|
190 |
+
"# With Pretrained Weights"
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"cell_type": "code",
|
195 |
+
"execution_count": 6,
|
196 |
+
"metadata": {},
|
197 |
+
"outputs": [
|
198 |
+
{
|
199 |
+
"name": "stderr",
|
200 |
+
"output_type": "stream",
|
201 |
+
"text": [
|
202 |
+
"/tmp/ipykernel_1581909/817923638.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",
|
203 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"data": {
|
208 |
+
"text/plain": [
|
209 |
+
"T5ClassificationModel(\n",
|
210 |
+
" (base_model): T5EncoderModel(\n",
|
211 |
+
" (shared): Embedding(32128, 512)\n",
|
212 |
+
" (encoder): T5Stack(\n",
|
213 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
214 |
+
" (block): ModuleList(\n",
|
215 |
+
" (0): T5Block(\n",
|
216 |
+
" (layer): ModuleList(\n",
|
217 |
+
" (0): T5LayerSelfAttention(\n",
|
218 |
+
" (SelfAttention): T5Attention(\n",
|
219 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
220 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
221 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
222 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
223 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" (1): T5LayerFF(\n",
|
229 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
230 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
231 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
232 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
233 |
+
" (act): ReLU()\n",
|
234 |
+
" )\n",
|
235 |
+
" (layer_norm): T5LayerNorm()\n",
|
236 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
237 |
+
" )\n",
|
238 |
+
" )\n",
|
239 |
+
" )\n",
|
240 |
+
" (1-5): 5 x T5Block(\n",
|
241 |
+
" (layer): ModuleList(\n",
|
242 |
+
" (0): T5LayerSelfAttention(\n",
|
243 |
+
" (SelfAttention): T5Attention(\n",
|
244 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
245 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
246 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
247 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" (1): T5LayerFF(\n",
|
253 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
254 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
255 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" (act): ReLU()\n",
|
258 |
+
" )\n",
|
259 |
+
" (layer_norm): T5LayerNorm()\n",
|
260 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
261 |
+
" )\n",
|
262 |
+
" )\n",
|
263 |
+
" )\n",
|
264 |
+
" )\n",
|
265 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
266 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
267 |
+
" )\n",
|
268 |
+
" )\n",
|
269 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
270 |
+
")"
|
271 |
+
]
|
272 |
+
},
|
273 |
+
"execution_count": 6,
|
274 |
+
"metadata": {},
|
275 |
+
"output_type": "execute_result"
|
276 |
+
}
|
277 |
+
],
|
278 |
+
"source": [
|
279 |
+
"classification_head_path = hf_hub_download(\n",
|
280 |
+
" repo_id=\"ppak10/defect-classification-t5-prompt-02-epochs\",\n",
|
281 |
+
" repo_type=\"model\",\n",
|
282 |
+
" filename=\"classification_head.pt\"\n",
|
283 |
+
")\n",
|
284 |
+
"\n",
|
285 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
286 |
+
"model.eval() # Set the model to evaluation mode"
|
287 |
+
]
|
288 |
+
},
|
289 |
+
{
|
290 |
+
"cell_type": "code",
|
291 |
+
"execution_count": 7,
|
292 |
+
"metadata": {},
|
293 |
+
"outputs": [
|
294 |
+
{
|
295 |
+
"name": "stderr",
|
296 |
+
"output_type": "stream",
|
297 |
+
"text": [
|
298 |
+
"100%|ββββββββββ| 1415/1415 [20:28<00:00, 1.15it/s]"
|
299 |
+
]
|
300 |
+
},
|
301 |
+
{
|
302 |
+
"name": "stdout",
|
303 |
+
"output_type": "stream",
|
304 |
+
"text": [
|
305 |
+
"Overall Accuracy: 0.8813090371761586\n"
|
306 |
+
]
|
307 |
+
},
|
308 |
+
{
|
309 |
+
"name": "stderr",
|
310 |
+
"output_type": "stream",
|
311 |
+
"text": [
|
312 |
+
"\n"
|
313 |
+
]
|
314 |
+
}
|
315 |
+
],
|
316 |
+
"source": [
|
317 |
+
"# Ensure the model is on the GPU\n",
|
318 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
319 |
+
"model = model.to(device)\n",
|
320 |
+
"\n",
|
321 |
+
"# Define the batch size\n",
|
322 |
+
"batch_size = 512\n",
|
323 |
+
"\n",
|
324 |
+
"# Create a DataLoader for the validation dataset\n",
|
325 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
326 |
+
"\n",
|
327 |
+
"def label_to_classifications_batch(labels):\n",
|
328 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
329 |
+
" \n",
|
330 |
+
" results = []\n",
|
331 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
332 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
333 |
+
" results.append(result)\n",
|
334 |
+
" return results\n",
|
335 |
+
"\n",
|
336 |
+
"accuracy_total = 0\n",
|
337 |
+
"\n",
|
338 |
+
"# Process the validation dataset in batches\n",
|
339 |
+
"for batch in tqdm(validation_loader):\n",
|
340 |
+
" texts = batch[\"text\"]\n",
|
341 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
342 |
+
"\n",
|
343 |
+
" # Move labels to GPU\n",
|
344 |
+
" # print(np.array(labels))\n",
|
345 |
+
" labels = torch.tensor(labels).to(device)\n",
|
346 |
+
"\n",
|
347 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
348 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
349 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
350 |
+
"\n",
|
351 |
+
" # Perform inference\n",
|
352 |
+
" outputs = model(**inputs)\n",
|
353 |
+
"\n",
|
354 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
355 |
+
" logits = outputs[\"logits\"]\n",
|
356 |
+
" probs = torch.sigmoid(logits)\n",
|
357 |
+
"\n",
|
358 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
359 |
+
" preds = (probs > 0.5).int()\n",
|
360 |
+
"\n",
|
361 |
+
" # Compute accuracy for the batch\n",
|
362 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
363 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
364 |
+
"\n",
|
365 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
366 |
+
"\n",
|
367 |
+
"# Calculate overall accuracy\n",
|
368 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
369 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
370 |
+
]
|
371 |
+
},
|
372 |
+
{
|
373 |
+
"cell_type": "code",
|
374 |
+
"execution_count": null,
|
375 |
+
"metadata": {},
|
376 |
+
"outputs": [],
|
377 |
+
"source": []
|
378 |
+
}
|
379 |
+
],
|
380 |
+
"metadata": {
|
381 |
+
"kernelspec": {
|
382 |
+
"display_name": "venv",
|
383 |
+
"language": "python",
|
384 |
+
"name": "python3"
|
385 |
+
},
|
386 |
+
"language_info": {
|
387 |
+
"codemirror_mode": {
|
388 |
+
"name": "ipython",
|
389 |
+
"version": 3
|
390 |
+
},
|
391 |
+
"file_extension": ".py",
|
392 |
+
"mimetype": "text/x-python",
|
393 |
+
"name": "python",
|
394 |
+
"nbconvert_exporter": "python",
|
395 |
+
"pygments_lexer": "ipython3",
|
396 |
+
"version": "3.10.12"
|
397 |
+
}
|
398 |
+
},
|
399 |
+
"nbformat": 4,
|
400 |
+
"nbformat_minor": 2
|
401 |
+
}
|
notebooks/t5_prompt_05_epochs.ipynb
ADDED
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [
|
8 |
+
{
|
9 |
+
"name": "stderr",
|
10 |
+
"output_type": "stream",
|
11 |
+
"text": [
|
12 |
+
"/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",
|
13 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
14 |
+
]
|
15 |
+
}
|
16 |
+
],
|
17 |
+
"source": [
|
18 |
+
"import ast\n",
|
19 |
+
"import numpy as np\n",
|
20 |
+
"import random\n",
|
21 |
+
"import torch\n",
|
22 |
+
"\n",
|
23 |
+
"from datasets import load_dataset\n",
|
24 |
+
"from huggingface_hub import hf_hub_download\n",
|
25 |
+
"from torch.utils.data import DataLoader\n",
|
26 |
+
"from transformers import T5Tokenizer \n",
|
27 |
+
"from tqdm import tqdm\n",
|
28 |
+
"\n",
|
29 |
+
"from model.t5 import T5ClassificationModel"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": 2,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"# Set the seed for Python's random module\n",
|
39 |
+
"random.seed(42)\n",
|
40 |
+
"\n",
|
41 |
+
"# Set the seed for NumPy\n",
|
42 |
+
"np.random.seed(42)\n",
|
43 |
+
"\n",
|
44 |
+
"# Set the seed for PyTorch\n",
|
45 |
+
"torch.manual_seed(42)\n",
|
46 |
+
"\n",
|
47 |
+
"# Ensure reproducibility on GPUs\n",
|
48 |
+
"if torch.cuda.is_available():\n",
|
49 |
+
" torch.cuda.manual_seed(42)\n",
|
50 |
+
" torch.cuda.manual_seed_all(42) # For multi-GPU setups\n",
|
51 |
+
"\n",
|
52 |
+
"# Optional: Ensure deterministic behavior\n",
|
53 |
+
"torch.backends.cudnn.deterministic = True\n",
|
54 |
+
"torch.backends.cudnn.benchmark = False"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 3,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"name": "stderr",
|
64 |
+
"output_type": "stream",
|
65 |
+
"text": [
|
66 |
+
"/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",
|
67 |
+
" state_dict = torch.load(pytorch_model_path)\n"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"data": {
|
72 |
+
"text/plain": [
|
73 |
+
"T5ClassificationModel(\n",
|
74 |
+
" (base_model): T5EncoderModel(\n",
|
75 |
+
" (shared): Embedding(32128, 512)\n",
|
76 |
+
" (encoder): T5Stack(\n",
|
77 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
78 |
+
" (block): ModuleList(\n",
|
79 |
+
" (0): T5Block(\n",
|
80 |
+
" (layer): ModuleList(\n",
|
81 |
+
" (0): T5LayerSelfAttention(\n",
|
82 |
+
" (SelfAttention): T5Attention(\n",
|
83 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
84 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
85 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
86 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
87 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
88 |
+
" )\n",
|
89 |
+
" (layer_norm): T5LayerNorm()\n",
|
90 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
91 |
+
" )\n",
|
92 |
+
" (1): T5LayerFF(\n",
|
93 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
94 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
95 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
96 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
97 |
+
" (act): ReLU()\n",
|
98 |
+
" )\n",
|
99 |
+
" (layer_norm): T5LayerNorm()\n",
|
100 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
101 |
+
" )\n",
|
102 |
+
" )\n",
|
103 |
+
" )\n",
|
104 |
+
" (1-5): 5 x T5Block(\n",
|
105 |
+
" (layer): ModuleList(\n",
|
106 |
+
" (0): T5LayerSelfAttention(\n",
|
107 |
+
" (SelfAttention): T5Attention(\n",
|
108 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
109 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
110 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
111 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
112 |
+
" )\n",
|
113 |
+
" (layer_norm): T5LayerNorm()\n",
|
114 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
115 |
+
" )\n",
|
116 |
+
" (1): T5LayerFF(\n",
|
117 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
118 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
119 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
120 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
121 |
+
" (act): ReLU()\n",
|
122 |
+
" )\n",
|
123 |
+
" (layer_norm): T5LayerNorm()\n",
|
124 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
125 |
+
" )\n",
|
126 |
+
" )\n",
|
127 |
+
" )\n",
|
128 |
+
" )\n",
|
129 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
130 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
131 |
+
" )\n",
|
132 |
+
" )\n",
|
133 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
134 |
+
")"
|
135 |
+
]
|
136 |
+
},
|
137 |
+
"execution_count": 3,
|
138 |
+
"metadata": {},
|
139 |
+
"output_type": "execute_result"
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"source": [
|
143 |
+
"# Initialize the model\n",
|
144 |
+
"model = T5ClassificationModel(\"ppak10/defect-classification-t5-prompt-05-epochs\")\n",
|
145 |
+
"model.eval() # Set the model to evaluation mode"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "code",
|
150 |
+
"execution_count": 4,
|
151 |
+
"metadata": {},
|
152 |
+
"outputs": [
|
153 |
+
{
|
154 |
+
"name": "stderr",
|
155 |
+
"output_type": "stream",
|
156 |
+
"text": [
|
157 |
+
"Map (num_proc=64): 100%|ββββββββββ| 40767900/40767900 [17:41<00:00, 38416.97 examples/s]\n",
|
158 |
+
"Map (num_proc=32): 100%|ββββββββββ| 1630710/1630710 [00:54<00:00, 30168.99 examples/s]\n",
|
159 |
+
"Map (num_proc=32): 100%|ββββββββββ| 724750/724750 [00:25<00:00, 27965.39 examples/s]\n"
|
160 |
+
]
|
161 |
+
}
|
162 |
+
],
|
163 |
+
"source": [
|
164 |
+
"# Load dataset\n",
|
165 |
+
"dataset = load_dataset(\"ppak10/melt-pool-classification\")\n",
|
166 |
+
"train_dataset = dataset[\"train_prompt\"]\n",
|
167 |
+
"test_dataset = dataset[\"test_prompt\"]\n",
|
168 |
+
"validation_dataset = dataset[\"validation_prompt\"]\n",
|
169 |
+
"\n",
|
170 |
+
"# Load the tokenizer\n",
|
171 |
+
"tokenizer = T5Tokenizer.from_pretrained(\"ppak10/defect-classification-t5-prompt-05-epochs\")\n",
|
172 |
+
"\n",
|
173 |
+
"# Preprocessing function\n",
|
174 |
+
"def preprocess_function(examples):\n",
|
175 |
+
" examples[\"label\"] = [ast.literal_eval(label) for label in examples[\"label\"]]\n",
|
176 |
+
" examples[\"label\"] = [np.array(label, dtype=np.float32) for label in examples[\"label\"]]\n",
|
177 |
+
" return tokenizer(\n",
|
178 |
+
" examples[\"text\"], truncation=True, padding=\"max_length\", max_length=256\n",
|
179 |
+
" )\n",
|
180 |
+
"\n",
|
181 |
+
"train_dataset_tokenized = train_dataset.map(preprocess_function, batched=True, num_proc=64)\n",
|
182 |
+
"test_dataset_tokenized = test_dataset.map(preprocess_function, batched=True, num_proc=32)\n",
|
183 |
+
"validation_dataset_tokenized = validation_dataset.map(preprocess_function, batched=True, num_proc=32)"
|
184 |
+
]
|
185 |
+
},
|
186 |
+
{
|
187 |
+
"cell_type": "markdown",
|
188 |
+
"metadata": {},
|
189 |
+
"source": [
|
190 |
+
"# With Pretrained Weights"
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"cell_type": "code",
|
195 |
+
"execution_count": 5,
|
196 |
+
"metadata": {},
|
197 |
+
"outputs": [
|
198 |
+
{
|
199 |
+
"name": "stderr",
|
200 |
+
"output_type": "stream",
|
201 |
+
"text": [
|
202 |
+
"/tmp/ipykernel_3687333/3984333715.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",
|
203 |
+
" model.classifier.load_state_dict(torch.load(classification_head_path))\n"
|
204 |
+
]
|
205 |
+
},
|
206 |
+
{
|
207 |
+
"data": {
|
208 |
+
"text/plain": [
|
209 |
+
"T5ClassificationModel(\n",
|
210 |
+
" (base_model): T5EncoderModel(\n",
|
211 |
+
" (shared): Embedding(32128, 512)\n",
|
212 |
+
" (encoder): T5Stack(\n",
|
213 |
+
" (embed_tokens): Embedding(32128, 512)\n",
|
214 |
+
" (block): ModuleList(\n",
|
215 |
+
" (0): T5Block(\n",
|
216 |
+
" (layer): ModuleList(\n",
|
217 |
+
" (0): T5LayerSelfAttention(\n",
|
218 |
+
" (SelfAttention): T5Attention(\n",
|
219 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
220 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
221 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
222 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
223 |
+
" (relative_attention_bias): Embedding(32, 8)\n",
|
224 |
+
" )\n",
|
225 |
+
" (layer_norm): T5LayerNorm()\n",
|
226 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
227 |
+
" )\n",
|
228 |
+
" (1): T5LayerFF(\n",
|
229 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
230 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
231 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
232 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
233 |
+
" (act): ReLU()\n",
|
234 |
+
" )\n",
|
235 |
+
" (layer_norm): T5LayerNorm()\n",
|
236 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
237 |
+
" )\n",
|
238 |
+
" )\n",
|
239 |
+
" )\n",
|
240 |
+
" (1-5): 5 x T5Block(\n",
|
241 |
+
" (layer): ModuleList(\n",
|
242 |
+
" (0): T5LayerSelfAttention(\n",
|
243 |
+
" (SelfAttention): T5Attention(\n",
|
244 |
+
" (q): Linear(in_features=512, out_features=512, bias=False)\n",
|
245 |
+
" (k): Linear(in_features=512, out_features=512, bias=False)\n",
|
246 |
+
" (v): Linear(in_features=512, out_features=512, bias=False)\n",
|
247 |
+
" (o): Linear(in_features=512, out_features=512, bias=False)\n",
|
248 |
+
" )\n",
|
249 |
+
" (layer_norm): T5LayerNorm()\n",
|
250 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
251 |
+
" )\n",
|
252 |
+
" (1): T5LayerFF(\n",
|
253 |
+
" (DenseReluDense): T5DenseActDense(\n",
|
254 |
+
" (wi): Linear(in_features=512, out_features=2048, bias=False)\n",
|
255 |
+
" (wo): Linear(in_features=2048, out_features=512, bias=False)\n",
|
256 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
257 |
+
" (act): ReLU()\n",
|
258 |
+
" )\n",
|
259 |
+
" (layer_norm): T5LayerNorm()\n",
|
260 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
261 |
+
" )\n",
|
262 |
+
" )\n",
|
263 |
+
" )\n",
|
264 |
+
" )\n",
|
265 |
+
" (final_layer_norm): T5LayerNorm()\n",
|
266 |
+
" (dropout): Dropout(p=0.1, inplace=False)\n",
|
267 |
+
" )\n",
|
268 |
+
" )\n",
|
269 |
+
" (classifier): Linear(in_features=512, out_features=4, bias=True)\n",
|
270 |
+
")"
|
271 |
+
]
|
272 |
+
},
|
273 |
+
"execution_count": 5,
|
274 |
+
"metadata": {},
|
275 |
+
"output_type": "execute_result"
|
276 |
+
}
|
277 |
+
],
|
278 |
+
"source": [
|
279 |
+
"classification_head_path = hf_hub_download(\n",
|
280 |
+
" repo_id=\"ppak10/defect-classification-t5-prompt-05-epochs\",\n",
|
281 |
+
" repo_type=\"model\",\n",
|
282 |
+
" filename=\"classification_head.pt\"\n",
|
283 |
+
")\n",
|
284 |
+
"\n",
|
285 |
+
"model.classifier.load_state_dict(torch.load(classification_head_path))\n",
|
286 |
+
"model.eval() # Set the model to evaluation mode"
|
287 |
+
]
|
288 |
+
},
|
289 |
+
{
|
290 |
+
"cell_type": "code",
|
291 |
+
"execution_count": 6,
|
292 |
+
"metadata": {},
|
293 |
+
"outputs": [
|
294 |
+
{
|
295 |
+
"name": "stderr",
|
296 |
+
"output_type": "stream",
|
297 |
+
"text": [
|
298 |
+
"100%|ββββββββββ| 1416/1416 [15:42<00:00, 1.50it/s]"
|
299 |
+
]
|
300 |
+
},
|
301 |
+
{
|
302 |
+
"name": "stdout",
|
303 |
+
"output_type": "stream",
|
304 |
+
"text": [
|
305 |
+
"Overall Accuracy: 0.8219775784724579\n"
|
306 |
+
]
|
307 |
+
},
|
308 |
+
{
|
309 |
+
"name": "stderr",
|
310 |
+
"output_type": "stream",
|
311 |
+
"text": [
|
312 |
+
"\n"
|
313 |
+
]
|
314 |
+
}
|
315 |
+
],
|
316 |
+
"source": [
|
317 |
+
"# Ensure the model is on the GPU\n",
|
318 |
+
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
|
319 |
+
"model = model.to(device)\n",
|
320 |
+
"\n",
|
321 |
+
"# Define the batch size\n",
|
322 |
+
"batch_size = 512\n",
|
323 |
+
"\n",
|
324 |
+
"# Create a DataLoader for the validation dataset\n",
|
325 |
+
"validation_loader = DataLoader(validation_dataset_tokenized, batch_size=batch_size, shuffle=False)\n",
|
326 |
+
"\n",
|
327 |
+
"def label_to_classifications_batch(labels):\n",
|
328 |
+
" classifications = [\"Desirable\", \"Keyhole\", \"Lack of Fusion\", \"Balling\"]\n",
|
329 |
+
" \n",
|
330 |
+
" results = []\n",
|
331 |
+
" for label in labels: # Iterate over each label in the batch\n",
|
332 |
+
" result = [classifications[index] for index, encoding in enumerate(label) if encoding == 1]\n",
|
333 |
+
" results.append(result)\n",
|
334 |
+
" return results\n",
|
335 |
+
"\n",
|
336 |
+
"accuracy_total = 0\n",
|
337 |
+
"\n",
|
338 |
+
"# Process the validation dataset in batches\n",
|
339 |
+
"for batch in tqdm(validation_loader):\n",
|
340 |
+
" texts = batch[\"text\"]\n",
|
341 |
+
" labels = np.array(batch[\"label\"]).T\n",
|
342 |
+
"\n",
|
343 |
+
" # Move labels to GPU\n",
|
344 |
+
" # print(np.array(labels))\n",
|
345 |
+
" labels = torch.tensor(labels).to(device)\n",
|
346 |
+
"\n",
|
347 |
+
" # Tokenize input for the entire batch and move to GPU\n",
|
348 |
+
" inputs = tokenizer(list(texts), return_tensors=\"pt\", truncation=True, padding=\"max_length\", max_length=256)\n",
|
349 |
+
" inputs = {key: value.to(device) for key, value in inputs.items()}\n",
|
350 |
+
"\n",
|
351 |
+
" # Perform inference\n",
|
352 |
+
" outputs = model(**inputs)\n",
|
353 |
+
"\n",
|
354 |
+
" # Extract logits and apply sigmoid activation for multi-label classification\n",
|
355 |
+
" logits = outputs[\"logits\"]\n",
|
356 |
+
" probs = torch.sigmoid(logits)\n",
|
357 |
+
"\n",
|
358 |
+
" # Convert probabilities to one-hot encoded labels\n",
|
359 |
+
" preds = (probs > 0.5).int()\n",
|
360 |
+
"\n",
|
361 |
+
" # Compute accuracy for the batch\n",
|
362 |
+
" accuracy_per_label = (preds == labels).float().mean(dim=1) # Mean per sample\n",
|
363 |
+
" accuracy_batch_mean = accuracy_per_label.mean().item() # Mean for the batch\n",
|
364 |
+
"\n",
|
365 |
+
" accuracy_total += accuracy_batch_mean * len(labels) # Weighted addition for overall accuracy\n",
|
366 |
+
"\n",
|
367 |
+
"# Calculate overall accuracy\n",
|
368 |
+
"overall_accuracy = accuracy_total / len(validation_dataset_tokenized)\n",
|
369 |
+
"print(f\"Overall Accuracy: {overall_accuracy}\")"
|
370 |
+
]
|
371 |
+
},
|
372 |
+
{
|
373 |
+
"cell_type": "code",
|
374 |
+
"execution_count": null,
|
375 |
+
"metadata": {},
|
376 |
+
"outputs": [],
|
377 |
+
"source": []
|
378 |
+
}
|
379 |
+
],
|
380 |
+
"metadata": {
|
381 |
+
"kernelspec": {
|
382 |
+
"display_name": "venv",
|
383 |
+
"language": "python",
|
384 |
+
"name": "python3"
|
385 |
+
},
|
386 |
+
"language_info": {
|
387 |
+
"codemirror_mode": {
|
388 |
+
"name": "ipython",
|
389 |
+
"version": 3
|
390 |
+
},
|
391 |
+
"file_extension": ".py",
|
392 |
+
"mimetype": "text/x-python",
|
393 |
+
"name": "python",
|
394 |
+
"nbconvert_exporter": "python",
|
395 |
+
"pygments_lexer": "ipython3",
|
396 |
+
"version": "3.10.16"
|
397 |
+
}
|
398 |
+
},
|
399 |
+
"nbformat": 4,
|
400 |
+
"nbformat_minor": 2
|
401 |
+
}
|
start_server.sh
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
#!/bin/bash
|
2 |
JUPYTER_TOKEN="${JUPYTER_TOKEN:=huggingface}"
|
3 |
|
4 |
-
NOTEBOOK_DIR="
|
5 |
|
6 |
jupyter labextension disable "@jupyterlab/apputils-extension:announcements"
|
7 |
|
|
|
1 |
#!/bin/bash
|
2 |
JUPYTER_TOKEN="${JUPYTER_TOKEN:=huggingface}"
|
3 |
|
4 |
+
NOTEBOOK_DIR="./notebooks"
|
5 |
|
6 |
jupyter labextension disable "@jupyterlab/apputils-extension:announcements"
|
7 |
|