-
Notifications
You must be signed in to change notification settings - Fork 232
/
model.py
1408 lines (1204 loc) · 53.2 KB
/
model.py
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" CLIP Model
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
import functools
import inspect
from copy import deepcopy
import os
import random
import copy
from contextlib import nullcontext
from argparse import Namespace
from dataclasses import dataclass
import functools
import logging
import math
from typing import Tuple, Union, Callable, Optional
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.checkpoint import checkpoint
# apply the non-reentrant variant of checkpoint
if 'use_reentrant' in inspect.signature(checkpoint).parameters:
checkpoint = functools.partial(checkpoint, use_reentrant=False)
from .timm_model import TimmModel
from .utils import freeze_batch_norm_2d, to_2tuple
from .resnet import ModifiedResNet
from .l0module import L0Module
def load_state_dict(model, state_dict):
model.load_state_dict(state_dict, strict=True)
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor, hidden_z=None):
'''
x: (N, L, C)
hidden_z: (C,)
'''
self.hidden_z = hidden_z
orig_type = x.dtype
if hidden_z is None:
x = F.layer_norm(x, self.normalized_shape,
self.weight, self.bias, self.eps)
else:
assert len(self.normalized_shape) == 1
# [TODO] weighted layer norm
remaining_index = torch.where(hidden_z != 0)[0]
compressed_input = torch.index_select(
x, dim=-1, index=remaining_index)
compressed_weight = self.weight[remaining_index]
compressed_bias = self.bias[remaining_index]
normalized_shape = len(remaining_index)
normed_input = F.layer_norm(
compressed_input, [normalized_shape], compressed_weight, compressed_bias, self.eps)
x = x.new_zeros(x.shape)
x[..., remaining_index] = normed_input.to(orig_type)
return x.to(orig_type)
def prune(self):
if self.hidden_z is None:
return self
hidden_z = self.hidden_z
assert len(self.normalized_shape) == 1
remaining_index = torch.where(hidden_z != 0)[0]
compressed_weight = self.weight[remaining_index]
compressed_bias = self.bias[remaining_index]
# m = self
m = LayerNorm(remaining_index.shape[0]).to(self.weight.device)
m.normalized_shape = (len(remaining_index),)
m.weight.data = compressed_weight.contiguous()
m.bias.data = compressed_bias.contiguous()
return m
def prune_mul_hidden(self):
if self.hidden_z is None:
return self
hidden_z = self.hidden_z
assert len(self.normalized_shape) == 1
remaining_index = torch.where(hidden_z != 0)[0]
compressed_weight = self.weight[remaining_index] * \
hidden_z[remaining_index]
compressed_bias = self.bias[remaining_index] * \
hidden_z[remaining_index]
m = self
m.normalized_shape = (len(remaining_index),)
m.weight.data = compressed_weight.contiguous()
m.bias.data = compressed_bias.contiguous()
return m
class QuickGELU(nn.Module):
# NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory
def forward(self, x: torch.Tensor):
return x * torch.sigmoid(1.702 * x)
class Mlp(nn.Module):
def __init__(self, d_model, mlp_width, act_layer=nn.GELU, scale_fc=False):
super().__init__()
self.d_model = d_model
self.mlp_width = mlp_width
self.c_fc = nn.Linear(d_model, mlp_width)
assert not scale_fc
# self.ln = LayerNorm(mlp_width) if scale_fc else nn.Identity()
self.act_layer = act_layer
self.scale_fc = scale_fc
self.gelu = act_layer()
self.c_proj = nn.Linear(mlp_width, d_model)
def forward(self, x, hidden_z=None, intermediate_z=None):
'''
x: (N, L, C)
intermediate_z: (mlp_width,) or (1, 1, mlp_width)
hidden_z: (embed_dim,) or (1, 1, embed_dim)
'''
self.hidden_z = hidden_z
self.intermediate_z = intermediate_z
x = self.c_fc(x)
x = self.gelu(x)
if intermediate_z is not None:
x = torch.mul(x, intermediate_z)
x = self.c_proj(x)
if hidden_z is not None:
x = torch.mul(x, hidden_z)
return x
def prune(self):
device = self.c_fc.weight.device
if self.hidden_z is None:
self.hidden_z = torch.ones(
(self.d_model,), dtype=torch.bool, device=device)
if self.intermediate_z is None:
self.intermediate_z = torch.ones(
(self.mlp_width,), dtype=torch.bool, device=device)
hidden_r = torch.where(self.hidden_z != 0)[0]
intermediate_r = torch.where(self.intermediate_z != 0)[0]
d_model = len(hidden_r)
mlp_width = len(intermediate_r)
# m = self
m = copy.deepcopy(self)
m.c_fc = nn.Linear(hidden_r.shape[0], intermediate_r.shape[0])
m.c_proj = nn.Linear(intermediate_r.shape[0], hidden_r.shape[0])
m.d_model = d_model
m.mlp_width = mlp_width
m.c_fc.weight = nn.Parameter(
(self.c_fc.weight[intermediate_r][:, hidden_r]).contiguous())
m.c_fc.bias = nn.Parameter(
(self.c_fc.bias[intermediate_r]).contiguous())
m.c_proj.weight = nn.Parameter(((self.c_proj.weight *
self.intermediate_z.view(1, -1) * self.hidden_z.view(-1, 1))[hidden_r][:, intermediate_r]).contiguous())
m.c_proj.bias = nn.Parameter(
((self.c_proj.bias * self.hidden_z)[hidden_r]).contiguous())
return m
class MultiheadAttention(nn.MultiheadAttention):
def prune(self):
device = self.in_proj_weight.device
if self.hidden_z is None:
self.hidden_z = torch.ones(
(self.embed_dim,), dtype=torch.bool, device=device)
if self.head_z is None:
self.head_z = torch.ones(
(self.num_heads,), dtype=torch.bool, device=device)
hidden_r = torch.where(self.hidden_z != 0)[0]
head_r = torch.where(self.head_z != 0)[0]
d_model = len(hidden_r)
d_head = len(head_r)
org_num_heads = self.num_heads
org_head_dim = self.head_dim
org_embed_dim = self.embed_dim
mod = self
mod.use_naive_compute = True
mod.embed_dim = d_model
mod.head_dim = self.head_dim
mod.num_heads = d_head
inter_dim = d_head * self.head_dim
mod.in_proj_weight = nn.Parameter(self.in_proj_weight.view(
3, org_num_heads, org_head_dim, org_embed_dim)[:, head_r][..., hidden_r].reshape(-1, d_model))
if self.in_proj_bias is not None:
mod.in_proj_bias = nn.Parameter(self.in_proj_bias.view(
3, org_num_heads, org_head_dim)[:, head_r].reshape(-1))
mod.out_proj.weight = nn.Parameter(
((self.out_proj.weight * self.hidden_z.view(-1, 1)).
view(org_embed_dim, org_num_heads, org_head_dim) * self.head_z.view(1, org_num_heads, 1))[hidden_r][:, head_r].reshape(d_model, -1)
)
if self.out_proj.bias is not None:
mod.out_proj.bias = nn.Parameter(
(self.out_proj.bias * self.hidden_z.view(-1,)).
view(org_embed_dim)[hidden_r].reshape(-1)
)
return mod
class ResidualAttentionBlock(nn.Module):
def __init__(
self,
d_model: int,
n_head: int,
mlp_ratio: float = 4.0,
act_layer: Callable = nn.GELU,
scale_cosine_attn: bool = False,
scale_heads: bool = False,
scale_attn: bool = False,
scale_fc: bool = False,
):
super().__init__()
self.ln_1 = LayerNorm(d_model)
# FIXME torchscript issues need to be resolved for custom attention
# if scale_cosine_attn or scale_heads:
# self.attn = Attention(
# d_model, n_head,
# scaled_cosine=scale_cosine_attn,
# scale_heads=scale_heads,
# )
self.attn = MultiheadAttention(d_model, n_head)
assert not scale_attn
self.ln_attn = LayerNorm(d_model) if scale_attn else nn.Identity()
self.ln_2 = LayerNorm(d_model)
mlp_width = int(d_model * mlp_ratio)
self.mlp = Mlp(d_model, mlp_width, act_layer, scale_fc)
def attention(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None,
*,
head_z: Optional[torch.Tensor] = None,
hidden_z: Optional[torch.Tensor] = None,
):
self.attn.head_z = head_z
self.attn.hidden_z = hidden_z
if (head_z is None and hidden_z is None and
not getattr(self.attn, 'use_naive_compute', False)):
return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]
else:
# the following code does not support `attn_mask`
# x: (length, batch_size, embed_dim)
n_head = self.attn.num_heads
length, batch_size, d_model = x.shape
ws = self.attn.in_proj_weight.chunk(3)
bs = self.attn.in_proj_bias.chunk(3)
dim_per_head = len(ws[0]) // n_head
# (length, batch_size, n_head * dim_per_head)
q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)]
# (batch_size * n_head, length, d_head)
q = q.reshape(length, batch_size * n_head, -1).transpose(0, 1)
k = k.reshape(length, batch_size * n_head, -1).transpose(0, 1)
v = v.reshape(length, batch_size * n_head, -1).transpose(0, 1)
scale = dim_per_head ** -0.5
q *= scale
# (batch_size * n_head, length, length)
sim = q @ k.transpose(1, 2)
if attn_mask is not None:
sim += attn_mask
sim = torch.softmax(sim, -1)
# (batch_size * n_head, length, head_dim)
out = sim @ v
if head_z is not None:
out = out.view(batch_size, n_head, length, dim_per_head)
# head_z: (1, n_head, 1, 1)
out *= head_z.view(1, -1, 1, 1)
out = out.view(batch_size * n_head, length, dim_per_head)
out = out.transpose(0, 1).reshape(length, batch_size, -1)
out = F.linear(out, self.attn.out_proj.weight,
self.attn.out_proj.bias)
if hidden_z is not None:
out = torch.mul(out, hidden_z)
return out
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None,
hidden_z: Optional[torch.Tensor] = None,
heads_z: Optional[torch.Tensor] = None,
mha_z: Optional[torch.Tensor] = None,
intermediate_z: Optional[torch.Tensor] = None,
ffn_z: Optional[torch.Tensor] = None):
self.hidden_z = hidden_z
self.heads_z = heads_z
self.mha_z = mha_z
self.intermediate_z = intermediate_z
self.ffn_z = ffn_z
# x: (length, batch_size, embed_dim) e.g. 50, 128, 768 for vision
if self.attention is not None:
attn_out = self.attention(self.ln_1(x, hidden_z=hidden_z),
attn_mask=attn_mask,
head_z=heads_z, hidden_z=hidden_z)
if mha_z is not None: # a number
attn_out = attn_out.mul(mha_z)
x = x + attn_out
if self.mlp is not None:
ln_2_out = self.ln_2(x, hidden_z=hidden_z)
mlp_out = self.mlp(ln_2_out,
intermediate_z=intermediate_z,
hidden_z=hidden_z)
if ffn_z is not None: # a number
mlp_out = mlp_out.mul(ffn_z)
x = x + mlp_out
return x
def prune(self):
mod = self
if (self.mha_z is not None and self.mha_z.item() == 0) or (self.heads_z).sum() == 0:
mod.ln_1 = None
mod.attn = None
mod.attention = None
else:
mod.ln_1 = mod.ln_1.prune()
mod.attn = mod.attn.prune()
if self.mha_z is not None:
mod.attn.out_proj.weight.data *= self.mha_z
mod.attn.out_proj.bias.data *= self.mha_z
if self.ffn_z is not None and self.ffn_z.item() == 0:
mod.ln_2 = None
mod.mlp = None
else:
mod.ln_2 = mod.ln_2.prune()
mod.mlp = mod.mlp.prune()
if self.ffn_z is not None:
mod.mlp.c_proj.weight.data *= self.ffn_z
mod.mlp.c_proj.bias.data *= self.ffn_z
return mod
class Transformer(nn.Module):
def __init__(self, width: int, layers: int, heads: int, mlp_ratio: float = 4.0,
act_layer: Callable = nn.GELU):
super().__init__()
self.width = width
self.layers = layers
self.grad_checkpointing = False
assert width % heads == 0
self.head_dim = width // heads
self.num_heads = heads
self.mlp_ratio = mlp_ratio
self.resblocks = nn.ModuleList([
ResidualAttentionBlock(
width, heads, mlp_ratio, act_layer=act_layer)
for _ in range(layers)
])
def forward(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None,
hidden_z: Optional[torch.Tensor] = None,
heads_z: Optional[torch.Tensor] = None,
mha_z: Optional[torch.Tensor] = None,
intermediate_z: Optional[torch.Tensor] = None,
ffn_z: Optional[torch.Tensor] = None):
return self.infer_blocks(x, attn_mask,
hidden_z=hidden_z,
heads_z=heads_z,
mha_z=mha_z,
intermediate_z=intermediate_z,
ffn_z=ffn_z)
def infer_blocks(self, x: torch.Tensor, attn_mask: Optional[torch.Tensor] = None, block_idxs=None,
hidden_z: Optional[torch.Tensor] = None,
heads_z: Optional[torch.Tensor] = None,
mha_z: Optional[torch.Tensor] = None,
intermediate_z: Optional[torch.Tensor] = None,
ffn_z: Optional[torch.Tensor] = None):
num_layers = self.layers
if hidden_z is not None:
assert hidden_z.shape == (self.width,)
if heads_z is not None:
if heads_z.ndim == 5:
heads_z = heads_z.view(num_layers, self.num_heads)
assert heads_z.shape in [(num_layers, self.num_heads), (self.num_heads,)], (
heads_z.shape, (num_layers, self.num_heads))
if mha_z is not None:
assert mha_z.shape == (num_layers,), mha_z.shape
if intermediate_z is not None:
if intermediate_z.ndim == 4:
intermediate_z = intermediate_z.view(num_layers, -1)
assert intermediate_z.shape in [
(num_layers, self.mlp_ratio * self.width), (self.mlp_ratio * self.width,)], intermediate_z.shape
if ffn_z is not None:
assert ffn_z.shape == (num_layers,), ffn_z.shape
def _get_zi(z, i, ndim=2):
if z is None:
return None
if z.ndim == ndim:
return z[i]
return z
block_idxs = block_idxs or list(range(self.layers))
for i in block_idxs:
r = self.resblocks[i]
if self.grad_checkpointing and not torch.jit.is_scripting():
x = checkpoint(r, x, attn_mask,
hidden_z,
_get_zi(heads_z, i),
_get_zi(mha_z, i, ndim=1),
_get_zi(intermediate_z, i),
_get_zi(ffn_z, i, ndim=1))
else:
x = r(x, attn_mask=attn_mask,
hidden_z=hidden_z,
heads_z=_get_zi(heads_z, i),
mha_z=_get_zi(mha_z, i, ndim=1),
intermediate_z=_get_zi(intermediate_z, i),
ffn_z=_get_zi(ffn_z, i, ndim=1))
return x
@torch.jit.ignore
def set_grad_checkpointing(self, enable=True):
self.grad_checkpointing = enable
def extra_repr(self):
return f'grad_checkpointing={self.grad_checkpointing}'
def prune(self):
mod = self
for i in range(len(self.resblocks)):
self.resblocks[i] = self.resblocks[i].prune()
return mod
class VisualTransformer(nn.Module):
def __init__(
self,
image_size: int,
patch_size: int,
width: int,
layers: int,
heads: int,
mlp_ratio: float,
output_dim: int,
act_layer: Callable = nn.GELU,
teacher_width: int = -1,
):
super().__init__()
self.image_size = to_2tuple(image_size)
self.patch_size = to_2tuple(patch_size)
self.grid_size = (
self.image_size[0] // self.patch_size[0], self.image_size[1] // self.patch_size[1])
self.output_dim = output_dim
self.embed_dim = width
self.layers = layers
self.conv1 = nn.Conv2d(in_channels=3, out_channels=width,
kernel_size=patch_size, stride=patch_size, bias=False)
scale = width ** -0.5
self.class_embedding = nn.Parameter(scale * torch.randn(width))
self.positional_embedding = nn.Parameter(
scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width))
self.ln_pre = LayerNorm(width)
self.transformer = Transformer(
width, layers, heads, mlp_ratio, act_layer=act_layer)
self.head_dim = width // heads
self.ln_post = LayerNorm(width)
# image proj
if teacher_width > 0:
self.proj = nn.Parameter(torch.empty(
teacher_width, output_dim), requires_grad=False)
else:
self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
assert unlocked_groups == 0, 'partial locking not currently supported for this model'
for param in self.parameters():
param.requires_grad = False
@torch.jit.ignore
def set_grad_checkpointing(self, enable=True):
self.transformer.set_grad_checkpointing(enable)
def forward(self, x: torch.Tensor,
hidden_z: Optional[torch.Tensor] = None,
heads_z: Optional[torch.Tensor] = None,
mha_z: Optional[torch.Tensor] = None,
intermediate_z: Optional[torch.Tensor] = None,
ffn_z: Optional[torch.Tensor] = None,
embed_dim_z: Optional[torch.Tensor] = None):
self.hidden_z = hidden_z
self.embed_dim_z = embed_dim_z
x = x.to(self.conv1.weight.device)
x = self.conv1(x) # shape = [*, width, grid, grid]
# shape = [*, width, grid ** 2]
x = x.reshape(x.shape[0], x.shape[1], -1)
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
# the first token is the class token.
x = torch.cat(
[self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device),
x], dim=1) # shape = [*, 1 + grid ** 2, width]
x = x + self.positional_embedding.to(x.dtype) # 128, 50, 768
if hidden_z is not None:
x = torch.mul(x, hidden_z)
x = self.ln_pre(x, hidden_z=hidden_z)
x = x.permute(1, 0, 2) # NLD -> LND 50, 128, 768
x = self.transformer(x,
hidden_z=hidden_z,
heads_z=heads_z,
mha_z=mha_z,
intermediate_z=intermediate_z,
ffn_z=ffn_z)
x = x.permute(1, 0, 2) # LND -> NLD
# select class token
x = self.ln_post(x[:, 0, :], hidden_z=hidden_z)
if self.proj is not None:
x = self.get_proj_feature(x)
return x
def get_proj_feature(self, x):
if self.proj is not None:
x = x @ self.proj
return x
def extra_repr(self):
return 'image_size={}, output_dim={}'.format(self.image_size, self.output_dim)
def prune(self):
hidden_r = torch.where(self.hidden_z != 0)[0]
self.conv1.weight = nn.Parameter(
(self.conv1.weight.data * self.hidden_z.view(-1, 1, 1, 1))[hidden_r])
if self.conv1.bias is not None:
self.conv1.bias = nn.Parameter(
(self.conv1.bias * self.hidden_z.view(-1,))[hidden_r])
self.class_embedding = nn.Parameter(
(self.class_embedding * self.hidden_z.view(-1,))[hidden_r])
self.positional_embedding = nn.Parameter(
(self.positional_embedding * self.hidden_z.view(1, -1))[:, hidden_r])
self.ln_pre = self.ln_pre.prune()
self.transformer = self.transformer.prune()
self.ln_post = self.ln_post.prune()
if self.embed_dim_z is not None:
embed_dim_r = self.embed_dim_z > 0
self.proj = nn.Parameter((self.proj * self.hidden_z.view(-1, 1)
* self.embed_dim_z.view(1, -1))[hidden_r][:, embed_dim_r])
else:
self.proj = nn.Parameter(
(self.proj * self.hidden_z.view(-1, 1))[hidden_r])
return self
@dataclass
class CLIPVisionCfg:
layers: Union[Tuple[int, int, int, int], int] = 12
width: int = 768
teacher_width: int = -1
head_width: int = 64
mlp_ratio: float = 4.0
patch_size: int = 16
image_size: Union[Tuple[int, int], int] = 224
timm_model_name: str = None # a valid model name overrides layers, width, patch_size
# use (imagenet) pretrained weights for named model
timm_model_pretrained: bool = False
# feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '')
timm_pool: str = 'avg'
# linear projection for timm model output ('linear', 'mlp', '')
timm_proj: str = 'linear'
@dataclass
class CLIPTextCfg:
context_length: int = 77
vocab_size: int = 49408
width: int = 512
teacher_width: int = -1
heads: int = 8
layers: int = 12
class ImageEncoder(nn.Module):
def __init__(self, embed_dim, vision_cfg, quick_gelu,
l0_module_image=False,
mask_cfg=None):
super().__init__()
act_layer = QuickGELU if quick_gelu else nn.GELU
if vision_cfg.timm_model_name:
self.visual = TimmModel(
vision_cfg.timm_model_name,
pretrained=vision_cfg.timm_model_pretrained,
pool=vision_cfg.timm_pool,
proj=vision_cfg.timm_proj,
embed_dim=embed_dim,
image_size=vision_cfg.image_size
)
act_layer = nn.GELU # so that text transformer doesn't use QuickGELU w/ timm models
elif isinstance(vision_cfg.layers, (tuple, list)):
vision_heads = vision_cfg.width * 32 // vision_cfg.head_width
self.visual = ModifiedResNet(
layers=vision_cfg.layers,
output_dim=embed_dim,
heads=vision_heads,
image_size=vision_cfg.image_size,
width=vision_cfg.width
)
else:
vision_heads = vision_cfg.width // vision_cfg.head_width
self.visual = VisualTransformer(
image_size=vision_cfg.image_size,
patch_size=vision_cfg.patch_size,
width=vision_cfg.width,
layers=vision_cfg.layers,
heads=vision_heads,
mlp_ratio=vision_cfg.mlp_ratio,
output_dim=embed_dim,
act_layer=act_layer,
teacher_width=vision_cfg.teacher_width,
)
self.init_parameters()
if l0_module_image:
logging.info('use l0_module_vision')
config_mask = Namespace()
config_mask.hidden_size = vision_cfg.width
config_mask.intermediate_size = 4 * vision_cfg.width
config_mask.num_attention_heads = vision_heads
config_mask.num_hidden_layers = vision_cfg.layers
config_mask.sparsity_warmup = mask_cfg.sparsity_warmup
config_mask.sparsity = mask_cfg.sparsity
config_mask.start_sparsity = mask_cfg.start_sparsity
self.l0_module = L0Module(config_mask, lagrangian_warmup=config_mask.sparsity_warmup, start_sparsity=config_mask.start_sparsity,
target_sparsity=config_mask.sparsity, pruning_type=["hidden", "heads", "intermediate"])
else:
self.l0_module = None
self.mask = None
def init_parameters(self):
if hasattr(self.visual, 'init_parameters'):
self.visual.init_parameters()
def forward(self, image, normalized=False,
**mask):
if self.l0_module is not None:
mask = self.l0_module.forward()
self.mask = mask
image_features = self.visual(image, **mask)
embed_dim_z = mask.get('embed_dim_z', None)
if embed_dim_z is not None:
image_features = image_features.mul(embed_dim_z)
if normalized:
image_features = F.normalize(image_features, dim=-1)
return image_features
def prune(self):
self.visual = self.visual.prune()
return self
class TextEncoder(nn.Module):
def __init__(self, embed_dim, text_cfg, quick_gelu,
l0_module_text, mask_cfg=None):
super().__init__()
act_layer = QuickGELU if quick_gelu else nn.GELU
self.context_length = text_cfg.context_length
if text_cfg.layers > 0:
self.transformer = Transformer(
width=text_cfg.width,
layers=text_cfg.layers,
heads=text_cfg.heads,
act_layer=act_layer,
)
else:
self.transformer = None
self.text_projection = None
if text_cfg.layers > 0:
self.vocab_size = text_cfg.vocab_size
self.token_embedding = nn.Embedding(
text_cfg.vocab_size, text_cfg.width)
self.positional_embedding = nn.Parameter(
torch.empty(self.context_length, text_cfg.width))
self.ln_final = LayerNorm(text_cfg.width)
if text_cfg.teacher_width > 0:
self.text_projection = nn.Parameter(torch.empty(
text_cfg.width, embed_dim), requires_grad=False)
else:
self.text_projection = nn.Parameter(
torch.empty(text_cfg.width, embed_dim))
self.register_buffer(
'attn_mask', self.build_attention_mask(), persistent=False)
else:
self.token_embedding = None
self.init_parameters()
if l0_module_text:
logging.info('use l0_module_text')
config_mask = Namespace()
config_mask.hidden_size = text_cfg.width
config_mask.intermediate_size = 4 * text_cfg.width
config_mask.num_attention_heads = text_cfg.heads
config_mask.num_hidden_layers = text_cfg.layers
config_mask.sparsity_warmup = mask_cfg.sparsity_warmup
config_mask.sparsity = mask_cfg.sparsity
config_mask.start_sparsity = mask_cfg.start_sparsity
self.l0_module = L0Module(config_mask, lagrangian_warmup=config_mask.sparsity_warmup, start_sparsity=config_mask.start_sparsity,
target_sparsity=config_mask.sparsity, pruning_type=["hidden", "heads", "intermediate"])
else:
self.l0_module = None
self.mask = None
def init_parameters(self):
if self.transformer is not None:
nn.init.normal_(self.token_embedding.weight, std=0.02)
nn.init.normal_(self.positional_embedding, std=0.01)
proj_std = (self.transformer.width ** -0.5) * \
((2 * self.transformer.layers) ** -0.5)
attn_std = self.transformer.width ** -0.5
fc_std = (2 * self.transformer.width) ** -0.5
for block in self.transformer.resblocks:
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
if self.text_projection is not None:
nn.init.normal_(self.text_projection,
std=self.transformer.width ** -0.5)
def build_attention_mask(self):
# lazily create causal attention mask, with full attention between the vision tokens
# pytorch uses additive attention mask; fill with -inf
mask = torch.empty(self.context_length, self.context_length)
mask.fill_(float("-inf"))
mask.triu_(1) # zero out the lower diagonal
return mask
def encode_text(self, text, normalized=False,
hidden_z: Optional[torch.Tensor] = None,
heads_z: Optional[torch.Tensor] = None,
mha_z: Optional[torch.Tensor] = None,
intermediate_z: Optional[torch.Tensor] = None,
ffn_z: Optional[torch.Tensor] = None,
embed_dim_z: Optional[torch.Tensor] = None,
):
self.hidden_z = hidden_z
self.embed_dim_z = embed_dim_z
text = text.to(self.token_embedding.weight.device)
x = self.token_embedding(text) # [batch_size, n_ctx, d_model]
x = x + self.positional_embedding
if hidden_z is not None:
x = torch.mul(x, hidden_z)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x, attn_mask=self.attn_mask,
hidden_z=hidden_z,
heads_z=heads_z,
mha_z=mha_z,
intermediate_z=intermediate_z,
ffn_z=ffn_z)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_final(x, hidden_z)
# if hidden_z is not None:
# x = torch.mul(x, hidden_z)
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)]
# x.shape = [batch_size, n_ctx, transformer.width]
# take features from the eot embedding (eot_token is the highest number in each sequence)
x = self.get_proj_feature(x)
if embed_dim_z is not None:
x = x.mul(embed_dim_z)
if normalized:
x = F.normalize(x, dim=-1)
return x
def get_proj_feature(self, x):
return x @ self.text_projection
def forward(self, text, normalized=False):
mask = dict()
if self.l0_module is not None:
mask = self.l0_module.forward()
self.mask = mask
return self.encode_text(text, normalized=normalized, **mask)
def prune(self):
device = self.token_embedding.weight.device
if self.hidden_z is None:
self.hidden_z = torch.ones(
self.text_projection.size(0), device=device)
if self.embed_dim_z is None:
self.embed_dim_z = torch.ones(
self.text_projection.size(1), device=device)
mod = self
self_copy = copy.deepcopy(self)
hidden_r = self.hidden_z > 0
mod.token_embedding = nn.Embedding(
self_copy.token_embedding.weight.shape[0], hidden_r.sum())
mod.positional_embedding = nn.Parameter(
torch.empty(self_copy.context_length, hidden_r.sum()))
mod.token_embedding.weight = nn.Parameter(
(self_copy.token_embedding.weight * self_copy.hidden_z.view(1, -1))[:, hidden_r])
mod.positional_embedding = nn.Parameter(
(self_copy.positional_embedding * self_copy.hidden_z.view(1, -1))[:, hidden_r])
mod.transformer = self.transformer.prune()
mod.ln_final = self.ln_final.prune()
embed_dim_r = self.embed_dim_z > 0
mod.text_projection = nn.Parameter(
(self.text_projection * self.hidden_z.view(-1, 1) * self.embed_dim_z.view(1, -1))[hidden_r][:, embed_dim_r])
return mod
class LogitScale(nn.Module):
def __init__(self):
super().__init__()
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
def forward(self, dummy):
return self.logit_scale
class FNBlock(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, *args, **kwargs):
return self.fn(*args, **kwargs)
class FakeDDP(nn.Module):
def __init__(self, module):
super().__init__()
self.module = module
def forward(self, *args, **kwargs):
return self.module(*args, **kwargs)
class CLIPBase(nn.Module):
def __init__(self, image_encoder, text_encoder):
super().__init__()
self._image_encoder = image_encoder
self._text_encoder = text_encoder
self._logit_scale = LogitScale()
# autocast context
self.image_autocast = nullcontext
self.text_autocast = nullcontext
self.logit_autocast = nullcontext
# copy the module without ddp
self._without_ddp = [self._image_encoder,
self._text_encoder, self._logit_scale]
self.used_ddp = False
def set_autocast(self, image_autocast, text_autocast, logit_autocast):
self.image_autocast = image_autocast
self.text_autocast = text_autocast
self.logit_autocast = logit_autocast
@property
def image_encoder_without_ddp(self):
return self._without_ddp[0]
@image_encoder_without_ddp.setter
def image_encoder_without_ddp(self, encoder):
assert self.used_ddp is False
self._image_encoder = encoder
self._without_ddp[0] = self._image_encoder
@property
def text_encoder_without_ddp(self):
return self._without_ddp[1]
@text_encoder_without_ddp.setter
def text_encoder_without_ddp(self, encoder):
assert self.used_ddp is False
self._text_encoder = encoder
self._without_ddp[1] = self._text_encoder
@property
def logit_scale_without_ddp(self):
return self._without_ddp[2]
@logit_scale_without_ddp.setter
def logit_scale_without_ddp(self, logit_scale):
assert self.used_ddp is False
self._logit_scale = logit_scale
self._without_ddp[2] = self._logit_scale
@property
def visual(self):
return self.image_encoder_without_ddp.visual
@property
def transformer(self):
return self.text_encoder_without_ddp.transformer
@property
def text_encoder_without_ddp(self):
return self._without_ddp[1]
@property
def logit_scale_without_ddp(self):
return self._without_ddp[2]
def get_teacher(self):
return self.teacher[0]
def use_teacher_image(self):
def teacher_image_encoder_fn(image, normalized=False):
teacher = self.get_teacher()
with torch.no_grad():
return teacher.encode_image(image, normalized=normalized)
self._image_encoder = FNBlock(teacher_image_encoder_fn)
class EmptyVisual(nn.Module):
def __init__(self):
super().__init__()
self.layers = 0
self._image_encoder.visual = EmptyVisual()
self._without_ddp[0] = self._image_encoder
def use_teacher_text(self):
def teacher_text_encoder_fn(text, normalized=False):
teacher = self.get_teacher()
with torch.no_grad():
return teacher.encode_text(text, normalized=normalized)
self._text_encoder = FNBlock(teacher_text_encoder_fn)
class EmptyTransformer(nn.Module):
def __init__(self):
super().__init__()
self.layers = 0
self._text_encoder.transformer = EmptyTransformer()
self._text_encoder.token_embedding = None
self._without_ddp[1] = self._text_encoder
def ddpify(self, ddp_fn):
def _ddp_fn(module):
cnt = sum([p.numel()
for p in module.parameters() if p.requires_grad])
if cnt > 0:
return ddp_fn(module)
return FakeDDP(module)
self._image_encoder = _ddp_fn(self.image_encoder_without_ddp)
self._text_encoder = _ddp_fn(self.text_encoder_without_ddp)
self._logit_scale = _ddp_fn(self.logit_scale_without_ddp)
self.used_ddp = True
def forward(self, image, text, normalized=True):
image_features = text_features = None
if image is not None:
with self.image_autocast():
image_features = self._image_encoder(
image, normalized=normalized)
if text is not None:
with self.text_autocast():
text_features = self._text_encoder(text, normalized=normalized)
with self.logit_autocast():
logit_scale = self._logit_scale(torch.tensor(0))