vit_tch 0.1.0

Vision Transformer models and building blocks for Rust using tch.
Documentation
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use tch::{Kind, Tensor, nn};

use crate::{
    config::{TwinsSVTConfig, TwinsSVTStageConfig},
    conv_layers::ChannelLayerNorm2D,
    tensor::{assert_image_patchable, window_partition, window_unpartition},
};

#[derive(Debug)]
struct PatchEmbedding {
    patch_size: i64,
    norm1: ChannelLayerNorm2D,
    proj: nn::Conv2D,
    norm2: ChannelLayerNorm2D,
}

impl PatchEmbedding {
    fn new(vs: &nn::Path, dim: i64, dim_out: i64, patch_size: i64) -> Self {
        assert!(patch_size > 0, "patch size must be positive");
        let patch_dim = dim * patch_size * patch_size;
        let norm1 = ChannelLayerNorm2D::new(&(vs / "norm1"), patch_dim, 1e-5);
        let proj = nn::conv2d(vs / "proj", patch_dim, dim_out, 1, Default::default());
        let norm2 = ChannelLayerNorm2D::new(&(vs / "norm2"), dim_out, 1e-5);

        Self {
            patch_size,
            norm1,
            proj,
            norm2,
        }
    }
}

impl nn::ModuleT for PatchEmbedding {
    fn forward_t(&self, xs: &Tensor, _train: bool) -> Tensor {
        let size = xs.size();
        let batch = size[0];
        let channels = size[1];
        let height = size[2];
        let width = size[3];
        assert_image_patchable(height, width, self.patch_size, self.patch_size);
        let grid_h = height / self.patch_size;
        let grid_w = width / self.patch_size;

        xs.view([
            batch,
            channels,
            grid_h,
            self.patch_size,
            grid_w,
            self.patch_size,
        ])
        .permute([0, 1, 3, 5, 2, 4])
        .contiguous()
        .view([
            batch,
            channels * self.patch_size * self.patch_size,
            grid_h,
            grid_w,
        ])
        .apply(&self.norm1)
        .apply(&self.proj)
        .apply(&self.norm2)
    }
}

#[derive(Debug)]
struct FeedForward2D {
    norm: ChannelLayerNorm2D,
    fc1: nn::Conv2D,
    fc2: nn::Conv2D,
    dropout: f64,
}

impl FeedForward2D {
    fn new(vs: &nn::Path, dim: i64, mult: i64, dropout: f64) -> Self {
        assert!(mult > 0, "mlp multiplier must be positive");
        let norm = ChannelLayerNorm2D::new(&(vs / "norm"), dim, 1e-5);
        let fc1 = nn::conv2d(vs / "fc1", dim, dim * mult, 1, Default::default());
        let fc2 = nn::conv2d(vs / "fc2", dim * mult, dim, 1, Default::default());

        Self {
            norm,
            fc1,
            fc2,
            dropout,
        }
    }
}

impl nn::ModuleT for FeedForward2D {
    fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor {
        xs.apply(&self.norm)
            .apply(&self.fc1)
            .gelu("none")
            .dropout(self.dropout, train)
            .apply(&self.fc2)
            .dropout(self.dropout, train)
    }
}

#[derive(Debug)]
struct LocalAttention {
    norm: ChannelLayerNorm2D,
    to_q: nn::Conv2D,
    to_kv: nn::Conv2D,
    to_out: nn::Conv2D,
    heads: i64,
    dim_head: i64,
    patch_size: i64,
    scale: f64,
    dropout: f64,
}

impl LocalAttention {
    fn new(
        vs: &nn::Path,
        dim: i64,
        heads: i64,
        dim_head: i64,
        patch_size: i64,
        dropout: f64,
    ) -> Self {
        assert!(patch_size > 0, "local patch size must be positive");
        assert!(heads > 0, "heads must be positive");
        assert!(dim_head > 0, "dim head must be positive");
        let inner_dim = heads * dim_head;
        let norm = ChannelLayerNorm2D::new(&(vs / "norm"), dim, 1e-5);
        let conv_config = nn::ConvConfig {
            bias: false,
            ..Default::default()
        };
        let to_q = nn::conv2d(vs / "to_q", dim, inner_dim, 1, conv_config);
        let to_kv = nn::conv2d(vs / "to_kv", dim, inner_dim * 2, 1, conv_config);
        let to_out = nn::conv2d(vs / "to_out", inner_dim, dim, 1, Default::default());

        Self {
            norm,
            to_q,
            to_kv,
            to_out,
            heads,
            dim_head,
            patch_size,
            scale: (dim_head as f64).powf(-0.5),
            dropout,
        }
    }
}

impl nn::ModuleT for LocalAttention {
    fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor {
        let xs = xs.apply(&self.norm);
        let size = xs.size();
        let batch = size[0];
        let height = size[2];
        let width = size[3];
        let grid_h = height / self.patch_size;
        let grid_w = width / self.patch_size;
        let windows = window_partition(&xs, self.patch_size, self.patch_size);
        let q = windows.apply(&self.to_q);
        let kv = windows.apply(&self.to_kv).chunk(2, 1);
        let window_count = q.size()[0];
        let tokens = self.patch_size * self.patch_size;

        let q = q
            .view([
                window_count,
                self.heads,
                self.dim_head,
                self.patch_size,
                self.patch_size,
            ])
            .permute([0, 1, 3, 4, 2])
            .contiguous()
            .view([window_count * self.heads, tokens, self.dim_head]);
        let k = kv[0]
            .view([
                window_count,
                self.heads,
                self.dim_head,
                self.patch_size,
                self.patch_size,
            ])
            .permute([0, 1, 3, 4, 2])
            .contiguous()
            .view([window_count * self.heads, tokens, self.dim_head]);
        let v = kv[1]
            .view([
                window_count,
                self.heads,
                self.dim_head,
                self.patch_size,
                self.patch_size,
            ])
            .permute([0, 1, 3, 4, 2])
            .contiguous()
            .view([window_count * self.heads, tokens, self.dim_head]);

        let attn = (q.matmul(&k.transpose(-1, -2)) * self.scale)
            .softmax(-1, Kind::Float)
            .dropout(self.dropout, train);
        let out = attn.matmul(&v);
        let out = out
            .view([
                window_count,
                self.heads,
                self.patch_size,
                self.patch_size,
                self.dim_head,
            ])
            .permute([0, 1, 4, 2, 3])
            .contiguous()
            .view([
                window_count,
                self.heads * self.dim_head,
                self.patch_size,
                self.patch_size,
            ])
            .apply(&self.to_out)
            .dropout(self.dropout, train);

        let _ = (grid_h, grid_w);

        window_unpartition(&out, batch, height, width, self.patch_size, self.patch_size)
    }
}

#[derive(Debug)]
struct GlobalAttention {
    norm: ChannelLayerNorm2D,
    to_q: nn::Conv2D,
    to_kv: nn::Conv2D,
    to_out: nn::Conv2D,
    heads: i64,
    dim_head: i64,
    scale: f64,
    dropout: f64,
}

impl GlobalAttention {
    fn new(
        vs: &nn::Path,
        dim: i64,
        heads: i64,
        dim_head: i64,
        global_k: i64,
        dropout: f64,
    ) -> Self {
        assert!(global_k > 0, "global k must be positive");
        assert!(heads > 0, "heads must be positive");
        assert!(dim_head > 0, "dim head must be positive");
        let inner_dim = heads * dim_head;
        let norm = ChannelLayerNorm2D::new(&(vs / "norm"), dim, 1e-5);
        let q_config = nn::ConvConfig {
            bias: false,
            ..Default::default()
        };
        let kv_config = nn::ConvConfig {
            stride: global_k,
            bias: false,
            ..Default::default()
        };
        let to_q = nn::conv2d(vs / "to_q", dim, inner_dim, 1, q_config);
        let to_kv = nn::conv2d(vs / "to_kv", dim, inner_dim * 2, global_k, kv_config);
        let to_out = nn::conv2d(vs / "to_out", inner_dim, dim, 1, Default::default());

        Self {
            norm,
            to_q,
            to_kv,
            to_out,
            heads,
            dim_head,
            scale: (dim_head as f64).powf(-0.5),
            dropout,
        }
    }
}

impl nn::ModuleT for GlobalAttention {
    fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor {
        let xs = xs.apply(&self.norm);
        let q = xs.apply(&self.to_q);
        let kv = xs.apply(&self.to_kv).chunk(2, 1);
        let size = q.size();
        let batch = size[0];
        let height = size[2];
        let width = size[3];
        let q_tokens = height * width;
        let kv_height = kv[0].size()[2];
        let kv_width = kv[0].size()[3];
        let kv_tokens = kv_height * kv_width;

        let q = q
            .view([batch, self.heads, self.dim_head, height, width])
            .permute([0, 1, 3, 4, 2])
            .contiguous()
            .view([batch * self.heads, q_tokens, self.dim_head]);
        let k = kv[0]
            .view([batch, self.heads, self.dim_head, kv_height, kv_width])
            .permute([0, 1, 3, 4, 2])
            .contiguous()
            .view([batch * self.heads, kv_tokens, self.dim_head]);
        let v = kv[1]
            .view([batch, self.heads, self.dim_head, kv_height, kv_width])
            .permute([0, 1, 3, 4, 2])
            .contiguous()
            .view([batch * self.heads, kv_tokens, self.dim_head]);

        let attn = (q.matmul(&k.transpose(-1, -2)) * self.scale)
            .softmax(-1, Kind::Float)
            .dropout(self.dropout, train);

        attn.matmul(&v)
            .view([batch, self.heads, height, width, self.dim_head])
            .permute([0, 1, 4, 2, 3])
            .contiguous()
            .view([batch, self.heads * self.dim_head, height, width])
            .apply(&self.to_out)
            .dropout(self.dropout, train)
    }
}

#[derive(Debug)]
struct TwinsTransformerLayer {
    local_attention: Option<LocalAttention>,
    local_ff: Option<FeedForward2D>,
    global_attention: GlobalAttention,
    global_ff: FeedForward2D,
}

impl TwinsTransformerLayer {
    fn new(
        vs: &nn::Path,
        dim: i64,
        config: TwinsSVTStageConfig,
        heads: i64,
        dim_head: i64,
        mlp_mult: i64,
        dropout: f64,
        has_local: bool,
    ) -> Self {
        let local_attention = has_local.then(|| {
            LocalAttention::new(
                &(vs / "local_attention"),
                dim,
                heads,
                dim_head,
                config.local_patch_size,
                dropout,
            )
        });
        let local_ff =
            has_local.then(|| FeedForward2D::new(&(vs / "local_ff"), dim, mlp_mult, dropout));
        let global_attention = GlobalAttention::new(
            &(vs / "global_attention"),
            dim,
            heads,
            dim_head,
            config.global_k,
            dropout,
        );
        let global_ff = FeedForward2D::new(&(vs / "global_ff"), dim, mlp_mult, dropout);

        Self {
            local_attention,
            local_ff,
            global_attention,
            global_ff,
        }
    }
}

impl nn::ModuleT for TwinsTransformerLayer {
    fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor {
        let mut xs = xs.shallow_clone();

        if let Some(local_attention) = &self.local_attention {
            xs = &xs + local_attention.forward_t(&xs, train);
        }

        if let Some(local_ff) = &self.local_ff {
            xs = &xs + local_ff.forward_t(&xs, train);
        }

        xs = &xs + self.global_attention.forward_t(&xs, train);
        let ff = self.global_ff.forward_t(&xs, train);

        xs + ff
    }
}

#[derive(Debug)]
struct TwinsTransformer {
    layers: Vec<TwinsTransformerLayer>,
}

impl TwinsTransformer {
    fn new(
        vs: &nn::Path,
        dim: i64,
        depth: usize,
        config: TwinsSVTStageConfig,
        heads: i64,
        dim_head: i64,
        mlp_mult: i64,
        dropout: f64,
        has_local: bool,
    ) -> Self {
        let layers = (0..depth)
            .map(|index| {
                let name = format!("layer_{index}");
                TwinsTransformerLayer::new(
                    &(vs / name.as_str()),
                    dim,
                    config,
                    heads,
                    dim_head,
                    mlp_mult,
                    dropout,
                    has_local,
                )
            })
            .collect();

        Self { layers }
    }
}

impl nn::ModuleT for TwinsTransformer {
    fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor {
        let mut xs = xs.shallow_clone();

        for layer in &self.layers {
            xs = layer.forward_t(&xs, train);
        }

        xs
    }
}

#[derive(Debug)]
struct PEG {
    proj: nn::Conv2D,
}

impl PEG {
    fn new(vs: &nn::Path, dim: i64, kernel_size: i64) -> Self {
        assert!(kernel_size > 0, "peg kernel size must be positive");
        let proj = nn::conv2d(
            vs / "proj",
            dim,
            dim,
            kernel_size,
            nn::ConvConfig {
                padding: kernel_size / 2,
                groups: dim,
                ..Default::default()
            },
        );

        Self { proj }
    }
}

impl nn::Module for PEG {
    fn forward(&self, xs: &Tensor) -> Tensor {
        xs + xs.apply(&self.proj)
    }
}

#[derive(Debug)]
struct TwinsStage {
    patch_embedding: PatchEmbedding,
    pre_peg: TwinsTransformer,
    peg: PEG,
    transformer: TwinsTransformer,
}

impl TwinsStage {
    fn new(
        vs: &nn::Path,
        dim_in: i64,
        config: TwinsSVTStageConfig,
        shared: &TwinsSVTConfig,
        is_last: bool,
    ) -> Self {
        let has_local = !is_last;
        let patch_embedding = PatchEmbedding::new(
            &(vs / "patch_embedding"),
            dim_in,
            config.emb_dim,
            config.patch_size,
        );
        let pre_peg = TwinsTransformer::new(
            &(vs / "pre_peg"),
            config.emb_dim,
            1,
            config,
            shared.heads,
            shared.dim_head,
            shared.mlp_mult,
            shared.dropout,
            has_local,
        );
        let peg = PEG::new(&(vs / "peg"), config.emb_dim, shared.peg_kernel_size);
        let transformer = TwinsTransformer::new(
            &(vs / "transformer"),
            config.emb_dim,
            config.depth,
            config,
            shared.heads,
            shared.dim_head,
            shared.mlp_mult,
            shared.dropout,
            has_local,
        );

        Self {
            patch_embedding,
            pre_peg,
            peg,
            transformer,
        }
    }
}

impl nn::ModuleT for TwinsStage {
    fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor {
        let xs = self.patch_embedding.forward_t(xs, train);
        let xs = self.pre_peg.forward_t(&xs, train);
        let xs = xs.apply(&self.peg);

        self.transformer.forward_t(&xs, train)
    }
}

#[derive(Debug)]
pub struct TwinsSVT {
    stages: Vec<TwinsStage>,
    head: nn::Linear,
}

impl TwinsSVT {
    pub fn new(vs: &nn::Path, config: TwinsSVTConfig) -> Self {
        let mut dim = config.channels;
        let mut stages = Vec::with_capacity(config.stages.len());

        for (index, stage_config) in config.stages.iter().copied().enumerate() {
            let name = format!("stage_{index}");
            let is_last = index == config.stages.len() - 1;
            stages.push(TwinsStage::new(
                &(vs / name.as_str()),
                dim,
                stage_config,
                &config,
                is_last,
            ));
            dim = stage_config.emb_dim;
        }

        let head = nn::linear(vs / "head", dim, config.num_classes, Default::default());

        Self { stages, head }
    }
}

impl nn::ModuleT for TwinsSVT {
    fn forward_t(&self, xs: &Tensor, train: bool) -> Tensor {
        let mut xs = xs.shallow_clone();

        for stage in &self.stages {
            xs = stage.forward_t(&xs, train);
        }

        xs.adaptive_avg_pool2d([1, 1]).flat_view().apply(&self.head)
    }
}