SE6446 commited on
Commit
d39a8f8
·
verified ·
1 Parent(s): bd6352f

Upload model

Browse files
Files changed (5) hide show
  1. README.md +201 -0
  2. config.json +20 -0
  3. configuration_vitmix.py +30 -0
  4. model.safetensors +3 -0
  5. modeling_vitmix.py +196 -0
README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
200
+
201
+
config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ViTMixModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_vitmix.ViTMixConfig",
7
+ "AutoModelForImageClassification": "modeling_vitmix.ViTMixModel"
8
+ },
9
+ "depth": 6,
10
+ "dim": 1024,
11
+ "heads": 16,
12
+ "image_size": 28,
13
+ "mlp_dim": 2048,
14
+ "model_type": "VitMix",
15
+ "num_classes": 10,
16
+ "num_experts": 12,
17
+ "patch_size": 14,
18
+ "torch_dtype": "float32",
19
+ "transformers_version": "4.38.0.dev0"
20
+ }
configuration_vitmix.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from typing import List
3
+
4
+
5
+ class ViTMixConfig(PretrainedConfig): #Note you cannot change the expert layers for now...
6
+ model_type = "VitMix"
7
+
8
+ def __init__(
9
+ self,
10
+ image_size = 28,
11
+ patch_size = 14,
12
+ num_classes = 10,
13
+ dim = 1024,
14
+ depth = 6,
15
+ heads = 16,
16
+ mlp_dim = 2048,
17
+ num_experts = 12
18
+ ):
19
+ if image_size % patch_size != 0:
20
+ print(f"image size must be half patch size! img_size: {image_size} | patch_size{patch_size}")
21
+
22
+ self.image_size = image_size
23
+ self.patch_size = patch_size
24
+ self.num_classes = num_classes
25
+ self.dim = dim
26
+ self.depth = depth
27
+ self.heads = heads
28
+ self.mlp_dim = mlp_dim
29
+ self.num_experts = num_experts
30
+ super().__init__()
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22244f61f64607469cd39413009ddd06c2ddb395b1dd898bb4719a940ac24fc1
3
+ size 1564290824
modeling_vitmix.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel
2
+ from .configuration_vitmix import ViTMixConfig
3
+
4
+
5
+ # Model architecture gracefully stolen from lucidrains https://github.com/lucidrains/vit-pytorch/blob/main/vit_pytorch/simple_vit.py
6
+ import torch
7
+ from torch import nn
8
+
9
+ from einops import rearrange
10
+ from einops.layers.torch import Rearrange
11
+
12
+ from st_moe_pytorch import SparseMoEBlock, MoE
13
+ # I thin this is 'including a copy of this notice'... tell me if I'm wrong
14
+ ####################################
15
+ #MIT License
16
+
17
+ #Copyright (c) 2020 Phil Wang
18
+
19
+ #Permission is hereby granted, free of charge, to any person obtaining a copy
20
+ #of this software and associated documentation files (the "Software"), to deal
21
+ #in the Software without restriction, including without limitation the rights
22
+ #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23
+ #copies of the Software, and to permit persons to whom the Software is
24
+ #furnished to do so, subject to the following conditions:
25
+
26
+ #The above copyright notice and this permission notice shall be included in all
27
+ #copies or substantial portions of the Software.
28
+
29
+ #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
+ #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31
+ #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32
+ #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33
+ #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34
+ #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35
+ #SOFTWARE.
36
+ ##################################]
37
+ # helpers
38
+
39
+ def pair(t):
40
+ return t if isinstance(t, tuple) else (t, t)
41
+
42
+ def posemb_sincos_2d(h, w, dim, temperature: int = 10000, dtype = torch.float32):
43
+ y, x = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij")
44
+ assert (dim % 4) == 0, "feature dimension must be multiple of 4 for sincos emb"
45
+ omega = torch.arange(dim // 4) / (dim // 4 - 1)
46
+ omega = 1.0 / (temperature ** omega)
47
+
48
+ y = y.flatten()[:, None] * omega[None, :]
49
+ x = x.flatten()[:, None] * omega[None, :]
50
+ pe = torch.cat((x.sin(), x.cos(), y.sin(), y.cos()), dim=1)
51
+ return pe.type(dtype)
52
+
53
+ # classes
54
+
55
+ class FeedForward(nn.Module):
56
+ def __init__(self, dim, hidden_dim):
57
+ super().__init__()
58
+ self.net = nn.Sequential(
59
+ nn.LayerNorm(dim),
60
+ nn.Linear(dim, hidden_dim),
61
+ nn.GELU(),
62
+ nn.Linear(hidden_dim, dim),
63
+ )
64
+ def forward(self, x):
65
+ return self.net(x)
66
+
67
+ class Attention(nn.Module):
68
+ def __init__(self, dim, heads = 8, dim_head = 64):
69
+ super().__init__()
70
+ inner_dim = dim_head * heads
71
+ self.heads = heads
72
+ self.scale = dim_head ** -0.5
73
+ self.norm = nn.LayerNorm(dim)
74
+
75
+ self.attend = nn.Softmax(dim = -1)
76
+
77
+ self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
78
+ self.to_out = nn.Linear(inner_dim, dim, bias = False)
79
+
80
+ def forward(self, x):
81
+ x = self.norm(x)
82
+
83
+ qkv = self.to_qkv(x).chunk(3, dim = -1)
84
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
85
+
86
+ dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
87
+
88
+ attn = self.attend(dots)
89
+
90
+ out = torch.matmul(attn, v)
91
+ out = rearrange(out, 'b h n d -> b n (h d)')
92
+ return self.to_out(out)
93
+
94
+ class Transformer(nn.Module):
95
+ ### Here is my MOE modification
96
+ def __init__(self, dim, depth, heads, dim_head, mlp_dim, num_experts):
97
+ super().__init__()
98
+ self.norm = nn.LayerNorm(dim)
99
+ self.layers = nn.ModuleList([])
100
+ for _ in range(depth):
101
+ if _ % 2 == 0: #make every other FNN an expert layer.
102
+ self.layers.append(nn.ModuleList([
103
+ Attention(dim, heads = heads, dim_head = dim_head),
104
+ FeedForward(dim, mlp_dim)
105
+ ]))
106
+ else:
107
+ self.layers.append(nn.ModuleList([
108
+ Attention(dim, heads = heads, dim_head = dim_head),
109
+ SparseMoEBlock(
110
+ MoE(dim = dim,
111
+ num_experts = num_experts,
112
+ gating_top_n = 2,
113
+ threshold_train = 0.2,
114
+ threshold_eval = 0.2,
115
+ capacity_factor_train = 1.25,
116
+ capacity_factor_eval = 2.,
117
+ balance_loss_coef = 1e-2,
118
+ router_z_loss_coef = 1e-3,
119
+ ),
120
+ add_ff_before = True,
121
+ add_ff_after = True
122
+ )
123
+ ]))
124
+ def forward(self, x):
125
+ for attne, ff in self.layers:
126
+ x = attne(x) + x
127
+ try:
128
+ x = ff(x) + x
129
+ except:
130
+ x = ff(x)[0]+x # I won't bother returning aux_loss... probably a bad idea
131
+ return self.norm(x)
132
+
133
+ class SimpleViTMIX(nn.Module):
134
+ def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, channels = 3, dim_head = 64, num_experts = 12):
135
+ super().__init__()
136
+ image_height, image_width = pair(image_size)
137
+ patch_height, patch_width = pair(patch_size)
138
+
139
+ assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'
140
+
141
+ patch_dim = channels * patch_height * patch_width
142
+
143
+ self.to_patch_embedding = nn.Sequential(
144
+ Rearrange("b c (h p1) (w p2) -> b (h w) (p1 p2 c)", p1 = patch_height, p2 = patch_width),
145
+ nn.LayerNorm(patch_dim),
146
+ nn.Linear(patch_dim, dim),
147
+ nn.LayerNorm(dim),
148
+ )
149
+
150
+ self.pos_embedding = posemb_sincos_2d(
151
+ h = image_height // patch_height,
152
+ w = image_width // patch_width,
153
+ dim = dim,
154
+ )
155
+
156
+ self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, num_experts)
157
+
158
+ self.pool = "mean"
159
+ self.to_latent = nn.Identity()
160
+
161
+ self.linear_head = nn.Linear(dim, num_classes)
162
+
163
+ def forward(self, img):
164
+ device = img.device
165
+
166
+ x = self.to_patch_embedding(img)
167
+ x += self.pos_embedding.to(device, dtype=x.dtype)
168
+
169
+ x = self.transformer(x)
170
+ x = x.mean(dim = 1)
171
+
172
+ x = self.to_latent(x)
173
+ return self.linear_head(x)
174
+
175
+
176
+
177
+ class ViTMixModel(PreTrainedModel):
178
+ config_class = ViTMixConfig
179
+ def __init__(self, config):
180
+ super().__init__(config)
181
+ self.model = SimpleViTMIX(
182
+ image_size = config.image_size,
183
+ patch_size = config.patch_size,
184
+ num_classes = config.num_classes,
185
+ dim = config.dim,
186
+ depth = config.depth,
187
+ heads = config.heads,
188
+ mlp_dim = config.mlp_dim,
189
+ num_experts = config.num_experts
190
+ )
191
+ def forward(self,tensor):
192
+ logits = self.model(tensor)
193
+ if labels is not None:
194
+ loss = torch.nn.cross_entropy(logits, labels)
195
+ return {"loss": loss, "logits": logits}
196
+ return {"logits": logits}