File size: 7,941 Bytes
7b58366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7d672
 
0da089d
 
7e7d672
 
0da089d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b58366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7d672
 
 
7b58366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7d672
 
 
 
7b58366
 
 
7e7d672
7b58366
7e7d672
 
 
 
7b58366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Train the Model"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "source": [
    "import torch\n",
    "from train_model import train_model\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torch.optim import lr_scheduler\n",
    "from model import build_hybrid_model\n",
    "import pennylane as qml\n",
    "\n",
    "STEP = 0.0004  # Learning rate\n",
    "BATCH_SIZE = 4  # Number of samples for each training step\n",
    "N_QUBITS = 4\n",
    "NUM_EPOCHS = 3  # Number of training epochs\n",
    "GAMMA_LR_SCHEDULER = 0.1  # Learning rate reduction applied every 10 epochs.\n",
    "PARAMETER_FILEPATH = \"state.pt\" # \n",
    "IF_INITIAL_TRAIN = False # Whether this is the first time training the model\n",
    "\n",
    "# Initialize Pennylane backend\n",
    "dev = qml.device(\"default.qubit\", wires=N_QUBITS)\n",
    "\n",
    "# Initialize PyTorch config\n",
    "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "# Load Model\n",
    "model = build_hybrid_model(\n",
    "    pennylane_dev=dev,\n",
    "    device=device,\n",
    "    n_qubits=N_QUBITS,\n",
    "    q_depth=6,\n",
    "    q_delta=0.01\n",
    ")\n",
    "\n",
    "if not IF_INITIAL_TRAIN:\n",
    "    # Load Model Weights from Disk\n",
    "    print(\"Loading Model Weights from Disk...\")\n",
    "    model.load_state_dict(torch.load(PARAMETER_FILEPATH))\n",
    "\n",
    "# Define Loss for Training\n",
    "criterion = nn.CrossEntropyLoss()\n",
    "optimizer_hybrid = optim.Adam(model.fc.parameters(), lr=STEP)\n",
    "exp_lr_scheduler = lr_scheduler.StepLR(\n",
    "    optimizer_hybrid, step_size=10, gamma=GAMMA_LR_SCHEDULER\n",
    ")\n",
    "\n",
    "# Train the Model\n",
    "trained_model = train_model(\n",
    "    model=model, \n",
    "    criterion=criterion, \n",
    "    optimizer=optimizer_hybrid, \n",
    "    scheduler=exp_lr_scheduler, \n",
    "    num_epochs=NUM_EPOCHS,\n",
    "    batch_size=BATCH_SIZE,\n",
    "    device=device\n",
    ")\n",
    "\n",
    "# Save Model Parameters to Disk\n",
    "print(\"Saving Model Weights to Disk...\")\n",
    "torch.save(trained_model.state_dict(), PARAMETER_FILEPATH)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-09-11T22:38:45.705122Z",
     "start_time": "2024-09-11T22:16:02.896239Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\MaxHu\\anaconda3\\envs\\quantum-env\\lib\\site-packages\\torchvision\\models\\_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.\n",
      "  warnings.warn(\n",
      "C:\\Users\\MaxHu\\anaconda3\\envs\\quantum-env\\lib\\site-packages\\torchvision\\models\\_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=ResNet18_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet18_Weights.DEFAULT` to get the most up-to-date weights.\n",
      "  warnings.warn(msg)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading Model Weights from Disk...\n",
      "Training started:\n",
      "Data Loading Completed in 0m 0s\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\MaxHu\\AppData\\Local\\Temp\\ipykernel_12896\\449253314.py:35: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
      "  model.load_state_dict(torch.load(PARAMETER_FILEPATH))\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Phase: train Epoch: 1/3 Loss: 0.8986 Acc: 0.5877        33\n",
      "Phase: validation   Epoch: 1/3 Loss: 1.9974 Acc: 0.3929        \n",
      "Phase: train Epoch: 2/3 Loss: 0.8994 Acc: 0.5849        76\n",
      "Phase: validation   Epoch: 2/3 Loss: 1.9718 Acc: 0.3929        \n",
      "Phase: train Epoch: 3/3 Loss: 0.8977 Acc: 0.5860        76\n",
      "Phase: validation   Epoch: 3/3 Loss: 2.0105 Acc: 0.3750        \n",
      "Training Completed in 22m 34s\n",
      "Best test loss: 1.9718 | Best test accuracy: 0.3929\n",
      "Saving Model Weights to Disk...\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "cell_type": "markdown",
   "source": [
    "# Visualize a Batch of Predictions"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "source": [
    "from helpers import visualize_model\n",
    "import torch\n",
    "from train_model import train_model\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torch.optim import lr_scheduler\n",
    "from model import build_hybrid_model\n",
    "import pennylane as qml\n",
    "\n",
    "BATCH_SIZE = 4\n",
    "N_QUBITS = 4\n",
    "PARAMETER_FILEPATH = \"state.pt\"\n",
    "\n",
    "# Initialize Pennylane backend\n",
    "dev = qml.device(\"default.qubit\", wires=N_QUBITS)\n",
    "\n",
    "# Initialize PyTorch config\n",
    "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "# Load Model\n",
    "model = build_hybrid_model(\n",
    "    pennylane_dev=dev,\n",
    "    device=device,\n",
    "    n_qubits=N_QUBITS,\n",
    "    q_depth=6,\n",
    "    q_delta=0.01\n",
    ")\n",
    "\n",
    "# Load Model Weights from Disk\n",
    "print(\"Loading Model Weights from Disk...\")\n",
    "model.load_state_dict(torch.load(PARAMETER_FILEPATH))\n",
    "\n",
    "visualize_model(\n",
    "    model=model,\n",
    "    device=device,\n",
    "    batch_size=BATCH_SIZE\n",
    ")"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "source": [
    "# Prediction Test"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "source": [
    "from generate_prediction import generate_prediction\n",
    "pred = generate_prediction(\"./image.jpeg\")\n",
    "print(\"PREDICTION:\",pred)"
   ],
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "source": "from app import *",
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "markdown",
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "quantum-env",
   "language": "python",
   "name": "quantum-env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}