FRESO-guided latent feature optimization * optimize spatial correspondence (match correlation_matrix) * optimize temporal correspondence (match warped_image)
(
sample, flows, occs, correlation_matrix=[], intra_weight=1e2, iters=20, unet_chunk_size=2, optimize_temporal=True
)
| 173 | |
| 174 | |
| 175 | def optimize_feature( |
| 176 | sample, flows, occs, correlation_matrix=[], intra_weight=1e2, iters=20, unet_chunk_size=2, optimize_temporal=True |
| 177 | ): |
| 178 | """ |
| 179 | FRESO-guided latent feature optimization |
| 180 | * optimize spatial correspondence (match correlation_matrix) |
| 181 | * optimize temporal correspondence (match warped_image) |
| 182 | """ |
| 183 | if (flows is None or occs is None or (not optimize_temporal)) and ( |
| 184 | intra_weight == 0 or len(correlation_matrix) == 0 |
| 185 | ): |
| 186 | return sample |
| 187 | # flows=[fwd_flows, bwd_flows]: (N-1)*2*H1*W1 |
| 188 | # occs=[fwd_occs, bwd_occs]: (N-1)*H1*W1 |
| 189 | # sample: 2N*C*H*W |
| 190 | torch.cuda.empty_cache() |
| 191 | video_length = sample.shape[0] // unet_chunk_size |
| 192 | latent = rearrange(sample.to(torch.float32), "(b f) c h w -> b f c h w", f=video_length) |
| 193 | |
| 194 | cs = torch.nn.Parameter((latent.detach().clone())) |
| 195 | optimizer = torch.optim.Adam([cs], lr=0.2) |
| 196 | |
| 197 | # unify resolution |
| 198 | if flows is not None and occs is not None: |
| 199 | scale = sample.shape[2] * 1.0 / flows[0].shape[2] |
| 200 | kernel = int(1 / scale) |
| 201 | bwd_flow_ = F.interpolate(flows[1] * scale, scale_factor=scale, mode="bilinear").repeat( |
| 202 | unet_chunk_size, 1, 1, 1 |
| 203 | ) |
| 204 | bwd_occ_ = F.max_pool2d(occs[1].unsqueeze(1), kernel_size=kernel).repeat( |
| 205 | unet_chunk_size, 1, 1, 1 |
| 206 | ) # 2(N-1)*1*H1*W1 |
| 207 | fwd_flow_ = F.interpolate(flows[0] * scale, scale_factor=scale, mode="bilinear").repeat( |
| 208 | unet_chunk_size, 1, 1, 1 |
| 209 | ) |
| 210 | fwd_occ_ = F.max_pool2d(occs[0].unsqueeze(1), kernel_size=kernel).repeat( |
| 211 | unet_chunk_size, 1, 1, 1 |
| 212 | ) # 2(N-1)*1*H1*W1 |
| 213 | # match frame 0,1,2,3 and frame 1,2,3,0 |
| 214 | reshuffle_list = list(range(1, video_length)) + [0] |
| 215 | |
| 216 | # attention_probs is the GRAM matrix of the normalized feature |
| 217 | attention_probs = None |
| 218 | for tmp in correlation_matrix: |
| 219 | if sample.shape[2] * sample.shape[3] == tmp.shape[1]: |
| 220 | attention_probs = tmp # 2N*HW*HW |
| 221 | break |
| 222 | |
| 223 | n_iter = [0] |
| 224 | while n_iter[0] < iters: |
| 225 | |
| 226 | def closure(): |
| 227 | optimizer.zero_grad() |
| 228 | |
| 229 | loss = 0 |
| 230 | |
| 231 | # temporal consistency loss |
| 232 | if optimize_temporal and flows is not None and occs is not None: |
no test coverage detected