File size: 19,927 Bytes
6c17409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1e99de7a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2024-06-20 13:18:56--  https://docs-assets.developer.apple.com/ml-research/datasets/mobileclip/mobileclip_s0.pt\n",
      "Resolving docs-assets.developer.apple.com (docs-assets.developer.apple.com)... 17.253.73.203, 17.253.73.201\n",
      "Connecting to docs-assets.developer.apple.com (docs-assets.developer.apple.com)|17.253.73.203|:443... connected.\n",
      "HTTP request sent, awaiting response... 416 Requested Range Not Satisfiable\n",
      "\n",
      "    The file is already fully retrieved; nothing to do.\n",
      "\n",
      "--2024-06-20 13:18:58--  https://raw.githubusercontent.com/apple/ml-mobileclip/main/mobileclip/configs/mobileclip_s0.json\n",
      "Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\n",
      "Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 416 Range Not Satisfiable\n",
      "\n",
      "    The file is already fully retrieved; nothing to do.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#!git clone https://huggingface.co/spaces/depth-anything/Depth-Anything-V2\n",
    "#!pip install -r Depth-Anything-V2/requirements.txt\n",
    "#!pip install -q --upgrade coremltools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d6cb8a61",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "801db364",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "scikit-learn version 1.6.0 is not supported. Minimum required version: 0.17. Maximum required version: 1.5.1. Disabling scikit-learn conversion API.\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import coremltools as ct\n",
    "import numpy as np\n",
    "from PIL import Image\n",
    "import tempfile\n",
    "from huggingface_hub import hf_hub_download\n",
    "import sys\n",
    "sys.path.append('./Depth-Anything-V2')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "73882c02",
   "metadata": {},
   "outputs": [],
   "source": [
    "from depth_anything_v2.dpt import DepthAnythingV2\n",
    "from depth_anything_v2.util.transform import Resize, NormalizeImage, PrepareForNet\n",
    "\n",
    "import torch.nn.functional as F"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26f7dcff",
   "metadata": {},
   "source": [
    "# 1. Load Depth-Anything-V2's vitl checkpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e67aa722",
   "metadata": {},
   "outputs": [],
   "source": [
    "DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'\n",
    "model_configs = {\n",
    "    'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},\n",
    "    'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},\n",
    "    'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},\n",
    "    'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]}\n",
    "}\n",
    "encoder2name = {\n",
    "    'vits': 'Small',\n",
    "    'vitb': 'Base',\n",
    "    'vitl': 'Large',\n",
    "    'vitg': 'Giant', # we are undergoing company review procedures to release our giant model checkpoint\n",
    "}\n",
    "encoder = 'vitl'\n",
    "model_name = encoder2name[encoder]\n",
    "model = DepthAnythingV2(**model_configs[encoder])\n",
    "filepath = hf_hub_download(repo_id=f\"depth-anything/Depth-Anything-V2-{model_name}\", filename=f\"depth_anything_v2_{encoder}.pth\", repo_type=\"model\")\n",
    "state_dict = torch.load(filepath, map_location=\"cpu\")\n",
    "model.load_state_dict(state_dict)\n",
    "model = model.to(DEVICE).eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a632e6b4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3024, 4032, 3)\n"
     ]
    }
   ],
   "source": [
    "image = Image.open(\"./sample_images/IMG_4061.jpeg\")\n",
    "img = np.array(image)\n",
    "print(img.shape)\n",
    "h, w = img.shape[:2]\n",
    "depth = model.infer_image(img)\n",
    "depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0\n",
    "depth = depth.astype(np.uint8)\n",
    "depth_image = Image.fromarray(depth)\n",
    "depth_image.save(\"depth_image.jpg\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "77477217",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3024, 4032, 3)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/dadler/Projects/Glide/ai-bots/depth/./Depth-Anything-V2/depth_anything_v2/dinov2_layers/patch_embed.py:73: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n",
      "  assert H % patch_H == 0, f\"Input image height {H} is not a multiple of patch height {patch_H}\"\n",
      "/Users/dadler/Projects/Glide/ai-bots/depth/./Depth-Anything-V2/depth_anything_v2/dinov2_layers/patch_embed.py:74: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n",
      "  assert W % patch_W == 0, f\"Input image width {W} is not a multiple of patch width: {patch_W}\"\n",
      "/Users/dadler/Projects/Glide/ai-bots/depth/./Depth-Anything-V2/depth_anything_v2/dinov2.py:183: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n",
      "  if npatch == N and w == h:\n",
      "/Users/dadler/Projects/Glide/ai-bots/depth/./Depth-Anything-V2/depth_anything_v2/dpt.py:147: TracerWarning: Converting a tensor to a Python integer might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!\n",
      "  out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode=\"bilinear\", align_corners=True)\n"
     ]
    }
   ],
   "source": [
    "original_image = Image.open(\"./sample_images/IMG_4061.jpeg\")\n",
    "origina_img = np.array(original_image)\n",
    "print(origina_img.shape)\n",
    "original_h, original_w = origina_img.shape[:2]\n",
    "input_size = 518\n",
    "image = original_image.resize((input_size,input_size), Image.Resampling.BILINEAR)\n",
    "img = np.array(image)\n",
    "input_image, (h, w) = model.image2tensor(img, input_size)\n",
    "input_image = input_image.to(DEVICE)\n",
    "with torch.no_grad():\n",
    "    depth = model(input_image)\n",
    "    depth = F.interpolate(depth[:, None], (h, w), mode=\"bilinear\", align_corners=True)[0, 0]\n",
    "    depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0\n",
    "    depth = depth.cpu().numpy().astype(np.uint8)\n",
    "depth_image = Image.fromarray(depth).resize((original_w,original_h), Image.Resampling.BILINEAR)\n",
    "depth_image.save(\"depth_image_2.jpg\")\n",
    "\n",
    "traced_model = torch.jit.trace(model, input_image)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "42632870",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Traced PyTorch ImageEncoder ckpt out for jpg:\n",
      ">>> tensor([[3.8735, 3.9076, 4.0226,  ..., 1.8554, 1.7260, 2.5633],\n",
      "        [4.3636, 4.1100, 4.1624,  ..., 2.1774, 2.2929, 2.2913],\n",
      "        [4.3914, 4.2280, 4.2901,  ..., 2.3076, 2.3133, 2.2698],\n",
      "        ...,\n",
      "        [5.8771, 5.8192, 5.8249,  ..., 3.9578, 3.9079, 3.7710],\n",
      "        [6.1631, 6.1475, 6.1688,  ..., 4.2481, 4.2320, 4.0410],\n",
      "        [6.4769, 6.4864, 6.4850,  ..., 4.6766, 4.6218, 4.4442]],\n",
      "       device='mps:0', grad_fn=<SliceBackward0>)\n"
     ]
    }
   ],
   "source": [
    "example_output = traced_model(input_image)\n",
    "print(\"Traced PyTorch ImageEncoder ckpt out for jpg:\\n>>>\", example_output[0, :10])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c0d9c70",
   "metadata": {},
   "source": [
    "You can see that there is some loss in precision, but it is still acceptable."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca182b4a",
   "metadata": {},
   "source": [
    "# 2. Export ImageEncoder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "ef7af5c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "image_means = [0.485, 0.456, 0.406]\n",
    "image_stds = [0.229, 0.224, 0.225]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "8f66a99c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torchvision.transforms as transforms\n",
    "\n",
    "class Wrapper(torch.nn.Module):    \n",
    "    def __init__(self, model):\n",
    "        super().__init__()\n",
    "        _means = image_means\n",
    "        _stds = image_stds\n",
    "        self.model = model   \n",
    "        self.stds = torch.tensor(_stds).half()[:,None,None]\n",
    "        self.means = torch.tensor(_means).half()[:,None,None]\n",
    "\n",
    "    transform_model = torch.nn.Sequential(\n",
    "        transforms.Normalize(mean=image_means, std=image_stds)\n",
    "                             )\n",
    "\n",
    "    def forward(self, input):        \n",
    "        input = input/255.0\n",
    "        intput = self.transform_model(input)\n",
    "        output = self.model(input)\n",
    "        output = (output - output.min()) / (output.max() - output.min())        \n",
    "        # Fix \"Image output, 'depthOutput', must have rank 4. Instead it has rank 3\"\n",
    "        output = output.unsqueeze(0)\n",
    "        # Fix \"Shape of the RGB/BGR image output, 'depthOutput', must be of kind (1, 3, H, W), i.e., first two dimensions must be (1, 3), instead they are: (1, 1)\"ArithmeticError\n",
    "        output = output.repeat(1, 3, 1, 1)\n",
    "        output = output * 255.0\n",
    "        return output\n",
    "\n",
    "# Instantiate the Wrapper model passing the original PyTorch FCN model\n",
    "wrapped_model = Wrapper(traced_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "b3da3350",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "wrapped PyTorch ImageEncoder ckpt out for jpg:\n",
      ">>> tensor([[[1.3479e+00, 1.3024e+00, 1.3246e+00,  ..., 3.6170e-02,\n",
      "          1.2884e-01, 4.5228e-01],\n",
      "         [1.5584e+00, 1.4481e+00, 1.4059e+00,  ..., 3.4862e-01,\n",
      "          3.9270e-01, 3.3447e-01],\n",
      "         [1.6099e+00, 1.5023e+00, 1.5238e+00,  ..., 3.6392e-01,\n",
      "          3.8963e-01, 4.5296e-01],\n",
      "         ...,\n",
      "         [1.0288e+02, 1.0318e+02, 1.0304e+02,  ..., 1.0168e+02,\n",
      "          1.0194e+02, 1.0191e+02],\n",
      "         [1.0353e+02, 1.0333e+02, 1.0334e+02,  ..., 1.0216e+02,\n",
      "          1.0219e+02, 1.0212e+02],\n",
      "         [1.0339e+02, 1.0290e+02, 1.0300e+02,  ..., 1.0180e+02,\n",
      "          1.0220e+02, 1.0189e+02]],\n",
      "\n",
      "        [[1.3479e+00, 1.3024e+00, 1.3246e+00,  ..., 3.6170e-02,\n",
      "          1.2884e-01, 4.5228e-01],\n",
      "         [1.5584e+00, 1.4481e+00, 1.4059e+00,  ..., 3.4862e-01,\n",
      "          3.9270e-01, 3.3447e-01],\n",
      "         [1.6099e+00, 1.5023e+00, 1.5238e+00,  ..., 3.6392e-01,\n",
      "          3.8963e-01, 4.5296e-01],\n",
      "         ...,\n",
      "         [1.0288e+02, 1.0318e+02, 1.0304e+02,  ..., 1.0168e+02,\n",
      "          1.0194e+02, 1.0191e+02],\n",
      "         [1.0353e+02, 1.0333e+02, 1.0334e+02,  ..., 1.0216e+02,\n",
      "          1.0219e+02, 1.0212e+02],\n",
      "         [1.0339e+02, 1.0290e+02, 1.0300e+02,  ..., 1.0180e+02,\n",
      "          1.0220e+02, 1.0189e+02]],\n",
      "\n",
      "        [[1.3479e+00, 1.3024e+00, 1.3246e+00,  ..., 3.6170e-02,\n",
      "          1.2884e-01, 4.5228e-01],\n",
      "         [1.5584e+00, 1.4481e+00, 1.4059e+00,  ..., 3.4862e-01,\n",
      "          3.9270e-01, 3.3447e-01],\n",
      "         [1.6099e+00, 1.5023e+00, 1.5238e+00,  ..., 3.6392e-01,\n",
      "          3.8963e-01, 4.5296e-01],\n",
      "         ...,\n",
      "         [1.0288e+02, 1.0318e+02, 1.0304e+02,  ..., 1.0168e+02,\n",
      "          1.0194e+02, 1.0191e+02],\n",
      "         [1.0353e+02, 1.0333e+02, 1.0334e+02,  ..., 1.0216e+02,\n",
      "          1.0219e+02, 1.0212e+02],\n",
      "         [1.0339e+02, 1.0290e+02, 1.0300e+02,  ..., 1.0180e+02,\n",
      "          1.0220e+02, 1.0189e+02]]], device='mps:0')\n",
      "Traced wrapped PyTorch ImageEncoder ckpt out for jpg:\n",
      ">>> tensor([[[1.3479e+00, 1.3024e+00, 1.3246e+00,  ..., 3.6170e-02,\n",
      "          1.2884e-01, 4.5228e-01],\n",
      "         [1.5584e+00, 1.4481e+00, 1.4059e+00,  ..., 3.4862e-01,\n",
      "          3.9270e-01, 3.3447e-01],\n",
      "         [1.6099e+00, 1.5023e+00, 1.5238e+00,  ..., 3.6392e-01,\n",
      "          3.8963e-01, 4.5296e-01],\n",
      "         ...,\n",
      "         [1.0288e+02, 1.0318e+02, 1.0304e+02,  ..., 1.0168e+02,\n",
      "          1.0194e+02, 1.0191e+02],\n",
      "         [1.0353e+02, 1.0333e+02, 1.0334e+02,  ..., 1.0216e+02,\n",
      "          1.0219e+02, 1.0212e+02],\n",
      "         [1.0339e+02, 1.0290e+02, 1.0300e+02,  ..., 1.0180e+02,\n",
      "          1.0220e+02, 1.0189e+02]],\n",
      "\n",
      "        [[1.3479e+00, 1.3024e+00, 1.3246e+00,  ..., 3.6170e-02,\n",
      "          1.2884e-01, 4.5228e-01],\n",
      "         [1.5584e+00, 1.4481e+00, 1.4059e+00,  ..., 3.4862e-01,\n",
      "          3.9270e-01, 3.3447e-01],\n",
      "         [1.6099e+00, 1.5023e+00, 1.5238e+00,  ..., 3.6392e-01,\n",
      "          3.8963e-01, 4.5296e-01],\n",
      "         ...,\n",
      "         [1.0288e+02, 1.0318e+02, 1.0304e+02,  ..., 1.0168e+02,\n",
      "          1.0194e+02, 1.0191e+02],\n",
      "         [1.0353e+02, 1.0333e+02, 1.0334e+02,  ..., 1.0216e+02,\n",
      "          1.0219e+02, 1.0212e+02],\n",
      "         [1.0339e+02, 1.0290e+02, 1.0300e+02,  ..., 1.0180e+02,\n",
      "          1.0220e+02, 1.0189e+02]],\n",
      "\n",
      "        [[1.3479e+00, 1.3024e+00, 1.3246e+00,  ..., 3.6170e-02,\n",
      "          1.2884e-01, 4.5228e-01],\n",
      "         [1.5584e+00, 1.4481e+00, 1.4059e+00,  ..., 3.4862e-01,\n",
      "          3.9270e-01, 3.3447e-01],\n",
      "         [1.6099e+00, 1.5023e+00, 1.5238e+00,  ..., 3.6392e-01,\n",
      "          3.8963e-01, 4.5296e-01],\n",
      "         ...,\n",
      "         [1.0288e+02, 1.0318e+02, 1.0304e+02,  ..., 1.0168e+02,\n",
      "          1.0194e+02, 1.0191e+02],\n",
      "         [1.0353e+02, 1.0333e+02, 1.0334e+02,  ..., 1.0216e+02,\n",
      "          1.0219e+02, 1.0212e+02],\n",
      "         [1.0339e+02, 1.0290e+02, 1.0300e+02,  ..., 1.0180e+02,\n",
      "          1.0220e+02, 1.0189e+02]]], device='mps:0')\n"
     ]
    }
   ],
   "source": [
    "i = np.asarray(original_image.resize((518, 518)))\n",
    "i = i.astype(\"float32\")\n",
    "i = np.transpose(i, (2, 0, 1))\n",
    "i = np.expand_dims(i, 0)\n",
    "i = torch.from_numpy(i).to(DEVICE)\n",
    "\n",
    "with torch.no_grad():\n",
    "    out = wrapped_model(i)\n",
    "\n",
    "print(\"wrapped PyTorch ImageEncoder ckpt out for jpg:\\n>>>\", out[0, :10])\n",
    "\n",
    "traced_model_w = torch.jit.trace(wrapped_model, i)\n",
    "\n",
    "with torch.no_grad():\n",
    "    out = traced_model_w(i)\n",
    "\n",
    "print(\"Traced wrapped PyTorch ImageEncoder ckpt out for jpg:\\n>>>\", out[0, :10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "db5cb9b9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([1, 3, 518, 518]), torch.Size([1, 3, 518, 518]))"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "i.shape, out.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "id": "681683aa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 3, 518, 518) 255.0 0.0 104.07214\n",
      "(518, 518, 3) 255 0 103.57204722648738\n"
     ]
    }
   ],
   "source": [
    "tmp = out.cpu().numpy()\n",
    "\n",
    "print(tmp.shape, tmp.max(), tmp.min(), tmp.mean())\n",
    "# Convert to 3, 256, 256\n",
    "tmp = np.transpose(tmp, (0, 2, 3, 1)).astype(np.uint8)\n",
    "tmp = tmp.squeeze()\n",
    "print(tmp.shape, tmp.max(), tmp.min(), tmp.mean())\n",
    "Image.fromarray(tmp)\n",
    "tmp_image = Image.fromarray(tmp).resize((original_w,original_h))\n",
    "tmp_image.save(\"depth_image_3.png\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "9e4f00bd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([1, 3, 518, 518])"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "i.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "304ae7b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Converting PyTorch Frontend ==> MIL Ops: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‰| 1247/1248 [00:00<00:00, 6927.17 ops/s]\n",
      "Running MIL frontend_pytorch pipeline: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 5/5 [00:00<00:00, 90.46 passes/s]\n",
      "Running MIL default pipeline: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 89/89 [00:06<00:00, 13.75 passes/s]\n",
      "Running MIL backend_mlprogram pipeline: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 12/12 [00:00<00:00, 99.10 passes/s]\n"
     ]
    }
   ],
   "source": [
    "traced_model_w.eval()\n",
    "image_input = ct.ImageType(name=\"colorImage\", shape=i.shape)\n",
    "image_encoder_model = ct.converters.convert(\n",
    "    traced_model_w,\n",
    "    convert_to=\"mlprogram\",\n",
    "    inputs=[image_input],\n",
    "    outputs=[ct.ImageType(name=\"depthOutput\")],\n",
    "    minimum_deployment_target=ct.target.iOS16,\n",
    ")\n",
    "image_encoder_model.save(\"DepthAnything_v2_large.mlpackage\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch2",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}