File size: 6,152 Bytes
3087568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Oasis 2D patch embedding."""

from __future__ import annotations

import torch
import torch.nn as nn
import triton
import triton.language as tl

from ..L1.conv2d import Conv2d


@triton.jit
def _patch_embed_2x2_kernel(
    x,
    weight,
    bias,
    out,
    N: tl.constexpr,
    BM: tl.constexpr,
    BN: tl.constexpr,
):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)
    m = pid_m * BM + tl.arange(0, BM)
    oc = pid_n * BN + tl.arange(0, BN)

    patch = m % 144
    batch = m // 144
    oh = patch // 16
    ow = patch % 16
    k = tl.arange(0, 64)
    channel = k // 4
    pixel = k % 4
    ih = oh[:, None] * 2 + pixel[None, :] // 2
    iw = ow[:, None] * 2 + pixel[None, :] % 2
    x_off = (
        batch[:, None] * (16 * 18 * 32)
        + channel[None, :] * (18 * 32)
        + ih * 32
        + iw
    )
    a = tl.load(x + x_off, mask=m[:, None] < N * 144, other=0.0)
    b = tl.load(
        weight + oc[None, :] * 64 + k[:, None],
        mask=oc[None, :] < 1024,
        other=0.0,
    )
    # Match the round-to-nearest TF32 inputs used by cuDNN on these batches.
    a_bits = a.to(tl.int32, bitcast=True)
    b_bits = b.to(tl.int32, bitcast=True)
    a_bits = (a_bits + 0xFFF + ((a_bits >> 13) & 1)) & -0x2000
    b_bits = (b_bits + 0xFFF + ((b_bits >> 13) & 1)) & -0x2000
    a_tf32 = a_bits.to(tl.float32, bitcast=True)
    b_tf32 = b_bits.to(tl.float32, bitcast=True)
    acc = tl.dot(a_tf32, b_tf32, input_precision="tf32")
    acc += tl.load(bias + oc, mask=oc < 1024, other=0.0)[None, :]
    tl.store(
        out + m[:, None] * 1024 + oc[None, :],
        acc,
        mask=(m[:, None] < N * 144) & (oc[None, :] < 1024),
    )


@triton.jit
def _patch_embed_20x20_kernel(
    x,
    weight,
    bias,
    out,
    BM: tl.constexpr,
    BN: tl.constexpr,
    BK: tl.constexpr,
):
    m = tl.program_id(0) * BM + tl.arange(0, BM)
    oc = tl.program_id(1) * BN + tl.arange(0, BN)
    oh = m // 32
    ow = m % 32
    acc = tl.zeros((BM, BN), tl.float32)

    for k0 in range(0, 1200, BK):
        k = k0 + tl.arange(0, BK)
        channel = k // 400
        pixel = k % 400
        ih = oh[:, None] * 20 + pixel[None, :] // 20
        iw = ow[:, None] * 20 + pixel[None, :] % 20
        a = tl.load(
            x + channel[None, :] * (360 * 640) + ih * 640 + iw,
            mask=(m[:, None] < 576) & (k[None, :] < 1200),
            other=0.0,
        )
        b = tl.load(
            weight + oc[None, :] * 1200 + k[:, None],
            mask=(oc[None, :] < 1024) & (k[:, None] < 1200),
            other=0.0,
        )
        acc = tl.dot(a, b, acc, input_precision="tf32x3")

    acc += tl.load(bias + oc, mask=oc < 1024, other=0.0)[None, :]
    tl.store(
        out + m[:, None] * 1024 + oc[None, :],
        acc,
        mask=(m[:, None] < 576) & (oc[None, :] < 1024),
    )


class OasisPatchEmbed(nn.Module):
    def __init__(
        self,
        img_height: int = 256,
        img_width: int = 256,
        patch_size: int = 16,
        in_chans: int = 3,
        embed_dim: int = 768,
        norm_layer=None,
        flatten: bool = True,
    ):
        super().__init__()
        self.img_size = (img_height, img_width)
        self.patch_size = (patch_size, patch_size)
        self.grid_size = (img_height // patch_size, img_width // patch_size)
        self.num_patches = self.grid_size[0] * self.grid_size[1]
        self.flatten = flatten
        self.proj = Conv2d(
            in_chans,
            embed_dim,
            kernel_size=self.patch_size,
            stride=self.patch_size,
            bias=True,
        )
        self.norm = norm_layer(embed_dim) if norm_layer else None

    def forward(self, x: torch.Tensor, random_sample: bool = False) -> torch.Tensor:
        batch, channels, height, width = x.shape
        if not random_sample and (height, width) != self.img_size:
            raise AssertionError(
                f"Input image size ({height}*{width}) doesn't match model {self.img_size}.",
            )
        if (
            x.is_cuda
            and x.dtype == torch.float32
            and x.is_contiguous()
            and self.norm is None
            and batch >= 3
            and channels == 16
            and (height, width) == (18, 32)
            and self.patch_size == (2, 2)
            and self.proj.out_channels == 1024
        ):
            source = x
            if self.flatten:
                out = torch.empty(
                    (batch, 144, 1024), device=x.device, dtype=x.dtype
                )
            else:
                out = torch.empty(
                    (batch, 9, 16, 1024), device=x.device, dtype=x.dtype
                )
            _patch_embed_2x2_kernel[
                (triton.cdiv(batch * 144, 32), triton.cdiv(1024, 64))
            ](
                x=source,
                weight=self.proj.weight,
                bias=self.proj.bias,
                out=out,
                N=batch,
                BM=32,
                BN=64,
                num_warps=4,
                num_stages=3,
            )
            return out
        if (
            x.is_cuda
            and x.dtype == torch.float32
            and x.is_contiguous()
            and self.norm is None
            and batch == 1
            and channels == 3
            and (height, width) == (360, 640)
            and self.patch_size == (20, 20)
            and self.proj.out_channels == 1024
        ):
            out = torch.empty((1, 576, 1024), device=x.device, dtype=x.dtype)
            _patch_embed_20x20_kernel[
                (triton.cdiv(576, 32), triton.cdiv(1024, 128))
            ](
                x,
                self.proj.weight,
                self.proj.bias,
                out,
                BM=32,
                BN=128,
                BK=32,
                num_warps=4,
                num_stages=3,
            )
            return out if self.flatten else out.reshape(1, 18, 32, 1024)
        x = self.proj(x)
        if self.flatten:
            x = x.flatten(2).transpose(1, 2)
        else:
            x = x.permute(0, 2, 3, 1)
        return self.norm(x) if self.norm is not None else x