Pedro Cuenca commited on
Commit
95fa0dc
1 Parent(s): ac3e482

Usage examples: link to colab, pmap encoding script.

Browse files
Files changed (1) hide show
  1. README.md +130 -2
README.md CHANGED
@@ -31,8 +31,136 @@ Finetuning was performed in PyTorch using [taming-transformers](https://github.c
31
 
32
  The checkpoint can be loaded using [Suraj Patil's implementation](https://github.com/patil-suraj/vqgan-jax) of `VQModel`.
33
 
34
- * Encoding. `coming soon`.
35
- * Decoding. `coming soon`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  ### Other
38
 
 
31
 
32
  The checkpoint can be loaded using [Suraj Patil's implementation](https://github.com/patil-suraj/vqgan-jax) of `VQModel`.
33
 
34
+ * Example notebook, heavily based in work by Suraj:
35
+
36
+ [![Colab](https://miro.medium.com/max/48/1*7oukapIBInsovpHkQB3QZg.jpeg)](https://colab.research.google.com/drive/1kdIsfz-vLHSoI_UPxpVrxQPxY2s593uH?usp=sharing/)
37
+
38
+ * Batch encoding using JAX `pmap`, complete example including data loading with PyTorch:
39
+
40
+ ```python
41
+ # VQGAN-JAX - pmap encoding HowTo
42
+
43
+ import numpy as np
44
+
45
+ # For data loading
46
+ import torch
47
+ import torchvision.transforms.functional as TF
48
+ from torch.utils.data import Dataset, DataLoader
49
+ from torchvision.datasets.folder import default_loader
50
+ from torchvision.transforms import InterpolationMode
51
+
52
+ # For data saving
53
+ from pathlib import Path
54
+ import pandas as pd
55
+ from tqdm import tqdm
56
+
57
+ import jax
58
+ from jax import pmap
59
+
60
+ from vqgan_jax.modeling_flax_vqgan import VQModel
61
+
62
+ ## Params and arguments
63
+
64
+ # List of paths containing images to encode
65
+ image_list = '/sddata/dalle-mini/CC12M/10k.tsv'
66
+ output_tsv = 'output.tsv' # Encoded results
67
+ batch_size = 64
68
+ num_workers = 4 # TPU v3-8s have 96 cores, so feel free to increase this number when necessary
69
+
70
+ # Load model
71
+ model = VQModel.from_pretrained("flax-community/vqgan_f16_16384")
72
+
73
+ ## Data Loading.
74
+
75
+ # Simple torch Dataset to load images from paths.
76
+ # You can use your own pipeline instead.
77
+ class ImageDataset(Dataset):
78
+ def __init__(self, image_list_path: str, image_size: int, max_items=None):
79
+ """
80
+ :param image_list_path: Path to a file containing a list of all images. We assume absolute paths for now.
81
+ :param image_size: Image size. Source images will be resized and center-cropped.
82
+ :max_items: Limit dataset size for debugging
83
+ """
84
+ self.image_list = pd.read_csv(image_list_path, sep='\t', header=None)
85
+ if max_items is not None: self.image_list = self.image_list[:max_items]
86
+ self.image_size = image_size
87
+
88
+ def __len__(self):
89
+ return len(self.image_list)
90
+
91
+ def _get_raw_image(self, i):
92
+ image_path = Path(self.image_list.iloc[i][0])
93
+ return default_loader(image_path)
94
+
95
+ def resize_image(self, image):
96
+ s = min(image.size)
97
+ r = self.image_size / s
98
+ s = (round(r * image.size[1]), round(r * image.size[0]))
99
+ image = TF.resize(image, s, interpolation=InterpolationMode.LANCZOS)
100
+ image = TF.center_crop(image, output_size = 2 * [self.image_size])
101
+ image = np.expand_dims(np.array(image), axis=0)
102
+ return image
103
+
104
+ def __getitem__(self, i):
105
+ image = self._get_raw_image(i)
106
+ return self.resize_image(image)
107
+
108
+ ## Encoding
109
+
110
+ # Encoding function to be parallelized with `pmap`
111
+ # Note: images have to be square
112
+ def encode(model, batch):
113
+ _, indices = model.encode(batch)
114
+ return indices
115
+
116
+ # Alternative: create a batch with num_tpus*batch_size and use `shard` to distribute.
117
+ def superbatch_generator(dataloader, num_tpus):
118
+ iter_loader = iter(dataloader)
119
+ for batch in iter_loader:
120
+ superbatch = [batch.squeeze(1)]
121
+ try:
122
+ for _ in range(num_tpus-1):
123
+ batch = next(iter_loader)
124
+ if batch is None:
125
+ break
126
+ # Skip incomplete last batch
127
+ if batch.shape[0] == dataloader.batch_size:
128
+ superbatch.append(batch.squeeze(1))
129
+ except StopIteration:
130
+ pass
131
+ superbatch = torch.stack(superbatch, axis=0)
132
+ yield superbatch
133
+
134
+ def encode_dataset(dataset, batch_size=32):
135
+ dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)
136
+ superbatches = superbatch_generator(dataloader, num_tpus=jax.device_count())
137
+
138
+ num_tpus = jax.device_count()
139
+ dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)
140
+ superbatches = superbatch_generator(dataloader, num_tpus=num_tpus)
141
+
142
+ p_encoder = pmap(lambda batch: encode(model, batch))
143
+
144
+ # Save each superbatch to avoid reallocation of buffers as we process them.
145
+ # Keep the file open to prevent excessive file seeks.
146
+ with open(output_tsv, "w") as file:
147
+ iterations = len(dataset) // (batch_size * num_tpus)
148
+ for n in tqdm(range(iterations)):
149
+ superbatch = next(superbatches)
150
+ encoded = p_encoder(superbatch.numpy())
151
+ encoded = encoded.reshape(-1, encoded.shape[-1])
152
+
153
+ # Extract paths from the dataset, save paths and encodings (as string)
154
+ start_index = n * batch_size * num_tpus
155
+ end_index = (n+1) * batch_size * num_tpus
156
+ paths = dataset.image_list[start_index:end_index][0].values
157
+ encoded_as_string = list(map(lambda item: np.array2string(item, separator=',', max_line_width=50000, formatter={'int':lambda x: str(x)}), encoded))
158
+ batch_df = pd.DataFrame.from_dict({"image_file": paths, "encoding": encoded_as_string})
159
+ batch_df.to_csv(file, sep='\t', header=(n==0), index=None)
160
+
161
+ dataset = ImageDataset(image_list, image_size=256)
162
+ encoded_dataset = encode_dataset(dataset, batch_size=batch_size)
163
+ ```
164
 
165
  ### Other
166