Spaces:
Running
on
Zero
Running
on
Zero
File size: 13,033 Bytes
9e15541 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
import math
import random
from typing import Tuple, Optional
import kornia
import torch
from torch import nn, Tensor
import torch.nn.functional as F
import torchvision.transforms as tf
from scenedino.models.backbones.dino.decoder import NoDecoder
import logging
logger = logging.getLogger("training")
class MultiScaleCropGT_kornia(nn.Module):
"""This class implements multi-scale-crop augmentation for DINO features."""
def __init__(
self,
gt_encoder: nn.Module,
num_views: int = 8,
image_size: Tuple[int, int] = (192, 640),
feature_stride: int = 16,
) -> None:
"""Constructor method.
Args:
num_views (int): Number of view per image. Default 8.
augmentations (Tuple[AugmentationBase2D, ...]): Geometric augmentations to be applied.
feature_stride (int): Stride of the features. Default 16.
"""
# Call super constructor
super(MultiScaleCropGT_kornia, self).__init__()
# GT encoder
self.gt_encoder = gt_encoder
# Save parameters
self.augmentations_per_sample: int = num_views
self.feature_stride: int = feature_stride
# Init augmentations
image_ratio = image_size[0] / image_size[1]
augmentations = (
kornia.augmentation.RandomHorizontalFlip(p=0.5),
#kornia.augmentation.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2),
kornia.augmentation.RandomResizedCrop(
scale=(0.5, 1.0), size=tuple(image_size), ratio=(image_ratio/1.2, image_ratio*1.2), p=1.0
# Here you need to set your resolution
),
)
self.augmentations: nn.Module = kornia.augmentation.VideoSequential(*augmentations, same_on_frame=True)
@staticmethod
def _affine_transform_valid_pixels(transform: Tensor, mask: Tensor) -> Tensor:
"""Applies affine transform to a mask of ones to estimate valid pixels.
Args:
transform (Tensor): Affine transform of the shape [B, 3, 3]
mask (Tensor): Mask of the shape [B, 1, H, W].
Returns:
valid_pixels (Tensor): Mask of valid pixels of the shape [B, 1, H, W].
"""
# Get shape
H, W = mask.shape[2:] # type: int, int
# Resample mask map
valid_pixels: Tensor = kornia.geometry.warp_perspective(
mask,
transform,
(H, W),
mode="nearest",
)
# Threshold mask
valid_pixels = torch.where( # type: ignore
valid_pixels > 0.999, torch.ones_like(valid_pixels), torch.zeros_like(valid_pixels)
)
return valid_pixels
def _accumulate_predictions(self, features: Tensor, transforms: Tensor) -> Tensor:
"""Accumulates features over multiple predictions.
Args:
features (Tensor): Feature predictions of the shape [B, num_views, H, W].
transforms (Tensor): Affine transformations of the shape [B, num_views, 3, 3].
Returns:
optical_flow_predictions_accumulated (Tensor): Accumulated optical flow of the shape [B, 2, H, W].
"""
# Get shape
B, N, C, H, W = features.shape # type: int, int, int, int, int
# Get base and augmented views
features_base = features[:, -2:]
features_augmented = features[:, :-2]
# Combine batch dimension and view dimension
features_augmented = features_augmented.flatten(0, 1)
transforms = transforms.flatten(0, 1)
# Rescale transformation
transforms[:, 0, -1] = transforms[:, 0, -1] #/ float(self.feature_stride)
transforms[:, 1, -1] = transforms[:, 1, -1] #/ float(self.feature_stride)
# Invert transformations
transforms_inv: Tensor = torch.inverse(transforms)
# Resample optical flow map
features_resampled: Tensor = kornia.geometry.warp_perspective(
features_augmented,
transforms_inv,
(H, W),
mode="bilinear",
)
# Separate batch and view dimension again
features_resampled = features_resampled.reshape(B, -1, C, H, W)
# Add base views
features_resampled = torch.cat((features_resampled, features_base), dim=1)
# Reverse flip
features_resampled[:, -2] = features_resampled[:, -2].flip(dims=(-1,))
# Compute valid pixels
mask: Tensor = torch.ones(
B, N - 2, 1, H, W, dtype=features_resampled.dtype, device=features_resampled.device
)
mask = mask.flatten(0, 1)
valid_pixels: Tensor = self._affine_transform_valid_pixels(transforms_inv, mask)
valid_pixels = valid_pixels.reshape(B, N - 2, 1, H, W)
valid_pixels = F.pad(valid_pixels, (0, 0, 0, 0, 0, 0, 0, 2), value=1)
# Set invalid flow vectors to zero
features_resampled[valid_pixels.repeat(1, 1, C, 1, 1) == 0.0] = torch.nan
# Average optical flow over different views given the sum valid pixels for the specific pixel
# logger.info(features_resampled.shape)
return features_resampled.nanmean(dim=1)
def _get_augmentations(self, images: Tensor) -> Tuple[Tensor, Tensor]:
"""Forward pass generates different augmentations of the input images.
Args:
images (Tensor): Images of the shape [B, 3, H, W]
Returns:
images_augmented (Tensor): Augmented images of the shape [B, N, H, W].
transforms (Tensor): Transformations of the shape [B, N, 3, 3].
"""
# Add dummy dimension shape is [B, num_views, 3, H, W]
images = images[:, None]
# Init tensor to store transformations
transformations: Tensor = torch.empty(
images.shape[0], self.augmentations_per_sample - 2, 3, 3, dtype=torch.float32, device=images.device
)
# Init tensor to store augmented images
images_augmented: Tensor = torch.empty_like(images)
images_augmented = images_augmented[:, None].repeat_interleave(self.augmentations_per_sample, dim=1)
# Save original and flipped images
images_augmented[:, -1] = images.clone()
images_augmented[:, -2] = images.clone().flip(dims=(-1,))
# Apply geometric augmentations
for index in range(images.shape[0]):
images_repeated: Tensor = images[index][None].repeat_interleave(self.augmentations_per_sample - 2, dim=0)
images_augmented[index, :-2] = self.augmentations(images_repeated)
transformations[index] = self.augmentations.get_transformation_matrix(
images_repeated, self.augmentations._params
)
return images_augmented[:, :, 0], transformations
def forward_chunk(self, images):
batch_size, _, h, w = images.shape
# Perform augmentation
images_aug, transformations = self._get_augmentations(images)
# Get representations
features = self.gt_encoder(images_aug.flatten(0, 1))[-1]
features = F.interpolate(features, size=(h, w), mode="bilinear")
# features = features.repeat_interleave(self.feature_stride, -1).repeat_interleave(self.feature_stride, -2)
_, dino_dim, _, _ = features.shape
features = features.view(batch_size, -1, dino_dim, h, w)
chunks = torch.chunk(features, chunks=4, dim=2) # Split into 4 parts along dim=3
chunks = [self._accumulate_predictions(chunk, transformations) for chunk in chunks]
features_accumulated = torch.cat(chunks, dim=1)
# features_accumulated = self._accumulate_predictions(features, transformations)
return features_accumulated / torch.linalg.norm(features_accumulated, dim=1, keepdim=True)
def forward(self, images):
max_chunk = 16
aug_no_images = images.shape[0] * self.augmentations_per_sample
if aug_no_images > max_chunk:
no_chunks = aug_no_images // max_chunk
images = torch.chunk(images, no_chunks)
features = [self.forward_chunk(image) for image in images]
features = torch.cat(features, dim=0)
return [features]
else:
return [self.forward_chunk(images)]
class InterpolatedGT(nn.Module):
def __init__(self, arch: str, gt_encoder: nn.Module, image_size: Tuple[int, int]):
super().__init__()
self.upsampler = NoDecoder(image_size, arch, normalize_features=False)
self.gt_encoder = gt_encoder
def forward(self, x):
gt_patches = self.gt_encoder(x)
return self.upsampler(gt_patches)
def _get_affine(params, crop_size, batch_size):
# construct affine operator
affine = torch.zeros(batch_size, 2, 3)
aspect_ratio = float(crop_size[0]) / float(crop_size[1])
for i, (dy, dx, alpha, scale, flip) in enumerate(params):
# R inverse
sin = math.sin(alpha * math.pi / 180.)
cos = math.cos(alpha * math.pi / 180.)
# inverse, note how flipping is incorporated
affine[i, 0, 0], affine[i, 0, 1] = flip * cos, sin * aspect_ratio
affine[i, 1, 0], affine[i, 1, 1] = -sin / aspect_ratio, cos
# T inverse Rinv * t == R^T * t
affine[i, 0, 2] = -1. * (cos * dx + sin * dy)
affine[i, 1, 2] = -1. * (-sin * dx + cos * dy)
# T
affine[i, 0, 2] /= float(crop_size[1] // 2)
affine[i, 1, 2] /= float(crop_size[0] // 2)
# scaling
affine[i] *= scale
return affine
class MultiScaleCropGT(nn.Module):
def __init__(self,
gt_encoder: nn.Module,
num_views: int,
scale_from: float = 0.4,
grid_sample_batch: Optional[int] = 96):
super().__init__()
self.gt_encoder = gt_encoder
self.num_views = num_views
self.augmentation = MaskRandScaleCrop(scale_from)
self.grid_sample_batch = grid_sample_batch
def forward(self, x):
result = None
count = 0
batch_size, _, h, w = x.shape
for i in range(self.num_views):
if i > 0:
x, params = self.augmentation(x)
else:
params = [[0., 0., 0., 1., 1.] for _ in range(x.shape[0])]
gt_patches = self.gt_encoder(x)[-1]
affine = _get_affine(params, (h, w), batch_size).cuda()
affine_grid_gt = F.affine_grid(affine, x.size(), align_corners=False)
if self.grid_sample_batch:
d = gt_patches.shape[1]
assert d % self.grid_sample_batch == 0
for idx in range(0, d, self.grid_sample_batch):
gt_aligned_batch = F.grid_sample(gt_patches[:, idx:idx+self.grid_sample_batch], affine_grid_gt,
mode="bilinear", align_corners=False)
if result is None:
result = torch.zeros(batch_size, d, h, w, device="cuda")
result[:, idx:idx+self.grid_sample_batch] += gt_aligned_batch
else:
gt_aligned = F.grid_sample(gt_patches, affine_grid_gt, mode="bilinear", align_corners=False)
if result is None:
result = 0
result += gt_aligned
within_bounds_x = (affine_grid_gt[..., 0] >= -1) & (affine_grid_gt[..., 0] <= 1)
within_bounds_y = (affine_grid_gt[..., 1] >= -1) & (affine_grid_gt[..., 1] <= 1)
not_padded_mask = within_bounds_x & within_bounds_y
count += not_padded_mask.unsqueeze(1)
count[count == 0] = 1
return [result.div_(count)]
class MaskRandScaleCrop(object):
def __init__(self, scale_from):
self.scale_from = scale_from
def get_params(self, h, w):
new_scale = random.uniform(self.scale_from, 1)
new_h = int(new_scale * h)
new_w = int(new_scale * w)
i = random.randint(0, h - new_h)
j = random.randint(0, w - new_w)
flip = 1 if random.random() > 0.5 else -1
return i, j, new_h, new_w, new_scale, flip
def __call__(self, images, affine=None):
if affine is None:
affine = [[0., 0., 0., 1., 1.] for _ in range(len(images))]
_, H, W = images[0].shape
i2 = H / 2
j2 = W / 2
for k, image in enumerate(images):
ii, jj, h, w, s, flip = self.get_params(H, W)
if s == 1.:
continue # no change in scale
# displacement of the centre
dy = ii + h / 2 - i2
dx = jj + w / 2 - j2
affine[k][0] = dy
affine[k][1] = dx
affine[k][3] = 1 / s
# affine[k][4] = flip
assert ii >= 0 and jj >= 0
image_crop = tf.functional.crop(image, ii, jj, h, w)
images[k] = tf.functional.resize(image_crop, (H, W), tf.InterpolationMode.BILINEAR)
return images, affine
|