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|
2 |
+
import torch.nn as nn
|
3 |
+
import numpy as np
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
from einops import rearrange, repeat
|
9 |
+
|
10 |
+
import torchvision.transforms.functional as ttf
|
11 |
+
from timm.models.convmixer import ConvMixer
|
12 |
+
import functorch
|
13 |
+
|
14 |
+
def img_to_patches(im, patch_h, patch_w):
|
15 |
+
"B, C, H, W -> B, C, D, h_patch, w_patch"
|
16 |
+
bs, c, h, w = im.shape
|
17 |
+
im = im.unfold(-1, patch_h, patch_w).unfold(2, patch_h, patch_w)
|
18 |
+
im = im.permute(0, 1, 2, 3, 5, 4)
|
19 |
+
im = im.contiguous().view(bs, c, -1, patch_h, patch_w)
|
20 |
+
return im
|
21 |
+
|
22 |
+
def patches_to_img(patches, num_patch_h, num_patch_w):
|
23 |
+
"B, C, D, h_patch, w_patch -> B, C, H, W"
|
24 |
+
bs, c, d, h, w = patches.shape
|
25 |
+
patches = patches.view(bs, c, num_patch_h, num_patch_w, h, w)
|
26 |
+
# fold patches
|
27 |
+
patches = torch.cat([patches[..., k, :, :] for k in range(num_patch_w)], dim=-1)
|
28 |
+
x = torch.cat([patches[..., k, :, :] for k in range(num_patch_h)], dim=-2)
|
29 |
+
return x
|
30 |
+
|
31 |
+
def vmapped_rotate(x, angle, in_dims=1):
|
32 |
+
"B, C, D, H, W -> B, C, D, H, W"
|
33 |
+
rotate_ = functorch.vmap(ttf.rotate, in_dims=in_dims, out_dims=in_dims)
|
34 |
+
return rotate_(x, angle=angle)
|
35 |
+
|
36 |
+
class CollageOperator2d(nn.Module):
|
37 |
+
|
38 |
+
def __init__(self, res, rh, rw, dh=None, dw=None, use_augmentations=False):
|
39 |
+
"""Collage Operator for two-dimensional data. Given a fractal code, it outputs the corresponding fixed-point.
|
40 |
+
|
41 |
+
Args:
|
42 |
+
res (int): Spatial resolutions of input (and output) data.
|
43 |
+
rh (int): Height of range (target) square patches.
|
44 |
+
rw (int): Width of range (target) square patches.
|
45 |
+
dh (int, optional): Height of range domain (source) patches. Defaults to `res`.
|
46 |
+
dw (int, optional): Width of range domain (source) patches. Defaults to `res`.
|
47 |
+
use_augmentations (bool, optional): Use augmentations of domain square patches at each decoding iteration. Defaults to `False`.
|
48 |
+
"""
|
49 |
+
super().__init__()
|
50 |
+
self.dh, self.dw = dh, dw
|
51 |
+
if self.dh is None: self.dh = res
|
52 |
+
if self.dw is None: self.dw = res
|
53 |
+
|
54 |
+
# 5 refers to the 5 copies of domain patches generated with the current choice of augmentations:
|
55 |
+
# 3 rotations (90, 180, 270), horizontal flips and vertical flips.
|
56 |
+
self.n_aug_transforms = 9 if use_augmentations else 0
|
57 |
+
|
58 |
+
# precompute useful quantities related to the partitioning scheme into patches, given
|
59 |
+
# the desired `dh`, `dw`, `rh`, `rw`.
|
60 |
+
partition_info = self.collage_partition_info(res, self.dh, self.dw, rh, rw)
|
61 |
+
self.n_dh, self.n_dw, self.n_rh, self.n_rw, self.h_factors, self.w_factors, self.n_domains, self.n_ranges = partition_info
|
62 |
+
|
63 |
+
# At each step of the collage, all (source) domain patches are pooled down to the size of range (target) patches.
|
64 |
+
# Notices how the pooling factors do not change if one decodes at higher resolutions, since both domain and range
|
65 |
+
# patch sizes are multiplied by the same integer.
|
66 |
+
self.pool = nn.AvgPool3d(kernel_size=(1, self.h_factors, self.w_factors), stride=(1, self.h_factors, self.w_factors))
|
67 |
+
|
68 |
+
def collage_operator(self, z, collage_weight, collage_bias):
|
69 |
+
"""Collage Operator (decoding). Performs the steps described in Def. 3.1, Figure 2."""
|
70 |
+
|
71 |
+
# Given the current iterate `z`, we split it into domain patches according to the partitioning scheme.
|
72 |
+
domains = img_to_patches(z)
|
73 |
+
|
74 |
+
# Pool domains (pre augmentation) to range patch sizes.
|
75 |
+
pooled_domains = self.pool(domains)
|
76 |
+
|
77 |
+
# If needed, produce additional candidate domain patches as augmentations of existing domains.
|
78 |
+
# Auxiliary learned feature maps / patches are also introduced here.
|
79 |
+
if self.n_aug_transforms > 1:
|
80 |
+
pooled_domains = self.generate_candidates(pooled_domains)
|
81 |
+
|
82 |
+
pooled_domains = repeat(pooled_domains, 'b c d h w -> b c d r h w', r=self.num_ranges)
|
83 |
+
|
84 |
+
# Apply the affine maps to domain patches
|
85 |
+
range_domains = torch.einsum('bcdrhw, bcdr -> bcrhw', pooled_domains, collage_weight)
|
86 |
+
range_domains = range_domains + collage_bias[..., None, None]
|
87 |
+
|
88 |
+
# Reconstruct data by "composing" the output patches back together (collage!).
|
89 |
+
z = patches_to_img(range_domains)
|
90 |
+
|
91 |
+
return z
|
92 |
+
|
93 |
+
def decode_step(self, z, weight, bias, superres_factor, return_patches=False):
|
94 |
+
"""Single Collage Operator step. Performs the steps described in:
|
95 |
+
https://arxiv.org/pdf/2204.07673.pdf (Def. 3.1, Figure 2).
|
96 |
+
"""
|
97 |
+
|
98 |
+
# Given the current iterate `z`, we split it into `n_domains` domain patches.
|
99 |
+
domains = img_to_patches(z, patch_h=self.dh * superres_factor, patch_w=self.dw * superres_factor)
|
100 |
+
|
101 |
+
# Pool domains (pre augmentation) for compatibility with range patches.
|
102 |
+
pooled_domains = self.pool(domains)
|
103 |
+
|
104 |
+
# If needed, produce additional candidate domain patches as augmentations of existing domains.
|
105 |
+
if self.n_aug_transforms > 1:
|
106 |
+
pooled_domains = self.generate_candidates(pooled_domains)
|
107 |
+
|
108 |
+
pooled_domains = repeat(pooled_domains, 'b c d h w -> b c d r h w', r=self.n_ranges)
|
109 |
+
|
110 |
+
# Apply the affine maps to domain patches
|
111 |
+
range_domains = torch.einsum('bcdrhw, bcdr -> bcrhw', pooled_domains, weight)
|
112 |
+
range_domains = range_domains + bias[:, :, :, None, None]
|
113 |
+
|
114 |
+
# Reconstruct data by "composing" the output patches back together (collage!).
|
115 |
+
z = patches_to_img(range_domains, self.n_rh, self.n_rw)
|
116 |
+
if return_patches: return z, (domains, pooled_domains, range_domains)
|
117 |
+
return z
|
118 |
+
|
119 |
+
def generate_candidates(self, domains):
|
120 |
+
domains = domains.permute(0,2,1,3,4)
|
121 |
+
rotations = [vmapped_rotate(domains, angle=angle) for angle in (90, 180, 270)]
|
122 |
+
hflips = ttf.hflip(domains)
|
123 |
+
vflips = ttf.vflip(domains)
|
124 |
+
br_shift = ttf.adjust_brightness(domains, 0.5)
|
125 |
+
cr_shift = ttf.adjust_contrast(domains, 0.5)
|
126 |
+
hue_shift = ttf.adjust_hue(domains, 0.5)
|
127 |
+
sat_shift = ttf.adjust_saturation(domains, 0.5)
|
128 |
+
domains = torch.cat([domains, *rotations, hflips, vflips, br_shift, cr_shift, hue_shift, sat_shift], dim=1)
|
129 |
+
return domains.permute(0,2,1,3,4)
|
130 |
+
|
131 |
+
def forward(self, x, co_w, co_bias, decode_steps=20, superres_factor=1):
|
132 |
+
B, C, H, W = x.shape
|
133 |
+
# It does not matter which initial condition is chosen, so long as the dimensions match.
|
134 |
+
# The fixed-point of a Collage Operator is uniquely determined* by the fractal code
|
135 |
+
# *: and auxiliary learned patches, if any.
|
136 |
+
z = torch.randn(B, C, H * superres_factor, W * superres_factor).to(x.device)
|
137 |
+
for _ in range(decode_steps):
|
138 |
+
z = self.decode_step(z, co_w, co_bias, superres_factor)
|
139 |
+
return z
|
140 |
+
|
141 |
+
def collage_partition_info(self, input_res, dh, dw, rh, rw):
|
142 |
+
"""
|
143 |
+
Computes auxiliary information for the collage (number of source and target domains, and relative size factors)
|
144 |
+
"""
|
145 |
+
height = width = input_res
|
146 |
+
n_dh, n_dw = height // dh, width // dw
|
147 |
+
n_domains = n_dh * n_dw
|
148 |
+
|
149 |
+
# Adjust number of domain patches to include augmentations
|
150 |
+
n_domains = n_domains + n_domains * self.n_aug_transforms # (3 rotations, hflip, vlip)
|
151 |
+
|
152 |
+
h_factors, w_factors = dh // rh, dw // rw
|
153 |
+
n_rh, n_rw = input_res // rh, input_res // rw
|
154 |
+
n_ranges = n_rh * n_rw
|
155 |
+
return n_dh, n_dw, n_rh, n_rw, h_factors, w_factors, n_domains, n_ranges
|
156 |
+
|
157 |
+
|
158 |
+
class NeuralCollageOperator2d(nn.Module):
|
159 |
+
def __init__(self, out_res, out_channels, rh, rw, dh=None, dw=None, net=None, use_augmentations=False):
|
160 |
+
super().__init__()
|
161 |
+
self.co = CollageOperator2d(out_res, rh, rw, dh, dw, use_augmentations)
|
162 |
+
# In a Collage Operator, the affine map requires a single scalar weight
|
163 |
+
# for each pair of domain and range patches, and a single scalar bias for each range.
|
164 |
+
# `net` learns to output these weights based on the objective.
|
165 |
+
self.co_w_dim = self.co.n_domains * self.co.n_ranges * out_channels
|
166 |
+
self.co_bias_dim = self.co.n_ranges * out_channels
|
167 |
+
tot_out_dim = self.co_w_dim + self.co_bias_dim
|
168 |
+
|
169 |
+
# Does not need to be a ConvMixer: for deep generative Neural Collages `net` can be e.g, a VDVAE.
|
170 |
+
if net is None:
|
171 |
+
net = ConvMixer(dim=32, depth=8, kernel_size=9, patch_size=7, num_classes=tot_out_dim)
|
172 |
+
self.net = net
|
173 |
+
|
174 |
+
self.softmax = nn.Softmax(dim=-1)
|
175 |
+
self.tanh = nn.Tanh()
|
176 |
+
|
177 |
+
def forward(self, x, decode_steps=10, superres_factor=1, return_co_code=False):
|
178 |
+
B, C, H, W = x.shape
|
179 |
+
co_code = self.net(x) # B, C, co_w_dim + co_mix_dim + co_bias_dim
|
180 |
+
co_w, co_bias = torch.split(co_code, [self.co_w_dim, self.co_bias_dim], dim=-1)
|
181 |
+
|
182 |
+
co_w = co_w.view(B, C, self.co.n_domains, self.co.n_ranges)
|
183 |
+
# No restrictions on co_w, thus no guarantee of contractiveness.
|
184 |
+
# In the full jax version of Neural Collages we enforce the constraint |co_w| < 1 (elementwise).
|
185 |
+
co_bias = co_bias.view(B, C, self.co.n_ranges)
|
186 |
+
co_bias = self.tanh(co_bias)
|
187 |
+
|
188 |
+
z = self.co(x, co_w, co_bias, decode_steps=decode_steps, superres_factor=superres_factor)
|
189 |
+
|
190 |
+
if return_co_code: return z, co_w, co_bias
|
191 |
+
else: return z
|
192 |
+
|
193 |
+
|
194 |
+
|
195 |
+
def fractalize(img, superresolution_factor=1):
|
196 |
+
superresolution_factor = int(superresolution_factor)
|
197 |
+
|
198 |
+
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
|
199 |
+
|
200 |
+
im = np.asarray(img)
|
201 |
+
|
202 |
+
im = torch.from_numpy(im).permute(2,0,1).to(device)
|
203 |
+
co = NeuralCollageOperator2d(out_res=100, out_channels=3, rh=2, rw=2, dh=100, dw=100).to(device)
|
204 |
+
|
205 |
+
opt = torch.optim.Adam(co.parameters(), lr=1e-2)
|
206 |
+
objective = nn.MSELoss()
|
207 |
+
norm_im = im.float().unsqueeze(0) / 255
|
208 |
+
|
209 |
+
for _ in range(200):
|
210 |
+
recon = co(norm_im, decode_steps=10, return_co_code=False)
|
211 |
+
|
212 |
+
loss = objective(recon, norm_im)
|
213 |
+
loss.backward()
|
214 |
+
opt.step()
|
215 |
+
opt.zero_grad()
|
216 |
+
|
217 |
+
fractal_img = co(norm_im, decode_steps=10, superres_factor=superresolution_factor)[0].permute(1,2,0).clamp(-1, 1)
|
218 |
+
return fractal_img.cpu().detach().numpy()
|
219 |
+
|
220 |
+
demo = gr.Interface(
|
221 |
+
fn=fractalize,
|
222 |
+
inputs=[gr.Image(shape=(100, 100), image_mode='RGB'), gr.Slider(1, 40, step=1)],
|
223 |
+
outputs="image"
|
224 |
+
)
|
225 |
+
demo.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy
|
2 |
+
torch
|
3 |
+
einops
|
4 |
+
timm
|
5 |
+
torchvision
|
6 |
+
functorch
|
7 |
+
torch
|