<jupyter_start><jupyter_text>VQGAN JAX Encoding for 🤗 Datasets in streaming mode This notebook shows how to pre-encode images to token sequences using JAX, VQGAN and 🤗 Datasets in streaming mode.This example uses our YFCC100M dataset, but it should be easy to adapt to any other image/caption dataset in the huggingface hub.<jupyter_code>import io

import requests
from PIL import Image
import numpy as np
from tqdm import tqdm

import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from torchvision.transforms import InterpolationMode
import os

import jax
from jax import pmap<jupyter_output><empty_output><jupyter_text>Dataset and Parameters<jupyter_code>import datasets
from datasets import Dataset, load_dataset<jupyter_output><empty_output><jupyter_text>We'll use the `validation` set for testing. Adjust accordingly.<jupyter_code>dataset = load_dataset('dalle-mini/YFCC100M_OpenAI_subset', use_auth_token=True, streaming=True, split='validation')
from pathlib import Path

yfcc100m = Path.home()/'data'/'YFCC100M_OpenAI_subset'
yfcc100m_output = yfcc100m/'encoded'      # Output directory for encoded files
batch_size = 128     # Per device
num_workers = 16     # Unused in streaming mode<jupyter_output><empty_output><jupyter_text>Data preparation * 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.* Captions: we extract a single `caption` column from the source data, by concatenating the cleaned title and description.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. This helper function is used to decode images from the bytes retrieved in `streaming` mode.<jupyter_code>from PIL import Image
import io

def get_image(byte_stream):
    image = Image.open(io.BytesIO(byte_stream))
    return image.convert('RGB')<jupyter_output><empty_output><jupyter_text>Image processing<jupyter_code>def center_crop(image, max_size=256):
    # Note: we allow upscaling too. We should exclude small images.    
    image = TF.resize(image, max_size, interpolation=InterpolationMode.LANCZOS)
    image = TF.center_crop(image, output_size=2 * [max_size])
    return image

preprocess_image = T.Compose([
    get_image,
    center_crop,
    T.ToTensor(),
    lambda t: t.permute(1, 2, 0)   # Reorder, we need dimensions last
])<jupyter_output><empty_output><jupyter_text>Caption preparation<jupyter_code>import string

def create_caption(title, description):
    title = title.strip()
    description = description.strip()
    if len(title) > 0 and title[-1] not in '.!?': title += '.'
    return f'{title} {description}'<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>def prepare_item(item):
    return {
        'key': item['key'],
        'caption': create_caption(item['title_clean'], item['description_clean']),
        'image': preprocess_image(item['img'])
    }<jupyter_output><empty_output><jupyter_text>Unlike when using non-streaming datasets, the following operation completes immediately in streaming mode. In streaming mode, `num_proc` is not supported.<jupyter_code>prepared_dataset = dataset.map(prepare_item, batched=False)
%%time
item = next(iter(prepared_dataset))
assert(list(item.keys()) == ['key', 'caption', 'image'])
item['image'].shape
T.ToPILImage()(item['image'].permute(2, 0, 1))<jupyter_output><empty_output><jupyter_text>Torch DataLoader We'll create a PyTorch DataLoader for convenience. This allows us to easily take batches of our desired size.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.htmlmulti-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<jupyter_code>import torch
from torch.utils.data import DataLoader
torch_dataset = prepared_dataset.with_format("torch")<jupyter_output><empty_output><jupyter_text>**Note**: according to my tests, `num_workers` is not compatible with Datasets in streaming mode. Processes deadlock and there's no progress.<jupyter_code>dataloader = DataLoader(torch_dataset, batch_size=batch_size * jax.device_count())
batch = next(iter(dataloader))
batch['image'].shape<jupyter_output><empty_output><jupyter_text>VQGAN-JAX model<jupyter_code>from vqgan_jax.modeling_flax_vqgan import VQModel<jupyter_output><empty_output><jupyter_text>We'll use a VQGAN trained with Taming Transformers and converted to a JAX model.<jupyter_code>model = VQModel.from_pretrained("flax-community/vqgan_f16_16384")<jupyter_output><empty_output><jupyter_text>Encoding 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.<jupyter_code>from flax.training.common_utils import shard
from functools import partial
@partial(jax.pmap, axis_name="batch")
def encode(batch):
    # Not sure if we should `replicate` params, does not seem to have any effect
    _, indices = model.encode(batch)
    return indices<jupyter_output><empty_output><jupyter_text>Encoding loop<jupyter_code>import os
import pandas as pd

def encode_captioned_dataset(dataloader, output_dir, save_every=14):
    output_dir.mkdir(parents=True, exist_ok=True)
        
    # Saving strategy:
    # - Create a new file every so often to prevent excessive file seeking.
    # - Save each batch after processing.
    # - Keep the file open until we are done with it.
    file = None        
    for n, batch in enumerate(tqdm(iter(dataloader))):
        if (n % save_every == 0):
            if file is not None:
                file.close()
            split_num = n // save_every
            file = open(output_dir/f'split_{split_num:05x}.jsonl', 'w')

        images = batch["image"].numpy()
        images = shard(images.squeeze())
        encoded = encode(images)
        encoded = encoded.reshape(-1, encoded.shape[-1])

        keys = batch["key"]
        captions = batch["caption"]

        encoded_as_string = list(map(lambda item: np.array2string(item, separator=',', max_line_width=50000, formatter={'int':lambda x: str(x)}), encoded))
        batch_df = pd.DataFrame.from_dict({"key": keys, "caption": captions, "encoding": encoded_as_string})
        batch_df.to_json(file, orient='records', lines=True)<jupyter_output><empty_output><jupyter_text>Create a new file every 318 iterations. This should produce splits of ~500 MB each, when using a total batch size of 1024.<jupyter_code>save_every = 318
encode_captioned_dataset(dataloader, yfcc100m_output, save_every=save_every)<jupyter_output>28it [01:17,  1.60s/it]
{'fraction_non_alphanumeric': 0.09489355781271741, 'fraction_numerical': 0.011966049812160847, 'mean_word_length': 5.245004344048653, 'pattern_counts': {'":': 3, '<': 60, '<?xml version=': 0, '>': 61, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '354351', 'license': 'Apache-2.0', 'n_tokens_mistral': 2274, 'n_tokens_neox': 2181, 'n_words': 662, 'path': 'dev/encoding/vqgan-jax-encoding-streaming.ipynb', 'repo_name': 'ProjectsStartUp/dalle-mini', 'size': '7187'}