File size: 1,250 Bytes
44c8862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Visual layers and image-plane coordinates shared by the model variants."""

import torch
from torch import nn


def image_pixels(images):
    return images.permute(0, 3, 1, 2).float() / 127.5 - 1


def patch_grid(grid_size):
    axis = (torch.arange(grid_size, dtype=torch.float32) + 0.5) / grid_size
    y, x = torch.meshgrid(axis, axis, indexing="ij")
    return torch.stack((x.flatten(), y.flatten()), dim=-1)


def patch_stem(input_channels, width):
    return nn.Sequential(
        nn.Conv2d(input_channels, 48, 5, stride=2, padding=2),
        nn.GroupNorm(8, 48),
        nn.GELU(),
        nn.Conv2d(48, 96, 3, stride=2, padding=1),
        nn.GroupNorm(8, 96),
        nn.GELU(),
        nn.Conv2d(96, width, 3, stride=2, padding=1),
    )


def transformer_layers(config):
    return [
        nn.TransformerEncoderLayer(
            config.width,
            config.heads,
            4 * config.width,
            dropout=0,
            activation="gelu",
            batch_first=True,
            norm_first=True,
        )
        for _ in range(config.depth)
    ]


def center_weights(centers, coordinates):
    radii = (centers.unsqueeze(2) - coordinates).square().sum(dim=-1)
    return (-radii / (2 * 0.07**2)).softmax(dim=-1)