boris commited on
Commit
bc441b8
1 Parent(s): 85eb5d3

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +154 -0
README.md ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## VQGAN-f16-16384
2
+
3
+ ### Model Description
4
+
5
+ This is a Flax/JAX implementation of VQGAN, which learns a codebook of context-rich visual parts by leveraging both the use of convolutional methods and transformers. It was introduced in [Taming Transformers for High-Resolution Image Synthesis](https://compvis.github.io/taming-transformers/) ([CVPR paper](https://openaccess.thecvf.com/content/CVPR2021/html/Esser_Taming_Transformers_for_High-Resolution_Image_Synthesis_CVPR_2021_paper.html)).
6
+
7
+ The model allows the encoding of images as a fixed-length sequence of tokens taken from the codebook.
8
+
9
+ This version of the model uses a reduction factor `f=16` and a vocabulary of `16,384` tokens.
10
+
11
+ As an example of how the reduction factor works, images of size `256x256` are encoded to sequences of `256` tokens: `256/16 * 256/16`. Images of `512x512` would result in sequences of `1024` tokens.
12
+
13
+ This model was ported to JAX using [a checkpoint trained on ImageNet](https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/).
14
+
15
+ ### How to Use
16
+
17
+ The checkpoint can be loaded using [Suraj Patil's implementation](https://github.com/patil-suraj/vqgan-jax) of `VQModel`.
18
+
19
+ * Example notebook, heavily based in work by [Suraj](https://huggingface.co/valhalla): [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/borisdayma/dalle-mini/blob/main/dev/vqgan/JAX_VQGAN_f16_16384_Reconstruction.ipynb)
20
+
21
+ * Batch encoding using JAX `pmap`, complete example including data loading with PyTorch:
22
+
23
+ ```python
24
+ # VQGAN-JAX - pmap encoding HowTo
25
+
26
+ import numpy as np
27
+
28
+ # For data loading
29
+ import torch
30
+ import torchvision.transforms.functional as TF
31
+ from torch.utils.data import Dataset, DataLoader
32
+ from torchvision.datasets.folder import default_loader
33
+ from torchvision.transforms import InterpolationMode
34
+
35
+ # For data saving
36
+ from pathlib import Path
37
+ import pandas as pd
38
+ from tqdm import tqdm
39
+
40
+ import jax
41
+ from jax import pmap
42
+
43
+ from vqgan_jax.modeling_flax_vqgan import VQModel
44
+
45
+ ## Params and arguments
46
+
47
+ # List of paths containing images to encode
48
+ image_list = '/sddata/dalle-mini/CC12M/10k.tsv'
49
+ output_tsv = 'output.tsv' # Encoded results
50
+ batch_size = 64
51
+ num_workers = 4 # TPU v3-8s have 96 cores, so feel free to increase this number when necessary
52
+
53
+ # Load model
54
+ model = VQModel.from_pretrained("flax-community/vqgan_f16_16384")
55
+
56
+ ## Data Loading.
57
+
58
+ # Simple torch Dataset to load images from paths.
59
+ # You can use your own pipeline instead.
60
+ class ImageDataset(Dataset):
61
+ def __init__(self, image_list_path: str, image_size: int, max_items=None):
62
+ """
63
+ :param image_list_path: Path to a file containing a list of all images. We assume absolute paths for now.
64
+ :param image_size: Image size. Source images will be resized and center-cropped.
65
+ :max_items: Limit dataset size for debugging
66
+ """
67
+ self.image_list = pd.read_csv(image_list_path, sep='\t', header=None)
68
+ if max_items is not None: self.image_list = self.image_list[:max_items]
69
+ self.image_size = image_size
70
+
71
+ def __len__(self):
72
+ return len(self.image_list)
73
+
74
+ def _get_raw_image(self, i):
75
+ image_path = Path(self.image_list.iloc[i][0])
76
+ return default_loader(image_path)
77
+
78
+ def resize_image(self, image):
79
+ s = min(image.size)
80
+ r = self.image_size / s
81
+ s = (round(r * image.size[1]), round(r * image.size[0]))
82
+ image = TF.resize(image, s, interpolation=InterpolationMode.LANCZOS)
83
+ image = TF.center_crop(image, output_size = 2 * [self.image_size])
84
+ image = np.expand_dims(np.array(image), axis=0)
85
+ return image
86
+
87
+ def __getitem__(self, i):
88
+ image = self._get_raw_image(i)
89
+ return self.resize_image(image)
90
+
91
+ ## Encoding
92
+
93
+ # Encoding function to be parallelized with `pmap`
94
+ # Note: images have to be square
95
+ def encode(model, batch):
96
+ _, indices = model.encode(batch)
97
+ return indices
98
+
99
+ # Alternative: create a batch with num_tpus*batch_size and use `shard` to distribute.
100
+ def superbatch_generator(dataloader, num_tpus):
101
+ iter_loader = iter(dataloader)
102
+ for batch in iter_loader:
103
+ superbatch = [batch.squeeze(1)]
104
+ try:
105
+ for _ in range(num_tpus-1):
106
+ batch = next(iter_loader)
107
+ if batch is None:
108
+ break
109
+ # Skip incomplete last batch
110
+ if batch.shape[0] == dataloader.batch_size:
111
+ superbatch.append(batch.squeeze(1))
112
+ except StopIteration:
113
+ pass
114
+ superbatch = torch.stack(superbatch, axis=0)
115
+ yield superbatch
116
+
117
+ def encode_dataset(dataset, batch_size=32):
118
+ dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)
119
+ superbatches = superbatch_generator(dataloader, num_tpus=jax.device_count())
120
+
121
+ num_tpus = jax.device_count()
122
+ dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)
123
+ superbatches = superbatch_generator(dataloader, num_tpus=num_tpus)
124
+
125
+ p_encoder = pmap(lambda batch: encode(model, batch))
126
+
127
+ # Save each superbatch to avoid reallocation of buffers as we process them.
128
+ # Keep the file open to prevent excessive file seeks.
129
+ with open(output_tsv, "w") as file:
130
+ iterations = len(dataset) // (batch_size * num_tpus)
131
+ for n in tqdm(range(iterations)):
132
+ superbatch = next(superbatches)
133
+ encoded = p_encoder(superbatch.numpy())
134
+ encoded = encoded.reshape(-1, encoded.shape[-1])
135
+
136
+ # Extract paths from the dataset, save paths and encodings (as string)
137
+ start_index = n * batch_size * num_tpus
138
+ end_index = (n+1) * batch_size * num_tpus
139
+ paths = dataset.image_list[start_index:end_index][0].values
140
+ encoded_as_string = list(map(lambda item: np.array2string(item, separator=',', max_line_width=50000, formatter={'int':lambda x: str(x)}), encoded))
141
+ batch_df = pd.DataFrame.from_dict({"image_file": paths, "encoding": encoded_as_string})
142
+ batch_df.to_csv(file, sep='\t', header=(n==0), index=None)
143
+
144
+ dataset = ImageDataset(image_list, image_size=256)
145
+ encoded_dataset = encode_dataset(dataset, batch_size=batch_size)
146
+ ```
147
+
148
+ ### Related Models in the Hub
149
+
150
+ * [DALL路E mini](https://huggingface.co/flax-community/dalle-mini), a Flax/JAX simplified implementation of OpenAI's DALL路E.
151
+
152
+ ### Other
153
+
154
+ This model can be used as part of the implementation of [DALL路E mini](https://github.com/borisdayma/dalle-mini). Our [report](https://wandb.ai/dalle-mini/dalle-mini/reports/DALL-E-mini--Vmlldzo4NjIxODA) contains more details on how to leverage it in an image encoding / generation pipeline.