File size: 32,806 Bytes
cf449ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
531
532
533
534
535
536
537
538
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c656aead-5827-49aa-b231-0db4f22e0e63",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import zipfile\n",
    "import numpy as np\n",
    "import PIL.Image\n",
    "import torch\n",
    "from torch.utils.data import DataLoader\n",
    "#import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "\n",
    "# Assume MultiZipImageFolderDataset is already defined\n",
    "\n",
    "# Helper function to create random images and save them in zip files\n",
    "def create_test_zip_files(num_zips=2, num_images_per_zip=10, img_size=(64, 64)):\n",
    "    os.makedirs('test_data', exist_ok=True)\n",
    "    for i in range(num_zips):\n",
    "        zip_path = os.path.join('test_data', f'images_{i}.zip')\n",
    "        with zipfile.ZipFile(zip_path, 'w') as zip_file:\n",
    "            for j in range(num_images_per_zip):\n",
    "                img_array = np.random.randint(0, 255, (img_size[0], img_size[1], 3), dtype=np.uint8)\n",
    "                img = PIL.Image.fromarray(img_array)\n",
    "                img_name = f'image_{i}_{j}.png'\n",
    "                img_bytes = img.tobytes()\n",
    "                img.save(img_name)\n",
    "                \n",
    "                with open(img_name, 'rb') as f:\n",
    "                    zip_file.writestr(img_name, f.read())\n",
    "                os.remove(img_name)\n",
    "\n",
    "# Function to display a batch of images\n",
    "def show_images(images):\n",
    "    fig, axes = plt.subplots(1, len(images), figsize=(15, 15))\n",
    "    for img, ax in zip(images, axes):\n",
    "        img = img.permute(1, 2, 0)  # CHW to HWC for displaying\n",
    "        ax.imshow(img)\n",
    "        ax.axis('off')\n",
    "    plt.show()\n",
    "\n",
    "# Step 1: Create test zip files\n",
    "create_test_zip_files(num_zips=3, num_images_per_zip=5, img_size=(64, 64))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4ff494a6-8b66-43dc-92c3-270ff38088d4",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "ename": "OSError",
     "evalue": "Path must point to a directory or zip",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mOSError\u001b[0m                                   Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[8], line 73\u001b[0m\n\u001b[1;32m     70\u001b[0m         \u001b[38;5;28;01mreturn\u001b[39;00m np\u001b[38;5;241m.\u001b[39mzeros([\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_raw_shape[\u001b[38;5;241m0\u001b[39m], \u001b[38;5;241m0\u001b[39m], dtype\u001b[38;5;241m=\u001b[39mnp\u001b[38;5;241m.\u001b[39mfloat32)  \u001b[38;5;66;03m# No labels\u001b[39;00m\n\u001b[1;32m     72\u001b[0m \u001b[38;5;66;03m# Usage Example\u001b[39;00m\n\u001b[0;32m---> 73\u001b[0m dataset \u001b[38;5;241m=\u001b[39m \u001b[43mMultiZipImageFolderDataset\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43m/usr/local/google/home/mingyuanzhou/SiD_google3_multinode/test_data/\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mresolution\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m64\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43muse_labels\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m)\u001b[49m\n\u001b[1;32m     74\u001b[0m dataloader \u001b[38;5;241m=\u001b[39m torch\u001b[38;5;241m.\u001b[39mutils\u001b[38;5;241m.\u001b[39mdata\u001b[38;5;241m.\u001b[39mDataLoader(dataset, batch_size\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m5\u001b[39m, shuffle\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n",
      "Cell \u001b[0;32mIn[8], line 27\u001b[0m, in \u001b[0;36mMultiZipImageFolderDataset.__init__\u001b[0;34m(self, path, resolution, use_labels, **super_kwargs)\u001b[0m\n\u001b[1;32m     25\u001b[0m     zip_paths \u001b[38;5;241m=\u001b[39m [\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_path]\n\u001b[1;32m     26\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m---> 27\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mIOError\u001b[39;00m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mPath must point to a directory or zip\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[1;32m     29\u001b[0m \u001b[38;5;66;03m# Make sure we have at least one zip file\u001b[39;00m\n\u001b[1;32m     30\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(zip_paths) \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m:\n",
      "\u001b[0;31mOSError\u001b[0m: Path must point to a directory or zip"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "abc69c5b-ad3b-4149-a177-ddec21c75089",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading image: 00000/img00000000.npy from zip: /usr/local/google/home/mingyuanzhou/Downloads/img512_split/dataset_part_01.zip\n"
     ]
    },
    {
     "ename": "UnidentifiedImageError",
     "evalue": "cannot identify image file <zipfile.ZipExtFile name='00000/img00000000.npy' mode='r'>",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mUnidentifiedImageError\u001b[0m                    Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[9], line 86\u001b[0m\n\u001b[1;32m     84\u001b[0m \u001b[38;5;66;03m# Iterate through the DataLoader\u001b[39;00m\n\u001b[1;32m     85\u001b[0m data_iter \u001b[38;5;241m=\u001b[39m \u001b[38;5;28miter\u001b[39m(dataloader)\n\u001b[0;32m---> 86\u001b[0m batch \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mnext\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mdata_iter\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     87\u001b[0m images, labels \u001b[38;5;241m=\u001b[39m batch  \u001b[38;5;66;03m# Unpack images and labels\u001b[39;00m\n\u001b[1;32m     89\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mBatch loaded. Image shapes:\u001b[39m\u001b[38;5;124m\"\u001b[39m, [img\u001b[38;5;241m.\u001b[39mshape \u001b[38;5;28;01mfor\u001b[39;00m img \u001b[38;5;129;01min\u001b[39;00m images])\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/torch/utils/data/dataloader.py:630\u001b[0m, in \u001b[0;36m_BaseDataLoaderIter.__next__\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m    627\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_sampler_iter \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m    628\u001b[0m     \u001b[38;5;66;03m# TODO(https://github.com/pytorch/pytorch/issues/76750)\u001b[39;00m\n\u001b[1;32m    629\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_reset()  \u001b[38;5;66;03m# type: ignore[call-arg]\u001b[39;00m\n\u001b[0;32m--> 630\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_next_data\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    631\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_num_yielded \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[1;32m    632\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_dataset_kind \u001b[38;5;241m==\u001b[39m _DatasetKind\u001b[38;5;241m.\u001b[39mIterable \u001b[38;5;129;01mand\u001b[39;00m \\\n\u001b[1;32m    633\u001b[0m         \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_IterableDataset_len_called \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \\\n\u001b[1;32m    634\u001b[0m         \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_num_yielded \u001b[38;5;241m>\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_IterableDataset_len_called:\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/torch/utils/data/dataloader.py:673\u001b[0m, in \u001b[0;36m_SingleProcessDataLoaderIter._next_data\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m    671\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_next_data\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[1;32m    672\u001b[0m     index \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_next_index()  \u001b[38;5;66;03m# may raise StopIteration\u001b[39;00m\n\u001b[0;32m--> 673\u001b[0m     data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_dataset_fetcher\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfetch\u001b[49m\u001b[43m(\u001b[49m\u001b[43mindex\u001b[49m\u001b[43m)\u001b[49m  \u001b[38;5;66;03m# may raise StopIteration\u001b[39;00m\n\u001b[1;32m    674\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_pin_memory:\n\u001b[1;32m    675\u001b[0m         data \u001b[38;5;241m=\u001b[39m _utils\u001b[38;5;241m.\u001b[39mpin_memory\u001b[38;5;241m.\u001b[39mpin_memory(data, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_pin_memory_device)\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/torch/utils/data/_utils/fetch.py:52\u001b[0m, in \u001b[0;36m_MapDatasetFetcher.fetch\u001b[0;34m(self, possibly_batched_index)\u001b[0m\n\u001b[1;32m     50\u001b[0m         data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset\u001b[38;5;241m.\u001b[39m__getitems__(possibly_batched_index)\n\u001b[1;32m     51\u001b[0m     \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m---> 52\u001b[0m         data \u001b[38;5;241m=\u001b[39m [\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdataset\u001b[49m\u001b[43m[\u001b[49m\u001b[43midx\u001b[49m\u001b[43m]\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m idx \u001b[38;5;129;01min\u001b[39;00m possibly_batched_index]\n\u001b[1;32m     53\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m     54\u001b[0m     data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset[possibly_batched_index]\n",
      "Cell \u001b[0;32mIn[9], line 73\u001b[0m, in \u001b[0;36mMultiZipImageFolderDataset.__getitem__\u001b[0;34m(self, idx)\u001b[0m\n\u001b[1;32m     72\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m__getitem__\u001b[39m(\u001b[38;5;28mself\u001b[39m, idx):\n\u001b[0;32m---> 73\u001b[0m     image \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_load_raw_image\u001b[49m\u001b[43m(\u001b[49m\u001b[43midx\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     74\u001b[0m     label \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39mzeros(\u001b[38;5;241m0\u001b[39m)  \u001b[38;5;66;03m# No labels for now\u001b[39;00m\n\u001b[1;32m     75\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m image, label\n",
      "Cell \u001b[0;32mIn[9], line 64\u001b[0m, in \u001b[0;36mMultiZipImageFolderDataset._load_raw_image\u001b[0;34m(self, raw_idx)\u001b[0m\n\u001b[1;32m     62\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mLoading image: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfname\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m from zip: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mzip_file\u001b[38;5;241m.\u001b[39mfilename\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m     63\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m zip_file\u001b[38;5;241m.\u001b[39mopen(fname) \u001b[38;5;28;01mas\u001b[39;00m f:\n\u001b[0;32m---> 64\u001b[0m     image \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39marray(\u001b[43mPIL\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mImage\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mopen\u001b[49m\u001b[43m(\u001b[49m\u001b[43mf\u001b[49m\u001b[43m)\u001b[49m)\n\u001b[1;32m     65\u001b[0m     image \u001b[38;5;241m=\u001b[39m image\u001b[38;5;241m.\u001b[39mtranspose(\u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m1\u001b[39m)  \u001b[38;5;66;03m# HWC to CHW\u001b[39;00m\n\u001b[1;32m     66\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m image\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/PIL/Image.py:3498\u001b[0m, in \u001b[0;36mopen\u001b[0;34m(fp, mode, formats)\u001b[0m\n\u001b[1;32m   3496\u001b[0m     warnings\u001b[38;5;241m.\u001b[39mwarn(message)\n\u001b[1;32m   3497\u001b[0m msg \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcannot identify image file \u001b[39m\u001b[38;5;132;01m%r\u001b[39;00m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;241m%\u001b[39m (filename \u001b[38;5;28;01mif\u001b[39;00m filename \u001b[38;5;28;01melse\u001b[39;00m fp)\n\u001b[0;32m-> 3498\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m UnidentifiedImageError(msg)\n",
      "\u001b[0;31mUnidentifiedImageError\u001b[0m: cannot identify image file <zipfile.ZipExtFile name='00000/img00000000.npy' mode='r'>"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import zipfile\n",
    "import PIL.Image\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils.data import Dataset\n",
    "\n",
    "class MultiZipImageFolderDataset(Dataset):\n",
    "    def __init__(self,\n",
    "        path_or_files,          # Path to directory or list of zip files.\n",
    "        resolution      = None, # Ensure specific resolution, None = anything goes.\n",
    "        use_labels      = False, # Disable labels by default.\n",
    "    ):\n",
    "        self._zipfiles = []     # List to store zipfile objects\n",
    "        self._zips_data = []    # List to store tuples of (zipfile, image_filenames)\n",
    "\n",
    "        # Check if input is a directory or a list of zip files\n",
    "        if isinstance(path_or_files, str) and os.path.isdir(path_or_files):\n",
    "            # If it's a directory, find all the zip files\n",
    "            zip_paths = sorted([os.path.join(path_or_files, f) for f in os.listdir(path_or_files) if f.endswith('.zip')])\n",
    "            if len(zip_paths) == 0:\n",
    "                raise IOError(f\"No zip files found in directory: {path_or_files}\")\n",
    "        elif isinstance(path_or_files, list):\n",
    "            # If it's a list of zip files, use it directly\n",
    "            zip_paths = path_or_files\n",
    "        else:\n",
    "            raise IOError('Input must be a directory or a list of zip files.')\n",
    "\n",
    "        # Gather all image filenames from each zip file\n",
    "        for zip_path in zip_paths:\n",
    "            zip_file = zipfile.ZipFile(zip_path)\n",
    "            fnames = set(zip_file.namelist())\n",
    "            supported_ext = PIL.Image.EXTENSION.keys() | {'.npy'}\n",
    "            image_fnames = sorted(fname for fname in fnames if self._file_ext(fname) in supported_ext)\n",
    "            if len(image_fnames) == 0:\n",
    "                continue  # Skip if no image files found\n",
    "            self._zipfiles.append(zip_file)\n",
    "            self._zips_data.append((zip_file, image_fnames))\n",
    "\n",
    "        # Initialize dataset size and shape\n",
    "        total_images = sum(len(fnames) for _, fnames in self._zips_data)\n",
    "        if total_images == 0:\n",
    "            raise IOError(\"No image files found across the zip files.\")\n",
    "        \n",
    "        # Assume all images have the same resolution\n",
    "        self.name = os.path.basename(zip_paths[0]) if isinstance(zip_paths[0], str) else 'multi_zip_dataset'\n",
    "        self._raw_shape = [total_images, 3, resolution, resolution]\n",
    "        self._use_labels = use_labels\n",
    "\n",
    "    @staticmethod\n",
    "    def _file_ext(fname):\n",
    "        return os.path.splitext(fname)[1].lower()\n",
    "\n",
    "    def _open_file(self, zip_file, fname):\n",
    "        return zip_file.open(fname, 'r')\n",
    "\n",
    "    def _load_raw_image(self, raw_idx):\n",
    "        cumulative_idx = 0\n",
    "        for zip_file, image_fnames in self._zips_data:\n",
    "            if raw_idx < cumulative_idx + len(image_fnames):\n",
    "                fname = image_fnames[raw_idx - cumulative_idx]\n",
    "                print(f\"Loading image: {fname} from zip: {zip_file.filename}\")\n",
    "                with zip_file.open(fname) as f:\n",
    "                    image = np.array(PIL.Image.open(f))\n",
    "                    image = image.transpose(2, 0, 1)  # HWC to CHW\n",
    "                return image\n",
    "            cumulative_idx += len(image_fnames)\n",
    "\n",
    "    def __len__(self):\n",
    "        return self._raw_shape[0]  # Return total number of images\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        image = self._load_raw_image(idx)\n",
    "        label = np.zeros(0)  # No labels for now\n",
    "        return image, label\n",
    "\n",
    "# Usage Example\n",
    "zip_files_dir = '/usr/local/google/home/mingyuanzhou/Downloads/img512_split/'\n",
    "dataset = MultiZipImageFolderDataset(zip_files_dir, resolution=64)\n",
    "\n",
    "# Create a DataLoader and fetch a batch\n",
    "dataloader = torch.utils.data.DataLoader(dataset, batch_size=5, shuffle=False)\n",
    "\n",
    "# Iterate through the DataLoader\n",
    "data_iter = iter(dataloader)\n",
    "batch = next(data_iter)\n",
    "images, labels = batch  # Unpack images and labels\n",
    "\n",
    "print(\"Batch loaded. Image shapes:\", [img.shape for img in images])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf85c9c2-2eb4-44e6-83b5-f21941516d01",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3093b92e-4661-4b31-b494-05c846b836d1",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "len(dataset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "651c125e-4fe9-458d-8b0c-5519dbb9da22",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 3 zip files.\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# Verify zip files in the directory\n",
    "zip_dir = '/usr/local/google/home/mingyuanzhou/SiD_google3_multinode/test_data/'\n",
    "zip_files = [f for f in os.listdir(zip_dir) if f.endswith('.zip')]\n",
    "\n",
    "if len(zip_files) == 0:\n",
    "    raise Exception(\"No zip files found in the directory.\")\n",
    "else:\n",
    "    print(f\"Found {len(zip_files)} zip files.\")\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3b74da59-f2e4-4331-bb13-24b6bdc2e24f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<__main__.MultiZipImageFolderDataset at 0x7f372f2bd610>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataset\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0ba70fc2-b518-456e-9f14-3602700efdbc",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "data_iter = iter(dataloader)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "a9222a9b-afb1-4636-b88a-1ff01a953f2f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<torch.utils.data.dataloader._SingleProcessDataLoaderIter at 0x7f37227a2510>"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data_iter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "9d13816b-fc9b-4b1f-a6be-bd973f667965",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[31], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m dataset \u001b[38;5;241m=\u001b[39m MultiZipImageFolderDataset(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m/usr/local/google/home/mingyuanzhou/SiD_google3_multinode/test_data/\u001b[39m\u001b[38;5;124m'\u001b[39m, resolution\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m64\u001b[39m, use_labels\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[1;32m      3\u001b[0m \u001b[38;5;66;03m# Try loading one image\u001b[39;00m\n\u001b[1;32m      4\u001b[0m image \u001b[38;5;241m=\u001b[39m dataset\u001b[38;5;241m.\u001b[39m_load_raw_image(\u001b[38;5;241m0\u001b[39m)\n",
      "Cell \u001b[0;32mIn[28], line 16\u001b[0m, in \u001b[0;36mMultiZipImageFolderDataset.__init__\u001b[0;34m(self, paths, resolution, **super_kwargs)\u001b[0m\n\u001b[1;32m     14\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39misdir(path):\n\u001b[1;32m     15\u001b[0m     file_type \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mdir\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[0;32m---> 16\u001b[0m     fnames \u001b[38;5;241m=\u001b[39m {os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mrelpath(os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mjoin(root, fname), start\u001b[38;5;241m=\u001b[39mpath) \u001b[38;5;28;01mfor\u001b[39;00m root, _dirs, files \u001b[38;5;129;01min\u001b[39;00m os\u001b[38;5;241m.\u001b[39mwalk(path) \u001b[38;5;28;01mfor\u001b[39;00m fname \u001b[38;5;129;01min\u001b[39;00m files}\n\u001b[1;32m     17\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_file_ext(path) \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124m.zip\u001b[39m\u001b[38;5;124m'\u001b[39m:\n\u001b[1;32m     18\u001b[0m     file_type \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mzip\u001b[39m\u001b[38;5;124m'\u001b[39m\n",
      "Cell \u001b[0;32mIn[28], line 16\u001b[0m, in \u001b[0;36m<setcomp>\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m     14\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39misdir(path):\n\u001b[1;32m     15\u001b[0m     file_type \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mdir\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[0;32m---> 16\u001b[0m     fnames \u001b[38;5;241m=\u001b[39m {os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mrelpath(os\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mjoin(root, fname), start\u001b[38;5;241m=\u001b[39mpath) \u001b[38;5;28;01mfor\u001b[39;00m root, _dirs, files \u001b[38;5;129;01min\u001b[39;00m os\u001b[38;5;241m.\u001b[39mwalk(path) \u001b[38;5;28;01mfor\u001b[39;00m fname \u001b[38;5;129;01min\u001b[39;00m files}\n\u001b[1;32m     17\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_file_ext(path) \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124m.zip\u001b[39m\u001b[38;5;124m'\u001b[39m:\n\u001b[1;32m     18\u001b[0m     file_type \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mzip\u001b[39m\u001b[38;5;124m'\u001b[39m\n",
      "File \u001b[0;32m<frozen os>:419\u001b[0m, in \u001b[0;36m_walk\u001b[0;34m(top, topdown, onerror, followlinks)\u001b[0m\n",
      "File \u001b[0;32m<frozen os>:419\u001b[0m, in \u001b[0;36m_walk\u001b[0;34m(top, topdown, onerror, followlinks)\u001b[0m\n",
      "    \u001b[0;31m[... skipping similar frames: _walk at line 419 (1 times)]\u001b[0m\n",
      "File \u001b[0;32m<frozen os>:419\u001b[0m, in \u001b[0;36m_walk\u001b[0;34m(top, topdown, onerror, followlinks)\u001b[0m\n",
      "File \u001b[0;32m<frozen os>:377\u001b[0m, in \u001b[0;36m_walk\u001b[0;34m(top, topdown, onerror, followlinks)\u001b[0m\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "dataset = MultiZipImageFolderDataset('/usr/local/google/home/mingyuanzhou/SiD_google3_multinode/test_data/', resolution=64, use_labels=False)\n",
    "\n",
    "# Try loading one image\n",
    "image = dataset._load_raw_image(0)\n",
    "print(\"Loaded image shape:\", image.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "67bff7a1-285e-48c5-b283-05b8fa3b7005",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Downloading: \"https://github.com/facebookresearch/dinov2/zipball/main\" to /usr/local/google/home/mingyuanzhou/.cache/torch/hub/main.zip\n",
      "/usr/local/google/home/mingyuanzhou/.cache/torch/hub/facebookresearch_dinov2_main/dinov2/layers/swiglu_ffn.py:51: UserWarning: xFormers is not available (SwiGLU)\n",
      "  warnings.warn(\"xFormers is not available (SwiGLU)\")\n",
      "/usr/local/google/home/mingyuanzhou/.cache/torch/hub/facebookresearch_dinov2_main/dinov2/layers/attention.py:33: UserWarning: xFormers is not available (Attention)\n",
      "  warnings.warn(\"xFormers is not available (Attention)\")\n",
      "/usr/local/google/home/mingyuanzhou/.cache/torch/hub/facebookresearch_dinov2_main/dinov2/layers/block.py:40: UserWarning: xFormers is not available (Block)\n",
      "  warnings.warn(\"xFormers is not available (Block)\")\n",
      "Downloading: \"https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth\" to /usr/local/google/home/mingyuanzhou/.cache/torch/hub/checkpoints/dinov2_vitl14_pretrain.pth\n",
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 1.13G/1.13G [00:08<00:00, 136MB/s]\n"
     ]
    }
   ],
   "source": [
    "dinov2_vitl14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a1787954-299d-497f-9134-ec2d167896a3",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'model' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[11], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mmodel\u001b[49m\u001b[38;5;241m.\u001b[39mload_state_dict(torch\u001b[38;5;241m.\u001b[39mload(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m/usr/local/google/home/mingyuanzhou/.cache/torch/hub/checkpoints/dinov2_vitl14_pretrain.pth\u001b[39m\u001b[38;5;124m'\u001b[39m))\n",
      "\u001b[0;31mNameError\u001b[0m: name 'model' is not defined"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "048e93f2-9556-4eed-a42f-0db1ef9fa2ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "from dinov2.models.vision_transformer import vit_large \n",
    "\n",
    "model = vit_large(\n",
    "    patch_size=14,\n",
    "    img_size=526,\n",
    "    init_values=1.0,\n",
    "    block_chunks=0\n",
    " )\n",
    "model.load_state_dict(torch.load('/usr/local/google/home/mingyuanzhou/.cache/torch/hub/checkpoints/dinov2_vitl14_pretrain.pth'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a05cea14-48fa-4e29-a2af-c47995e51f63",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_1579249/4014153075.py:1: 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('/usr/local/google/home/mingyuanzhou/.cache/torch/hub/checkpoints/dinov2_vitl14_pretrain.pth'))\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f98e3de1-a926-44af-b4f8-7f274aff7489",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DinoVisionTransformer(\n",
       "  (patch_embed): PatchEmbed(\n",
       "    (proj): Conv2d(3, 1024, kernel_size=(14, 14), stride=(14, 14))\n",
       "    (norm): Identity()\n",
       "  )\n",
       "  (blocks): ModuleList(\n",
       "    (0-23): 24 x NestedTensorBlock(\n",
       "      (norm1): LayerNorm((1024,), eps=1e-06, elementwise_affine=True)\n",
       "      (attn): MemEffAttention(\n",
       "        (qkv): Linear(in_features=1024, out_features=3072, bias=True)\n",
       "        (attn_drop): Dropout(p=0.0, inplace=False)\n",
       "        (proj): Linear(in_features=1024, out_features=1024, bias=True)\n",
       "        (proj_drop): Dropout(p=0.0, inplace=False)\n",
       "      )\n",
       "      (ls1): LayerScale()\n",
       "      (drop_path1): Identity()\n",
       "      (norm2): LayerNorm((1024,), eps=1e-06, elementwise_affine=True)\n",
       "      (mlp): Mlp(\n",
       "        (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n",
       "        (act): GELU(approximate='none')\n",
       "        (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n",
       "        (drop): Dropout(p=0.0, inplace=False)\n",
       "      )\n",
       "      (ls2): LayerScale()\n",
       "      (drop_path2): Identity()\n",
       "    )\n",
       "  )\n",
       "  (norm): LayerNorm((1024,), eps=1e-06, elementwise_affine=True)\n",
       "  (head): Identity()\n",
       ")"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "4277869a-b0ab-4acc-8e96-820a51a6de2c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/usr/local/google/home/mingyuanzhou/.cache/torch/hub\n"
     ]
    }
   ],
   "source": [
    "print(torch.hub.get_dir())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d5fc2d3-a3fb-4958-86d2-604d3d56ed1d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}