Upload model
Browse files- README.md +199 -0
- config.json +30 -0
- config.py +27 -0
- decoder.py +87 -0
- encoder.py +78 -0
- marlin.py +129 -0
- model.safetensors +3 -0
- modules.py +234 -0
- positional_embedding.py +49 -0
README.md
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
config.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"MarlinModel"
|
4 |
+
],
|
5 |
+
"as_feature_extractor": true,
|
6 |
+
"attn_drop_rate": 0.0,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "config.MarlinConfig",
|
9 |
+
"AutoModel": "marlin.MarlinModel"
|
10 |
+
},
|
11 |
+
"decoder_depth": 4,
|
12 |
+
"decoder_embed_dim": 384,
|
13 |
+
"decoder_num_heads": 6,
|
14 |
+
"drop_rate": 0.0,
|
15 |
+
"encoder_depth": 12,
|
16 |
+
"encoder_embed_dim": 768,
|
17 |
+
"encoder_num_heads": 12,
|
18 |
+
"img_size": 224,
|
19 |
+
"init_values": 0.0,
|
20 |
+
"mlp_ratio": 4.0,
|
21 |
+
"model_type": "marlin",
|
22 |
+
"n_frames": 16,
|
23 |
+
"norm_layer": "LayerNorm",
|
24 |
+
"patch_size": 16,
|
25 |
+
"qk_scale": null,
|
26 |
+
"qkv_bias": true,
|
27 |
+
"torch_dtype": "float32",
|
28 |
+
"transformers_version": "4.50.3",
|
29 |
+
"tubelet_size": 2
|
30 |
+
}
|
config.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class MarlinConfig(PretrainedConfig):
|
5 |
+
model_type = "marlin"
|
6 |
+
|
7 |
+
def __init__(self, **kwargs):
|
8 |
+
self.img_size = kwargs.pop("img_size", None)
|
9 |
+
self.patch_size = kwargs.pop("patch_size", None)
|
10 |
+
self.n_frames = kwargs.pop("n_frames", None)
|
11 |
+
self.encoder_embed_dim = kwargs.pop("encoder_embed_dim", None)
|
12 |
+
self.encoder_depth = kwargs.pop("encoder_depth", None)
|
13 |
+
self.encoder_num_heads = kwargs.pop("encoder_num_heads", None)
|
14 |
+
self.decoder_embed_dim = kwargs.pop("decoder_embed_dim", None)
|
15 |
+
self.decoder_depth = kwargs.pop("decoder_depth", None)
|
16 |
+
self.decoder_num_heads = kwargs.pop("decoder_num_heads", None)
|
17 |
+
self.mlp_ratio = kwargs.pop("mlp_ratio", None)
|
18 |
+
self.qkv_bias = kwargs.pop("qkv_bias", None)
|
19 |
+
self.qk_scale = kwargs.pop("qk_scale", None)
|
20 |
+
self.drop_rate = kwargs.pop("drop_rate", None)
|
21 |
+
self.attn_drop_rate = kwargs.pop("attn_drop_rate", None)
|
22 |
+
self.norm_layer = kwargs.pop("norm_layer", None)
|
23 |
+
self.init_values = kwargs.pop("init_values", None)
|
24 |
+
self.tubelet_size = kwargs.pop("tubelet_size", None)
|
25 |
+
self.as_feature_extractor = kwargs.pop("as_feature_extractor", True)
|
26 |
+
|
27 |
+
super().__init__(**kwargs)
|
decoder.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from einops import rearrange
|
3 |
+
from torch import nn, Tensor
|
4 |
+
from torch.nn import LayerNorm, Linear, ModuleList
|
5 |
+
|
6 |
+
from .modules import Block, no_grad_trunc_normal_
|
7 |
+
from .positional_embedding import SinCosPositionalEmbedding
|
8 |
+
|
9 |
+
|
10 |
+
class MarlinDecoder(nn.Module):
|
11 |
+
|
12 |
+
def __init__(self, img_size=224, patch_size=16, n_frames=16, embed_dim=384, depth=8,
|
13 |
+
num_heads=6, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
|
14 |
+
norm_layer="LayerNorm", init_values=1., tubelet_size=2
|
15 |
+
):
|
16 |
+
super().__init__()
|
17 |
+
output_dim = 3 * tubelet_size * patch_size * patch_size
|
18 |
+
self.patch_size = patch_size
|
19 |
+
self.tubelet_size = tubelet_size
|
20 |
+
self.n_patch_h = img_size // patch_size
|
21 |
+
self.n_patch_w = img_size // patch_size
|
22 |
+
self.embed_dim = embed_dim
|
23 |
+
if norm_layer == "LayerNorm":
|
24 |
+
self.norm_layer = LayerNorm
|
25 |
+
self.norm = self.norm_layer(embed_dim)
|
26 |
+
else:
|
27 |
+
raise NotImplementedError("Only LayerNorm is supported")
|
28 |
+
|
29 |
+
# sine-cosine positional embeddings
|
30 |
+
self.pos_embedding = SinCosPositionalEmbedding(
|
31 |
+
(self.n_patch_h * self.n_patch_w * (n_frames // tubelet_size), embed_dim), dropout_rate=0.)
|
32 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
33 |
+
|
34 |
+
self.blocks = ModuleList([
|
35 |
+
Block(
|
36 |
+
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
37 |
+
drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=self.norm_layer,
|
38 |
+
init_values=init_values
|
39 |
+
) for _ in range(depth)])
|
40 |
+
|
41 |
+
self.head = Linear(embed_dim, output_dim)
|
42 |
+
self.apply(self._init_weights)
|
43 |
+
no_grad_trunc_normal_(self.mask_token, mean=0., std=0.02, a=-0.02, b=0.02)
|
44 |
+
|
45 |
+
@staticmethod
|
46 |
+
def _init_weights(m):
|
47 |
+
if isinstance(m, nn.Linear):
|
48 |
+
nn.init.xavier_uniform_(m.weight)
|
49 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
50 |
+
nn.init.constant_(m.bias, 0)
|
51 |
+
elif isinstance(m, nn.LayerNorm):
|
52 |
+
nn.init.constant_(m.bias, 0)
|
53 |
+
nn.init.constant_(m.weight, 1.0)
|
54 |
+
|
55 |
+
def unpatch_to_img(self, x: Tensor) -> Tensor:
|
56 |
+
# x: (Batch, No. batches, Prod of cube size * C)
|
57 |
+
x = rearrange(x, "b n (c p) -> b n p c", c=3)
|
58 |
+
# x: (Batch, No. batches, Prod of cube size, C)
|
59 |
+
x = rearrange(x, "b (t h w) (p0 p1 p2) c -> b c (t p0) (h p1) (w p2)", p0=self.tubelet_size,
|
60 |
+
p1=self.patch_size, p2=self.patch_size, h=self.n_patch_h, w=self.n_patch_w)
|
61 |
+
# x: (B, C, T, H, W)
|
62 |
+
return x
|
63 |
+
|
64 |
+
def forward_features(self, x, return_token_num=0):
|
65 |
+
for block in self.blocks:
|
66 |
+
x = block(x)
|
67 |
+
|
68 |
+
if return_token_num > 0:
|
69 |
+
x = x[:, -return_token_num:]
|
70 |
+
|
71 |
+
x = self.norm(x)
|
72 |
+
x = self.head(x)
|
73 |
+
# x: (B, N_mask, C)
|
74 |
+
return x
|
75 |
+
|
76 |
+
def forward(self, x, mask):
|
77 |
+
# mask: 0 -> masked, 1 -> visible
|
78 |
+
b, n, c = x.shape
|
79 |
+
expand_pos_embed = self.pos_embedding.emb.data.expand(b, -1, -1)
|
80 |
+
pos_emb_vis = expand_pos_embed[mask].view(b, -1, c)
|
81 |
+
pos_emb_mask = expand_pos_embed[~mask].view(b, -1, c)
|
82 |
+
x = torch.cat([x + pos_emb_vis, self.mask_token + pos_emb_mask], dim=1)
|
83 |
+
|
84 |
+
mask_num = pos_emb_mask.shape[1]
|
85 |
+
|
86 |
+
x = self.forward_features(x, return_token_num=mask_num)
|
87 |
+
return x
|
encoder.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn, Tensor
|
2 |
+
from torch.nn import ModuleList, LayerNorm
|
3 |
+
|
4 |
+
from .modules import PatchEmbedding3d, Block
|
5 |
+
from .positional_embedding import SinCosPositionalEmbedding
|
6 |
+
|
7 |
+
|
8 |
+
class MarlinEncoder(nn.Module):
|
9 |
+
|
10 |
+
def __init__(self, img_size=224, patch_size=16, n_frames=16, embed_dim=768, depth=12,
|
11 |
+
num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
|
12 |
+
norm_layer="LayerNorm", init_values=0., tubelet_size=2
|
13 |
+
):
|
14 |
+
super().__init__()
|
15 |
+
|
16 |
+
self.embed_dim = embed_dim
|
17 |
+
self.patch_embedding = PatchEmbedding3d(
|
18 |
+
input_size=(3, n_frames, img_size, img_size),
|
19 |
+
patch_size=(tubelet_size, patch_size, patch_size),
|
20 |
+
embedding=embed_dim
|
21 |
+
)
|
22 |
+
num_patches = (img_size // patch_size) * (img_size // patch_size) * (n_frames // tubelet_size)
|
23 |
+
|
24 |
+
# sine-cosine positional embeddings
|
25 |
+
self.pos_embedding = SinCosPositionalEmbedding((num_patches, embed_dim), dropout_rate=0.)
|
26 |
+
|
27 |
+
if norm_layer == "LayerNorm":
|
28 |
+
self.norm_layer = LayerNorm
|
29 |
+
self.norm = self.norm_layer(embed_dim)
|
30 |
+
else:
|
31 |
+
raise NotImplementedError("Only LayerNorm is supported")
|
32 |
+
|
33 |
+
self.blocks = ModuleList([
|
34 |
+
Block(
|
35 |
+
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
36 |
+
drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=self.norm_layer,
|
37 |
+
init_values=init_values)
|
38 |
+
for _ in range(depth)
|
39 |
+
])
|
40 |
+
|
41 |
+
self.apply(self._init_weights)
|
42 |
+
|
43 |
+
@staticmethod
|
44 |
+
def _init_weights(m):
|
45 |
+
if isinstance(m, nn.Linear):
|
46 |
+
nn.init.xavier_uniform_(m.weight)
|
47 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
48 |
+
nn.init.constant_(m.bias, 0)
|
49 |
+
elif isinstance(m, nn.LayerNorm):
|
50 |
+
nn.init.constant_(m.bias, 0)
|
51 |
+
nn.init.constant_(m.weight, 1.0)
|
52 |
+
|
53 |
+
def forward_features(self, x):
|
54 |
+
for block in self.blocks:
|
55 |
+
x = block(x)
|
56 |
+
x = self.norm(x)
|
57 |
+
return x
|
58 |
+
|
59 |
+
def forward(self, x: Tensor, mask: Tensor) -> Tensor:
|
60 |
+
# mask: (B, T, N) with boolean values, 0 -> masked, 1 -> visible
|
61 |
+
assert len(x.shape) == 5, "x must be 5D"
|
62 |
+
emb = self.patch_embedding(x)
|
63 |
+
emb = self.pos_embedding(emb)
|
64 |
+
b, _, c = emb.shape
|
65 |
+
emb = emb[mask].view(b, -1, c) # only visible patches are used
|
66 |
+
emb = self.forward_features(emb)
|
67 |
+
return emb
|
68 |
+
|
69 |
+
def extract_features(self, x: Tensor, seq_mean_pool: bool) -> Tensor:
|
70 |
+
x = self.patch_embedding(x)
|
71 |
+
x = self.pos_embedding(x)
|
72 |
+
for block in self.blocks:
|
73 |
+
x = block(x)
|
74 |
+
|
75 |
+
if seq_mean_pool:
|
76 |
+
x = x.mean(dim=1)
|
77 |
+
x = self.norm(x)
|
78 |
+
return x
|
marlin.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from torch import Tensor
|
5 |
+
from torch.nn import Linear, Module
|
6 |
+
from transformers import PreTrainedModel
|
7 |
+
|
8 |
+
from .encoder import MarlinEncoder
|
9 |
+
from .decoder import MarlinDecoder
|
10 |
+
|
11 |
+
from .config import MarlinConfig
|
12 |
+
|
13 |
+
|
14 |
+
class Marlin(Module):
|
15 |
+
def __init__(
|
16 |
+
self,
|
17 |
+
img_size: int,
|
18 |
+
patch_size: int,
|
19 |
+
n_frames: int,
|
20 |
+
encoder_embed_dim: int,
|
21 |
+
encoder_depth: int,
|
22 |
+
encoder_num_heads: int,
|
23 |
+
decoder_embed_dim: int,
|
24 |
+
decoder_depth: int,
|
25 |
+
decoder_num_heads: int,
|
26 |
+
mlp_ratio: float,
|
27 |
+
qkv_bias: bool,
|
28 |
+
qk_scale: Optional[float],
|
29 |
+
drop_rate: float,
|
30 |
+
attn_drop_rate: float,
|
31 |
+
norm_layer: str,
|
32 |
+
init_values: float,
|
33 |
+
tubelet_size: int,
|
34 |
+
as_feature_extractor: bool = True,
|
35 |
+
):
|
36 |
+
super().__init__()
|
37 |
+
self.encoder = MarlinEncoder(
|
38 |
+
img_size=img_size,
|
39 |
+
patch_size=patch_size,
|
40 |
+
n_frames=n_frames,
|
41 |
+
embed_dim=encoder_embed_dim,
|
42 |
+
depth=encoder_depth,
|
43 |
+
num_heads=encoder_num_heads,
|
44 |
+
mlp_ratio=mlp_ratio,
|
45 |
+
qkv_bias=qkv_bias,
|
46 |
+
qk_scale=qk_scale,
|
47 |
+
drop_rate=drop_rate,
|
48 |
+
attn_drop_rate=attn_drop_rate,
|
49 |
+
norm_layer=norm_layer,
|
50 |
+
init_values=init_values,
|
51 |
+
tubelet_size=tubelet_size,
|
52 |
+
)
|
53 |
+
self.as_feature_extractor = as_feature_extractor
|
54 |
+
self.clip_frames = n_frames
|
55 |
+
if as_feature_extractor:
|
56 |
+
self.enc_dec_proj = None
|
57 |
+
self.decoder = None
|
58 |
+
else:
|
59 |
+
self.decoder = MarlinDecoder(
|
60 |
+
img_size=img_size,
|
61 |
+
patch_size=patch_size,
|
62 |
+
embed_dim=decoder_embed_dim,
|
63 |
+
depth=decoder_depth,
|
64 |
+
num_heads=decoder_num_heads,
|
65 |
+
mlp_ratio=mlp_ratio,
|
66 |
+
qkv_bias=qkv_bias,
|
67 |
+
qk_scale=qk_scale,
|
68 |
+
drop_rate=drop_rate,
|
69 |
+
attn_drop_rate=attn_drop_rate,
|
70 |
+
norm_layer=norm_layer,
|
71 |
+
init_values=init_values,
|
72 |
+
tubelet_size=tubelet_size,
|
73 |
+
)
|
74 |
+
|
75 |
+
self.enc_dec_proj = Linear(encoder_embed_dim, decoder_embed_dim, bias=False)
|
76 |
+
|
77 |
+
def forward(self, x: Tensor, mask: Tensor = None) -> Tensor:
|
78 |
+
if self.as_feature_extractor:
|
79 |
+
raise RuntimeError(
|
80 |
+
"For feature extraction, please use `extract_features` or `extract_video`."
|
81 |
+
)
|
82 |
+
else:
|
83 |
+
assert mask is not None
|
84 |
+
x = self.encoder(x, mask)
|
85 |
+
x = self.enc_dec_proj(x)
|
86 |
+
x = self.decoder(x, mask)
|
87 |
+
return x
|
88 |
+
|
89 |
+
@property
|
90 |
+
def device(self):
|
91 |
+
return self.encoder.norm.weight.device
|
92 |
+
|
93 |
+
def extract_features(self, x: Tensor, keep_seq: bool = True):
|
94 |
+
"""Extract features for one video clip (v)"""
|
95 |
+
if self.training:
|
96 |
+
return self.encoder.extract_features(x, seq_mean_pool=not keep_seq)
|
97 |
+
else:
|
98 |
+
with torch.no_grad():
|
99 |
+
return self.encoder.extract_features(x, seq_mean_pool=not keep_seq)
|
100 |
+
|
101 |
+
|
102 |
+
class MarlinModel(PreTrainedModel):
|
103 |
+
config_class = MarlinConfig
|
104 |
+
|
105 |
+
def __init__(self, config: MarlinConfig):
|
106 |
+
super().__init__(config)
|
107 |
+
self.config = config
|
108 |
+
self.marlin = Marlin(
|
109 |
+
img_size=config.img_size,
|
110 |
+
patch_size=config.patch_size,
|
111 |
+
n_frames=config.n_frames,
|
112 |
+
encoder_embed_dim=config.encoder_embed_dim,
|
113 |
+
encoder_depth=config.encoder_depth,
|
114 |
+
encoder_num_heads=config.encoder_num_heads,
|
115 |
+
decoder_embed_dim=config.decoder_embed_dim,
|
116 |
+
decoder_depth=config.decoder_depth,
|
117 |
+
decoder_num_heads=config.decoder_num_heads,
|
118 |
+
mlp_ratio=config.mlp_ratio,
|
119 |
+
qkv_bias=config.qkv_bias,
|
120 |
+
qk_scale=config.qk_scale,
|
121 |
+
drop_rate=config.drop_rate,
|
122 |
+
attn_drop_rate=config.attn_drop_rate,
|
123 |
+
norm_layer=config.norm_layer,
|
124 |
+
init_values=config.init_values,
|
125 |
+
tubelet_size=config.tubelet_size,
|
126 |
+
)
|
127 |
+
|
128 |
+
def forward(self, x: Tensor, keep_seq: bool = True):
|
129 |
+
return self.marlin.extract_features(x, keep_seq=keep_seq)
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a0bf06598cd8df475456224a33f7f051a167aa8bf8730b975ded930da556b6e9
|
3 |
+
size 349743632
|
modules.py
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import warnings
|
3 |
+
from typing import Union, Optional, Callable, Tuple, List, Sequence
|
4 |
+
|
5 |
+
import torch
|
6 |
+
from einops.layers.torch import Rearrange
|
7 |
+
from torch import Tensor, nn, Size
|
8 |
+
from torch.nn import Conv3d, ModuleList
|
9 |
+
from torch.nn import functional as F
|
10 |
+
|
11 |
+
Shape = Union[Size, List[int], Tuple[int, ...]]
|
12 |
+
ModuleFactory = Union[Callable[[], nn.Module], Callable[[int], nn.Module]]
|
13 |
+
|
14 |
+
|
15 |
+
class PatchEmbedding3d(nn.Module):
|
16 |
+
|
17 |
+
def __init__(self, input_size: Shape, patch_size: Union[int, Shape], embedding: int,
|
18 |
+
strides: Optional[Union[int, Shape]] = None,
|
19 |
+
build_normalization: Optional[ModuleFactory] = None
|
20 |
+
):
|
21 |
+
super().__init__()
|
22 |
+
# channel, time, height, width
|
23 |
+
c, t, h, w = input_size
|
24 |
+
# patch_time, patch_height, patch_width
|
25 |
+
pt, ph, pw = (patch_size, patch_size, patch_size) if type(patch_size) is int else patch_size
|
26 |
+
|
27 |
+
# configure the strides for conv3d
|
28 |
+
if strides is None:
|
29 |
+
# no specified means no overlap and gap between patches
|
30 |
+
strides = (pt, ph, pw)
|
31 |
+
elif type(strides) is int:
|
32 |
+
# transform the side length of strides to 3D
|
33 |
+
strides = (strides, strides, strides)
|
34 |
+
|
35 |
+
self.projection = Conv3d(c, embedding, kernel_size=(pt, ph, pw), stride=strides)
|
36 |
+
self.has_norm = build_normalization is not None
|
37 |
+
if self.has_norm:
|
38 |
+
self.normalization = build_normalization()
|
39 |
+
self.rearrange = Rearrange("b d nt nh nw -> b (nt nh nw) d")
|
40 |
+
|
41 |
+
def forward(self, x: Tensor) -> Tensor:
|
42 |
+
x = self.projection(x)
|
43 |
+
x = self.rearrange(x)
|
44 |
+
if self.has_norm:
|
45 |
+
x = self.normalization(x)
|
46 |
+
return x
|
47 |
+
|
48 |
+
|
49 |
+
class Linear(nn.Module):
|
50 |
+
|
51 |
+
def __init__(self, in_features: int, out_features: int, bias: bool = True,
|
52 |
+
build_activation: Optional[ModuleFactory] = None,
|
53 |
+
build_normalization: Optional[ModuleFactory] = None,
|
54 |
+
normalization_after_activation: bool = False,
|
55 |
+
dropout_rate: float = 0.
|
56 |
+
):
|
57 |
+
super().__init__()
|
58 |
+
self.linear = nn.Linear(in_features, out_features, bias)
|
59 |
+
|
60 |
+
self.has_act = build_activation is not None
|
61 |
+
if self.has_act:
|
62 |
+
self.activation = build_activation()
|
63 |
+
else:
|
64 |
+
self.activation = None
|
65 |
+
|
66 |
+
self.has_norm = build_normalization is not None
|
67 |
+
if self.has_norm:
|
68 |
+
self.normalization = build_normalization()
|
69 |
+
self.norm_after_act = normalization_after_activation
|
70 |
+
else:
|
71 |
+
self.normalization = None
|
72 |
+
|
73 |
+
self.has_dropout = dropout_rate > 0
|
74 |
+
if self.has_dropout:
|
75 |
+
self.dropout = nn.Dropout(dropout_rate)
|
76 |
+
|
77 |
+
def forward(self, x: Tensor) -> Tensor:
|
78 |
+
x = self.linear(x)
|
79 |
+
if self.has_act and self.has_norm:
|
80 |
+
if self.norm_after_act:
|
81 |
+
x = self.activation(x)
|
82 |
+
x = self.normalization(x)
|
83 |
+
else:
|
84 |
+
x = self.normalization(x)
|
85 |
+
x = self.activation(x)
|
86 |
+
elif self.has_act and not self.has_norm:
|
87 |
+
x = self.activation(x)
|
88 |
+
elif not self.has_act and self.has_norm:
|
89 |
+
x = self.normalization(x)
|
90 |
+
|
91 |
+
if self.has_dropout:
|
92 |
+
x = self.dropout(x)
|
93 |
+
return x
|
94 |
+
|
95 |
+
|
96 |
+
class MLP(nn.Module):
|
97 |
+
|
98 |
+
def __init__(self, neurons: Sequence[int],
|
99 |
+
build_activation: Optional[ModuleFactory] = None, dropout_rate: float = 0.
|
100 |
+
):
|
101 |
+
super().__init__()
|
102 |
+
n_features = neurons[1:]
|
103 |
+
self.layers: ModuleList[Linear] = ModuleList(
|
104 |
+
[Linear(neurons[i], neurons[i + 1], True, build_activation, None,
|
105 |
+
False, dropout_rate
|
106 |
+
) for i in range(len(n_features) - 1)
|
107 |
+
] + [
|
108 |
+
Linear(neurons[-2], neurons[-1], True)
|
109 |
+
]
|
110 |
+
)
|
111 |
+
|
112 |
+
def forward(self, x: Tensor) -> Tensor:
|
113 |
+
for layer in self.layers:
|
114 |
+
x = layer(x)
|
115 |
+
return x
|
116 |
+
|
117 |
+
|
118 |
+
class Attention(nn.Module):
|
119 |
+
|
120 |
+
def __init__(
|
121 |
+
self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
|
122 |
+
proj_drop=0., attn_head_dim=None
|
123 |
+
):
|
124 |
+
super().__init__()
|
125 |
+
self.num_heads = num_heads
|
126 |
+
head_dim = dim // num_heads
|
127 |
+
if attn_head_dim is not None:
|
128 |
+
head_dim = attn_head_dim
|
129 |
+
all_head_dim = head_dim * self.num_heads
|
130 |
+
self.scale = qk_scale or head_dim ** -0.5
|
131 |
+
|
132 |
+
self.qkv = nn.Linear(dim, all_head_dim * 3, bias=False)
|
133 |
+
if qkv_bias:
|
134 |
+
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
|
135 |
+
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
|
136 |
+
else:
|
137 |
+
self.q_bias = None
|
138 |
+
self.v_bias = None
|
139 |
+
|
140 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
141 |
+
self.proj = nn.Linear(all_head_dim, dim)
|
142 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
143 |
+
|
144 |
+
def forward(self, x):
|
145 |
+
B, N, C = x.shape
|
146 |
+
qkv_bias = None
|
147 |
+
if self.q_bias is not None:
|
148 |
+
qkv_bias = torch.cat((self.q_bias, torch.zeros_like(self.v_bias, requires_grad=False), self.v_bias))
|
149 |
+
# qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
150 |
+
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
|
151 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
152 |
+
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
|
153 |
+
|
154 |
+
q = q * self.scale
|
155 |
+
attn = (q @ k.transpose(-2, -1))
|
156 |
+
|
157 |
+
attn = attn.softmax(dim=-1)
|
158 |
+
attn = self.attn_drop(attn)
|
159 |
+
|
160 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
161 |
+
x = self.proj(x)
|
162 |
+
x = self.proj_drop(x)
|
163 |
+
return x
|
164 |
+
|
165 |
+
|
166 |
+
class Block(nn.Module):
|
167 |
+
|
168 |
+
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
|
169 |
+
init_values=None, act_layer=nn.GELU, norm_layer=nn.LayerNorm,
|
170 |
+
attn_head_dim=None
|
171 |
+
):
|
172 |
+
super().__init__()
|
173 |
+
self.norm1 = norm_layer(dim)
|
174 |
+
self.attn = Attention(
|
175 |
+
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
|
176 |
+
attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim)
|
177 |
+
self.norm2 = norm_layer(dim)
|
178 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
179 |
+
self.mlp = MLP(
|
180 |
+
neurons=[dim, mlp_hidden_dim, dim],
|
181 |
+
build_activation=act_layer,
|
182 |
+
dropout_rate=drop
|
183 |
+
)
|
184 |
+
|
185 |
+
if init_values > 0:
|
186 |
+
self.gamma_1 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
187 |
+
self.gamma_2 = nn.Parameter(init_values * torch.ones((dim)), requires_grad=True)
|
188 |
+
else:
|
189 |
+
self.gamma_1, self.gamma_2 = None, None
|
190 |
+
|
191 |
+
def forward(self, x):
|
192 |
+
if self.gamma_1 is None:
|
193 |
+
x = x + self.attn(self.norm1(x))
|
194 |
+
x = x + self.mlp(self.norm2(x))
|
195 |
+
else:
|
196 |
+
x = x + (self.gamma_1 * self.attn(self.norm1(x)))
|
197 |
+
x = x + (self.gamma_2 * self.mlp(self.norm2(x)))
|
198 |
+
return x
|
199 |
+
|
200 |
+
|
201 |
+
def no_grad_trunc_normal_(tensor, mean, std, a, b):
|
202 |
+
# Cut & paste from PyTorch official master until it's in a few official releases - RW
|
203 |
+
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
|
204 |
+
def norm_cdf(x):
|
205 |
+
# Computes standard normal cumulative distribution function
|
206 |
+
return (1. + math.erf(x / math.sqrt(2.))) / 2.
|
207 |
+
|
208 |
+
if (mean < a - 2 * std) or (mean > b + 2 * std):
|
209 |
+
warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
|
210 |
+
"The distribution of values may be incorrect.",
|
211 |
+
stacklevel=2)
|
212 |
+
|
213 |
+
with torch.no_grad():
|
214 |
+
# Values are generated by using a truncated uniform distribution and
|
215 |
+
# then using the inverse CDF for the normal distribution.
|
216 |
+
# Get upper and lower cdf values
|
217 |
+
l = norm_cdf((a - mean) / std)
|
218 |
+
u = norm_cdf((b - mean) / std)
|
219 |
+
|
220 |
+
# Uniformly fill tensor with values from [l, u], then translate to
|
221 |
+
# [2l-1, 2u-1].
|
222 |
+
tensor.uniform_(2 * l - 1, 2 * u - 1)
|
223 |
+
|
224 |
+
# Use inverse cdf transform for normal distribution to get truncated
|
225 |
+
# standard normal
|
226 |
+
tensor.erfinv_()
|
227 |
+
|
228 |
+
# Transform to proper mean, std
|
229 |
+
tensor.mul_(std * math.sqrt(2.))
|
230 |
+
tensor.add_(mean)
|
231 |
+
|
232 |
+
# Clamp to ensure it's in the proper range
|
233 |
+
tensor.clamp_(min=a, max=b)
|
234 |
+
return tensor
|
positional_embedding.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import Tensor, nn
|
3 |
+
|
4 |
+
from .modules import Shape
|
5 |
+
|
6 |
+
|
7 |
+
class PositionalEmbedding(nn.Module):
|
8 |
+
|
9 |
+
def __init__(self, input_shape: Shape, dropout_rate: float = 0.5, trainable: bool = True):
|
10 |
+
super().__init__()
|
11 |
+
self.input_shape = input_shape
|
12 |
+
self.emb = nn.Parameter(torch.zeros(1, *input_shape), requires_grad=trainable)
|
13 |
+
self.use_dropout = dropout_rate is not None and dropout_rate != 0.
|
14 |
+
if self.use_dropout:
|
15 |
+
self.dropout = nn.Dropout(dropout_rate)
|
16 |
+
|
17 |
+
def forward(self, x: Tensor) -> Tensor:
|
18 |
+
x = x + self.emb
|
19 |
+
if self.use_dropout:
|
20 |
+
x = self.dropout(x)
|
21 |
+
return x
|
22 |
+
|
23 |
+
@property
|
24 |
+
def trainable(self):
|
25 |
+
return self.emb.requires_grad
|
26 |
+
|
27 |
+
@trainable.setter
|
28 |
+
def trainable(self, value: bool):
|
29 |
+
self.emb.requires_grad = value
|
30 |
+
|
31 |
+
|
32 |
+
class SinCosPositionalEmbedding(PositionalEmbedding):
|
33 |
+
|
34 |
+
def __init__(self, input_shape: Shape, dropout_rate: float = 0.5):
|
35 |
+
super().__init__(input_shape, dropout_rate, trainable=False)
|
36 |
+
self.emb.data = self.make_embedding().unsqueeze(0)
|
37 |
+
|
38 |
+
def make_embedding(self) -> Tensor:
|
39 |
+
n_position, d_hid = self.input_shape
|
40 |
+
|
41 |
+
def get_position_angle_vec(position):
|
42 |
+
return position / torch.tensor(10000).pow(
|
43 |
+
2 * torch.div(torch.arange(d_hid), 2, rounding_mode='trunc') / d_hid)
|
44 |
+
|
45 |
+
sinusoid_table = torch.stack([get_position_angle_vec(pos_i) for pos_i in range(n_position)], 0)
|
46 |
+
sinusoid_table[:, 0::2] = torch.sin(sinusoid_table[:, 0::2]) # dim 2i
|
47 |
+
sinusoid_table[:, 1::2] = torch.cos(sinusoid_table[:, 1::2]) # dim 2i+1
|
48 |
+
|
49 |
+
return sinusoid_table.float()
|