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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "d0b72877",
6
+ "metadata": {},
7
+ "source": [
8
+ "# VQGAN JAX Encoding for 🤗 Datasets in streaming mode"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "ba7b31e6",
14
+ "metadata": {},
15
+ "source": [
16
+ "This notebook shows how to pre-encode images to token sequences using JAX, VQGAN and 🤗 Datasets in streaming mode.\n",
17
+ "\n",
18
+ "This example uses our YFCC100M dataset, but it should be easy to adapt to any other image/caption dataset in the huggingface hub."
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "id": "3b59489e",
25
+ "metadata": {},
26
+ "outputs": [],
27
+ "source": [
28
+ "import io\n",
29
+ "\n",
30
+ "import requests\n",
31
+ "from PIL import Image\n",
32
+ "import numpy as np\n",
33
+ "from tqdm import tqdm\n",
34
+ "\n",
35
+ "import torch\n",
36
+ "import torchvision.transforms as T\n",
37
+ "import torchvision.transforms.functional as TF\n",
38
+ "from torchvision.transforms import InterpolationMode\n",
39
+ "import os\n",
40
+ "\n",
41
+ "import jax\n",
42
+ "from jax import pmap"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "markdown",
47
+ "id": "c7c4c1e6",
48
+ "metadata": {},
49
+ "source": [
50
+ "## Dataset and Parameters"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "execution_count": null,
56
+ "id": "d45a289e",
57
+ "metadata": {},
58
+ "outputs": [],
59
+ "source": [
60
+ "import datasets\n",
61
+ "from datasets import Dataset, load_dataset"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "markdown",
66
+ "id": "f26e4f18",
67
+ "metadata": {},
68
+ "source": [
69
+ "We'll use the `validation` set for testing. Adjust accordingly."
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "execution_count": null,
75
+ "id": "28893c3e",
76
+ "metadata": {},
77
+ "outputs": [],
78
+ "source": [
79
+ "dataset = load_dataset('dalle-mini/YFCC100M_OpenAI_subset', use_auth_token=True, streaming=True, split='validation')"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "id": "33861477",
86
+ "metadata": {},
87
+ "outputs": [],
88
+ "source": [
89
+ "from pathlib import Path\n",
90
+ "\n",
91
+ "yfcc100m = Path.home()/'data'/'YFCC100M_OpenAI_subset'\n",
92
+ "yfcc100m_output = yfcc100m/'encoded' # Output directory for encoded files"
93
+ ]
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "execution_count": null,
98
+ "id": "6e7b71c4",
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "batch_size = 128 # Per device\n",
103
+ "num_workers = 16 # Unused in streaming mode"
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "markdown",
108
+ "id": "0793c26a",
109
+ "metadata": {},
110
+ "source": [
111
+ "### Data preparation"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "markdown",
116
+ "id": "86415769",
117
+ "metadata": {},
118
+ "source": [
119
+ "* Images: we transform them so they are center-cropped and square, all of the same size so we can build batches for TPU/GPU processing.\n",
120
+ "* Captions: we extract a single `caption` column from the source data, by concatenating the cleaned title and description.\n",
121
+ "\n",
122
+ "These transformations are done using the Datasets `map` function. In the case of streaming datasets, transformations will run as needed instead of pre-processing the dataset at once."
123
+ ]
124
+ },
125
+ {
126
+ "cell_type": "markdown",
127
+ "id": "0fdf1851",
128
+ "metadata": {},
129
+ "source": [
130
+ "This helper function is used to decode images from the bytes retrieved in `streaming` mode."
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": null,
136
+ "id": "5bbca804",
137
+ "metadata": {},
138
+ "outputs": [],
139
+ "source": [
140
+ "from PIL import Image\n",
141
+ "import io\n",
142
+ "\n",
143
+ "def get_image(byte_stream):\n",
144
+ " image = Image.open(io.BytesIO(byte_stream))\n",
145
+ " return image.convert('RGB')"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "markdown",
150
+ "id": "b435290b",
151
+ "metadata": {},
152
+ "source": [
153
+ "Image processing"
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "execution_count": null,
159
+ "id": "7e73dfa3",
160
+ "metadata": {},
161
+ "outputs": [],
162
+ "source": [
163
+ "def center_crop(image, max_size=256):\n",
164
+ " # Note: we allow upscaling too. We should exclude small images. \n",
165
+ " image = TF.resize(image, max_size, interpolation=InterpolationMode.LANCZOS)\n",
166
+ " image = TF.center_crop(image, output_size=2 * [max_size])\n",
167
+ " return image\n",
168
+ "\n",
169
+ "preprocess_image = T.Compose([\n",
170
+ " get_image,\n",
171
+ " center_crop,\n",
172
+ " T.ToTensor(),\n",
173
+ " lambda t: t.permute(1, 2, 0) # Reorder, we need dimensions last\n",
174
+ "])"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "markdown",
179
+ "id": "1e3ac8de",
180
+ "metadata": {},
181
+ "source": [
182
+ "Caption preparation"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "id": "aadb4d23",
189
+ "metadata": {},
190
+ "outputs": [],
191
+ "source": [
192
+ "import string\n",
193
+ "\n",
194
+ "def create_caption(title, description):\n",
195
+ " title = title.strip()\n",
196
+ " description = description.strip()\n",
197
+ " if len(title) > 0 and title[-1] not in '.!?': title += '.'\n",
198
+ " return f'{title} {description}'"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "markdown",
203
+ "id": "3c4522b9",
204
+ "metadata": {},
205
+ "source": [
206
+ "And this is the basic transformation function to use in `map`. We don't really need the `key`, but we'll keep it for reference. Since we are returning a new dictionary (as opposed to adding entries to the input), this also removes any metadata columns we don't need."
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": null,
212
+ "id": "2566ff68",
213
+ "metadata": {},
214
+ "outputs": [],
215
+ "source": [
216
+ "def prepare_item(item):\n",
217
+ " return {\n",
218
+ " 'key': item['key'],\n",
219
+ " 'caption': create_caption(item['title_clean'], item['description_clean']),\n",
220
+ " 'image': preprocess_image(item['img'])\n",
221
+ " }"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "markdown",
226
+ "id": "e519e475",
227
+ "metadata": {},
228
+ "source": [
229
+ "Unlike when using non-streaming datasets, the following operation completes immediately in streaming mode. In streaming mode, `num_proc` is not supported."
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "execution_count": null,
235
+ "id": "10d7750e",
236
+ "metadata": {},
237
+ "outputs": [],
238
+ "source": [
239
+ "prepared_dataset = dataset.map(prepare_item, batched=False)"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "execution_count": null,
245
+ "id": "a8595539",
246
+ "metadata": {},
247
+ "outputs": [],
248
+ "source": [
249
+ "%%time\n",
250
+ "item = next(iter(prepared_dataset))"
251
+ ]
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "execution_count": null,
256
+ "id": "04a6eeb4",
257
+ "metadata": {},
258
+ "outputs": [],
259
+ "source": [
260
+ "assert(list(item.keys()) == ['key', 'caption', 'image'])"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "execution_count": null,
266
+ "id": "40d3115f",
267
+ "metadata": {},
268
+ "outputs": [],
269
+ "source": [
270
+ "item['image'].shape"
271
+ ]
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "execution_count": null,
276
+ "id": "dd844e1c",
277
+ "metadata": {},
278
+ "outputs": [],
279
+ "source": [
280
+ "T.ToPILImage()(item['image'].permute(2, 0, 1))"
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "markdown",
285
+ "id": "44d50a51",
286
+ "metadata": {},
287
+ "source": [
288
+ "### Torch DataLoader"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "markdown",
293
+ "id": "17a4bbc6",
294
+ "metadata": {},
295
+ "source": [
296
+ "We'll create a PyTorch DataLoader for convenience. This allows us to easily take batches of our desired size.\n",
297
+ "\n",
298
+ "We won't be using parallel processing of the DataLoader for now, as the items will be retrieved on the fly. We could attempt to do it using these recommendations: https://pytorch.org/docs/stable/data.html#multi-process-data-loading. For performance considerations, please refer to this thread: https://discuss.huggingface.co/t/allow-streaming-of-large-datasets-with-image-audio/8062/13"
299
+ ]
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "execution_count": null,
304
+ "id": "e1c08b7e",
305
+ "metadata": {},
306
+ "outputs": [],
307
+ "source": [
308
+ "import torch\n",
309
+ "from torch.utils.data import DataLoader"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "execution_count": null,
315
+ "id": "6a296677",
316
+ "metadata": {},
317
+ "outputs": [],
318
+ "source": [
319
+ "torch_dataset = prepared_dataset.with_format(\"torch\")"
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "markdown",
324
+ "id": "29ab13bc",
325
+ "metadata": {},
326
+ "source": [
327
+ "**Note**: according to my tests, `num_workers` is not compatible with Datasets in streaming mode. Processes deadlock and there's no progress."
328
+ ]
329
+ },
330
+ {
331
+ "cell_type": "code",
332
+ "execution_count": null,
333
+ "id": "e2df5e13",
334
+ "metadata": {},
335
+ "outputs": [],
336
+ "source": [
337
+ "dataloader = DataLoader(torch_dataset, batch_size=batch_size * jax.device_count())"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "code",
342
+ "execution_count": null,
343
+ "id": "c15e3783",
344
+ "metadata": {},
345
+ "outputs": [],
346
+ "source": [
347
+ "batch = next(iter(dataloader))"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "code",
352
+ "execution_count": null,
353
+ "id": "71d027fe",
354
+ "metadata": {},
355
+ "outputs": [],
356
+ "source": [
357
+ "batch['image'].shape"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "markdown",
362
+ "id": "a354472b",
363
+ "metadata": {},
364
+ "source": [
365
+ "## VQGAN-JAX model"
366
+ ]
367
+ },
368
+ {
369
+ "cell_type": "code",
370
+ "execution_count": null,
371
+ "id": "2fcf01d7",
372
+ "metadata": {},
373
+ "outputs": [],
374
+ "source": [
375
+ "from vqgan_jax.modeling_flax_vqgan import VQModel"
376
+ ]
377
+ },
378
+ {
379
+ "cell_type": "markdown",
380
+ "id": "9daa636d",
381
+ "metadata": {},
382
+ "source": [
383
+ "We'll use a VQGAN trained with Taming Transformers and converted to a JAX model."
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "code",
388
+ "execution_count": null,
389
+ "id": "47a8b818",
390
+ "metadata": {
391
+ "scrolled": true
392
+ },
393
+ "outputs": [],
394
+ "source": [
395
+ "model = VQModel.from_pretrained(\"flax-community/vqgan_f16_16384\")"
396
+ ]
397
+ },
398
+ {
399
+ "cell_type": "markdown",
400
+ "id": "62ad01c3",
401
+ "metadata": {},
402
+ "source": [
403
+ "## Encoding"
404
+ ]
405
+ },
406
+ {
407
+ "cell_type": "markdown",
408
+ "id": "20357f74",
409
+ "metadata": {},
410
+ "source": [
411
+ "Encoding is really simple using `shard` to automatically distribute \"superbatches\" across devices, and `pmap`. This is all it takes to create our encoding function, that will be jitted on first use."
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "code",
416
+ "execution_count": null,
417
+ "id": "6686b004",
418
+ "metadata": {},
419
+ "outputs": [],
420
+ "source": [
421
+ "from flax.training.common_utils import shard\n",
422
+ "from functools import partial"
423
+ ]
424
+ },
425
+ {
426
+ "cell_type": "code",
427
+ "execution_count": null,
428
+ "id": "322a4619",
429
+ "metadata": {},
430
+ "outputs": [],
431
+ "source": [
432
+ "@partial(jax.pmap, axis_name=\"batch\")\n",
433
+ "def encode(batch):\n",
434
+ " # Not sure if we should `replicate` params, does not seem to have any effect\n",
435
+ " _, indices = model.encode(batch)\n",
436
+ " return indices"
437
+ ]
438
+ },
439
+ {
440
+ "cell_type": "markdown",
441
+ "id": "14375a41",
442
+ "metadata": {},
443
+ "source": [
444
+ "### Encoding loop"
445
+ ]
446
+ },
447
+ {
448
+ "cell_type": "code",
449
+ "execution_count": null,
450
+ "id": "ff6c10d4",
451
+ "metadata": {},
452
+ "outputs": [],
453
+ "source": [
454
+ "import os\n",
455
+ "import pandas as pd\n",
456
+ "\n",
457
+ "def encode_captioned_dataset(dataloader, output_dir, save_every=14):\n",
458
+ " output_dir.mkdir(parents=True, exist_ok=True)\n",
459
+ " \n",
460
+ " # Saving strategy:\n",
461
+ " # - Create a new file every so often to prevent excessive file seeking.\n",
462
+ " # - Save each batch after processing.\n",
463
+ " # - Keep the file open until we are done with it.\n",
464
+ " file = None \n",
465
+ " for n, batch in enumerate(tqdm(iter(dataloader))):\n",
466
+ " if (n % save_every == 0):\n",
467
+ " if file is not None:\n",
468
+ " file.close()\n",
469
+ " split_num = n // save_every\n",
470
+ " file = open(output_dir/f'split_{split_num:05x}.jsonl', 'w')\n",
471
+ "\n",
472
+ " images = batch[\"image\"].numpy()\n",
473
+ " images = shard(images.squeeze())\n",
474
+ " encoded = encode(images)\n",
475
+ " encoded = encoded.reshape(-1, encoded.shape[-1])\n",
476
+ "\n",
477
+ " keys = batch[\"key\"]\n",
478
+ " captions = batch[\"caption\"]\n",
479
+ "\n",
480
+ " encoded_as_string = list(map(lambda item: np.array2string(item, separator=',', max_line_width=50000, formatter={'int':lambda x: str(x)}), encoded))\n",
481
+ " batch_df = pd.DataFrame.from_dict({\"key\": keys, \"caption\": captions, \"encoding\": encoded_as_string})\n",
482
+ " batch_df.to_json(file, orient='records', lines=True)"
483
+ ]
484
+ },
485
+ {
486
+ "cell_type": "markdown",
487
+ "id": "09ff75a3",
488
+ "metadata": {},
489
+ "source": [
490
+ "Create a new file every 318 iterations. This should produce splits of ~500 MB each, when using a total batch size of 1024."
491
+ ]
492
+ },
493
+ {
494
+ "cell_type": "code",
495
+ "execution_count": null,
496
+ "id": "96222bb4",
497
+ "metadata": {},
498
+ "outputs": [],
499
+ "source": [
500
+ "save_every = 318"
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "code",
505
+ "execution_count": null,
506
+ "id": "7704863d",
507
+ "metadata": {},
508
+ "outputs": [
509
+ {
510
+ "name": "stderr",
511
+ "output_type": "stream",
512
+ "text": [
513
+ "28it [01:17, 1.60s/it]"
514
+ ]
515
+ }
516
+ ],
517
+ "source": [
518
+ "encode_captioned_dataset(dataloader, yfcc100m_output, save_every=save_every)"
519
+ ]
520
+ },
521
+ {
522
+ "cell_type": "markdown",
523
+ "id": "e266a70a",
524
+ "metadata": {},
525
+ "source": [
526
+ "This is ~10-15 slower than local encoding from an SSD. For performance considerations, see the discussion at https://discuss.huggingface.co/t/allow-streaming-of-large-datasets-with-image-audio/8062/13."
527
+ ]
528
+ },
529
+ {
530
+ "cell_type": "markdown",
531
+ "id": "8953dd84",
532
+ "metadata": {},
533
+ "source": [
534
+ "----"
535
+ ]
536
+ }
537
+ ],
538
+ "metadata": {
539
+ "interpreter": {
540
+ "hash": "db471c52d602b4f5f40ecaf278e88ccfef85c29d0a1a07185b0d51fc7acf4e26"
541
+ },
542
+ "kernelspec": {
543
+ "display_name": "Python 3 (ipykernel)",
544
+ "language": "python",
545
+ "name": "python3"
546
+ },
547
+ "language_info": {
548
+ "codemirror_mode": {
549
+ "name": "ipython",
550
+ "version": 3
551
+ },
552
+ "file_extension": ".py",
553
+ "mimetype": "text/x-python",
554
+ "name": "python",
555
+ "nbconvert_exporter": "python",
556
+ "pygments_lexer": "ipython3",
557
+ "version": "3.8.10"
558
+ }
559
+ },
560
+ "nbformat": 4,
561
+ "nbformat_minor": 5
562
+ }
dev/encoding/vqgan-jax-encoding-webdataset.ipynb ADDED
@@ -0,0 +1,461 @@
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
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "ba7b31e6",
14
+ "metadata": {},
15
+ "source": [
16
+ "This notebook shows how to pre-encode images to token sequences using JAX, VQGAN and a dataset in the [`webdataset` format](https://webdataset.github.io/webdataset/).\n",
17
+ "\n",
18
+ "This example uses a small subset of YFCC100M we created for testing, but it should be easy to adapt to any other image/caption dataset in the `webdataset` format."
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": null,
24
+ "id": "3b59489e",
25
+ "metadata": {},
26
+ "outputs": [],
27
+ "source": [
28
+ "import numpy as np\n",
29
+ "from tqdm import tqdm\n",
30
+ "\n",
31
+ "import torch\n",
32
+ "import torchvision.transforms as T\n",
33
+ "import torchvision.transforms.functional as TF\n",
34
+ "from torchvision.transforms import InterpolationMode\n",
35
+ "import math\n",
36
+ "\n",
37
+ "import webdataset as wds\n",
38
+ "\n",
39
+ "import jax\n",
40
+ "from jax import pmap"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "markdown",
45
+ "id": "c7c4c1e6",
46
+ "metadata": {},
47
+ "source": [
48
+ "## Dataset and Parameters"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "markdown",
53
+ "id": "9822850f",
54
+ "metadata": {},
55
+ "source": [
56
+ "The following is the list of shards we'll process. We hardcode the length of data so that we can see nice progress bars using `tqdm`."
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "execution_count": null,
62
+ "id": "1265dbfe",
63
+ "metadata": {},
64
+ "outputs": [],
65
+ "source": [
66
+ "shards = 'https://huggingface.co/datasets/dalle-mini/YFCC100M_OpenAI_subset/resolve/main/data/shard-{0000..0008}.tar'\n",
67
+ "length = 8320"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "markdown",
72
+ "id": "7e38fa14",
73
+ "metadata": {},
74
+ "source": [
75
+ "If we are extra cautious or our server is unreliable, we can enable retries by providing a custom `curl` retrieval command:"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": null,
81
+ "id": "4c8c5960",
82
+ "metadata": {},
83
+ "outputs": [],
84
+ "source": [
85
+ "# Enable curl retries to try to work around temporary network / server errors.\n",
86
+ "# This shouldn't be necessary when using reliable servers.\n",
87
+ "# shards = f'pipe:curl -s --retry 5 --retry-delay 5 -L {shards} || true'"
88
+ ]
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "execution_count": null,
93
+ "id": "13c6631b",
94
+ "metadata": {},
95
+ "outputs": [],
96
+ "source": [
97
+ "from pathlib import Path\n",
98
+ "\n",
99
+ "# Output directory for encoded files\n",
100
+ "encoded_output = Path.home()/'data'/'wds'/'encoded'\n",
101
+ "\n",
102
+ "batch_size = 128 # Per device\n",
103
+ "num_workers = 8 # For parallel processing"
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "execution_count": null,
109
+ "id": "3435fb85",
110
+ "metadata": {},
111
+ "outputs": [],
112
+ "source": [
113
+ "bs = batch_size * jax.device_count() # You can use a smaller size while testing\n",
114
+ "batches = math.ceil(length / bs)"
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "markdown",
119
+ "id": "88598e4b",
120
+ "metadata": {},
121
+ "source": [
122
+ "Image processing"
123
+ ]
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "execution_count": null,
128
+ "id": "669b35df",
129
+ "metadata": {},
130
+ "outputs": [],
131
+ "source": [
132
+ "def center_crop(image, max_size=256):\n",
133
+ " # Note: we allow upscaling too. We should exclude small images. \n",
134
+ " image = TF.resize(image, max_size, interpolation=InterpolationMode.LANCZOS)\n",
135
+ " image = TF.center_crop(image, output_size=2 * [max_size])\n",
136
+ " return image\n",
137
+ "\n",
138
+ "preprocess_image = T.Compose([\n",
139
+ " center_crop,\n",
140
+ " T.ToTensor(),\n",
141
+ " lambda t: t.permute(1, 2, 0) # Reorder, we need dimensions last\n",
142
+ "])"
143
+ ]
144
+ },
145
+ {
146
+ "cell_type": "markdown",
147
+ "id": "a185e90c",
148
+ "metadata": {},
149
+ "source": [
150
+ "Caption preparation.\n",
151
+ "\n",
152
+ "Note that we receive the contents of the `json` structure, which will be replaced by the string we return.\n",
153
+ "If we want to keep other fields inside `json`, we can add `caption` as a new field."
154
+ ]
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "execution_count": null,
159
+ "id": "423ee10e",
160
+ "metadata": {},
161
+ "outputs": [],
162
+ "source": [
163
+ "def create_caption(item):\n",
164
+ " title = item['title_clean'].strip()\n",
165
+ " description = item['description_clean'].strip()\n",
166
+ " if len(title) > 0 and title[-1] not in '.!?': title += '.'\n",
167
+ " return f'{title} {description}'"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "markdown",
172
+ "id": "8d3a95db",
173
+ "metadata": {},
174
+ "source": [
175
+ "When an error occurs (a download is disconnected, an image cannot be decoded, etc) the process stops with an exception. We can use one of the exception handlers provided by the `webdataset` library, such as `wds.warn_and_continue` or `wds.ignore_and_continue` to ignore the offending entry and keep iterating.\n",
176
+ "\n",
177
+ "**IMPORTANT WARNING:** Do not use error handlers to ignore exceptions until you have tested that your processing pipeline works fine. Otherwise, the process will continue trying to find a valid entry, and it will consume your whole dataset without doing any work.\n",
178
+ "\n",
179
+ "We can also create our custom exception handler as demonstrated here:"
180
+ ]
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "execution_count": null,
185
+ "id": "369d9719",
186
+ "metadata": {},
187
+ "outputs": [],
188
+ "source": [
189
+ "# UNUSED - Log exceptions to a file\n",
190
+ "def ignore_and_log(exn):\n",
191
+ " with open('errors.txt', 'a') as f:\n",
192
+ " f.write(f'{repr(exn)}\\n')\n",
193
+ " return True"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": null,
199
+ "id": "27de1414",
200
+ "metadata": {},
201
+ "outputs": [],
202
+ "source": [
203
+ "# Or simply use `wds.ignore_and_continue`\n",
204
+ "exception_handler = wds.warn_and_continue"
205
+ ]
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "execution_count": null,
210
+ "id": "5149b6d5",
211
+ "metadata": {},
212
+ "outputs": [],
213
+ "source": [
214
+ "dataset = wds.WebDataset(shards,\n",
215
+ " length=batches, # Hint so `len` is implemented\n",
216
+ " shardshuffle=False, # Keep same order for encoded files for easier bookkeeping. Set to `True` for training.\n",
217
+ " handler=exception_handler, # Ignore read errors instead of failing.\n",
218
+ ")\n",
219
+ "\n",
220
+ "dataset = (dataset \n",
221
+ " .decode('pil') # decode image with PIL\n",
222
+ "# .map_dict(jpg=preprocess_image, json=create_caption, handler=exception_handler) # Process fields with functions defined above\n",
223
+ " .map_dict(jpg=preprocess_image, json=create_caption) # Process fields with functions defined above\n",
224
+ " .to_tuple('__key__', 'jpg', 'json') # filter to keep only key (for reference), image, caption.\n",
225
+ " .batched(bs)) # better to batch in the dataset (but we could also do it in the dataloader) - this arg does not affect speed and we could remove it"
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "execution_count": null,
231
+ "id": "8cac98cb",
232
+ "metadata": {
233
+ "scrolled": true
234
+ },
235
+ "outputs": [],
236
+ "source": [
237
+ "%%time\n",
238
+ "keys, images, captions = next(iter(dataset))"
239
+ ]
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "execution_count": null,
244
+ "id": "cd268fbf",
245
+ "metadata": {},
246
+ "outputs": [],
247
+ "source": [
248
+ "images.shape"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": null,
254
+ "id": "c24693c0",
255
+ "metadata": {},
256
+ "outputs": [],
257
+ "source": [
258
+ "T.ToPILImage()(images[0].permute(2, 0, 1))"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "markdown",
263
+ "id": "44d50a51",
264
+ "metadata": {},
265
+ "source": [
266
+ "### Torch DataLoader"
267
+ ]
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "execution_count": null,
272
+ "id": "e2df5e13",
273
+ "metadata": {},
274
+ "outputs": [],
275
+ "source": [
276
+ "dl = torch.utils.data.DataLoader(dataset, batch_size=None, num_workers=num_workers)"
277
+ ]
278
+ },
279
+ {
280
+ "cell_type": "markdown",
281
+ "id": "a354472b",
282
+ "metadata": {},
283
+ "source": [
284
+ "## VQGAN-JAX model"
285
+ ]
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "execution_count": null,
290
+ "id": "2fcf01d7",
291
+ "metadata": {},
292
+ "outputs": [],
293
+ "source": [
294
+ "from vqgan_jax.modeling_flax_vqgan import VQModel"
295
+ ]
296
+ },
297
+ {
298
+ "cell_type": "markdown",
299
+ "id": "9daa636d",
300
+ "metadata": {},
301
+ "source": [
302
+ "We'll use a VQGAN trained with Taming Transformers and converted to a JAX model."
303
+ ]
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "execution_count": null,
308
+ "id": "47a8b818",
309
+ "metadata": {
310
+ "scrolled": true
311
+ },
312
+ "outputs": [],
313
+ "source": [
314
+ "model = VQModel.from_pretrained(\"flax-community/vqgan_f16_16384\")"
315
+ ]
316
+ },
317
+ {
318
+ "cell_type": "markdown",
319
+ "id": "62ad01c3",
320
+ "metadata": {},
321
+ "source": [
322
+ "## Encoding"
323
+ ]
324
+ },
325
+ {
326
+ "cell_type": "markdown",
327
+ "id": "20357f74",
328
+ "metadata": {},
329
+ "source": [
330
+ "Encoding is really simple using `shard` to automatically distribute \"superbatches\" across devices, and `pmap`. This is all it takes to create our encoding function, that will be jitted on first use."
331
+ ]
332
+ },
333
+ {
334
+ "cell_type": "code",
335
+ "execution_count": null,
336
+ "id": "6686b004",
337
+ "metadata": {},
338
+ "outputs": [],
339
+ "source": [
340
+ "from flax.training.common_utils import shard\n",
341
+ "from functools import partial"
342
+ ]
343
+ },
344
+ {
345
+ "cell_type": "code",
346
+ "execution_count": null,
347
+ "id": "322a4619",
348
+ "metadata": {},
349
+ "outputs": [],
350
+ "source": [
351
+ "@partial(jax.pmap, axis_name=\"batch\")\n",
352
+ "def encode(batch):\n",
353
+ " # Not sure if we should `replicate` params, does not seem to have any effect\n",
354
+ " _, indices = model.encode(batch)\n",
355
+ " return indices"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "markdown",
360
+ "id": "14375a41",
361
+ "metadata": {},
362
+ "source": [
363
+ "### Encoding loop"
364
+ ]
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "execution_count": null,
369
+ "id": "ff6c10d4",
370
+ "metadata": {},
371
+ "outputs": [],
372
+ "source": [
373
+ "import os\n",
374
+ "import pandas as pd\n",
375
+ "\n",
376
+ "def encode_captioned_dataset(dataloader, output_dir, save_every=14):\n",
377
+ " output_dir.mkdir(parents=True, exist_ok=True)\n",
378
+ "\n",
379
+ " # Saving strategy:\n",
380
+ " # - Create a new file every so often to prevent excessive file seeking.\n",
381
+ " # - Save each batch after processing.\n",
382
+ " # - Keep the file open until we are done with it.\n",
383
+ " file = None \n",
384
+ " for n, (keys, images, captions) in enumerate(tqdm(dataloader)):\n",
385
+ " if (n % save_every == 0):\n",
386
+ " if file is not None:\n",
387
+ " file.close()\n",
388
+ " split_num = n // save_every\n",
389
+ " file = open(output_dir/f'split_{split_num:05x}.jsonl', 'w')\n",
390
+ "\n",
391
+ " images = shard(images.numpy().squeeze())\n",
392
+ " encoded = encode(images)\n",
393
+ " encoded = encoded.reshape(-1, encoded.shape[-1])\n",
394
+ "\n",
395
+ " encoded_as_string = list(map(lambda item: np.array2string(item, separator=',', max_line_width=50000, formatter={'int':lambda x: str(x)}), encoded))\n",
396
+ " batch_df = pd.DataFrame.from_dict({\"key\": keys, \"caption\": captions, \"encoding\": encoded_as_string})\n",
397
+ " batch_df.to_json(file, orient='records', lines=True)"
398
+ ]
399
+ },
400
+ {
401
+ "cell_type": "markdown",
402
+ "id": "09ff75a3",
403
+ "metadata": {},
404
+ "source": [
405
+ "Create a new file every 318 iterations. This should produce splits of ~500 MB each, when using a total batch size of 1024."
406
+ ]
407
+ },
408
+ {
409
+ "cell_type": "code",
410
+ "execution_count": null,
411
+ "id": "96222bb4",
412
+ "metadata": {},
413
+ "outputs": [],
414
+ "source": [
415
+ "save_every = 318"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "code",
420
+ "execution_count": null,
421
+ "id": "7704863d",
422
+ "metadata": {},
423
+ "outputs": [],
424
+ "source": [
425
+ "encode_captioned_dataset(dl, encoded_output, save_every=save_every)"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "markdown",
430
+ "id": "8953dd84",
431
+ "metadata": {},
432
+ "source": [
433
+ "----"
434
+ ]
435
+ }
436
+ ],
437
+ "metadata": {
438
+ "interpreter": {
439
+ "hash": "db471c52d602b4f5f40ecaf278e88ccfef85c29d0a1a07185b0d51fc7acf4e26"
440
+ },
441
+ "kernelspec": {
442
+ "display_name": "Python 3 (ipykernel)",
443
+ "language": "python",
444
+ "name": "python3"
445
+ },
446
+ "language_info": {
447
+ "codemirror_mode": {
448
+ "name": "ipython",
449
+ "version": 3
450
+ },
451
+ "file_extension": ".py",
452
+ "mimetype": "text/x-python",
453
+ "name": "python",
454
+ "nbconvert_exporter": "python",
455
+ "pygments_lexer": "ipython3",
456
+ "version": "3.8.10"
457
+ }
458
+ },
459
+ "nbformat": 4,
460
+ "nbformat_minor": 5
461
+ }