calbors commited on
Commit
679a6b4
·
verified ·
1 Parent(s): bbd0791

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +18 -0
  3. configuration_revar.py +13 -0
  4. model.safetensors +3 -0
  5. modeling_revar.py +267 -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,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ReVarModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_revar.ReVarConfig",
7
+ "AutoModel": "modeling_revar.ReVarModel"
8
+ },
9
+ "inner_dim": 480,
10
+ "kernel_size": 5,
11
+ "model_type": "revar",
12
+ "num_output_channels": 5,
13
+ "num_stacks": 20,
14
+ "outer_dim": 960,
15
+ "stack_size": 2,
16
+ "torch_dtype": "float32",
17
+ "transformers_version": "4.43.3"
18
+ }
configuration_revar.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ class ReVarConfig(PretrainedConfig):
4
+ model_type = "revar"
5
+
6
+ def __init__(self, outer_dim: int = 960, inner_dim: int = 480, kernel_size: int = 5, stack_size: int = 2, num_stacks: int = 20, num_output_channels: int = 5, **kwargs):
7
+ self.outer_dim = outer_dim
8
+ self.inner_dim = inner_dim
9
+ self.kernel_size = kernel_size
10
+ self.stack_size = stack_size
11
+ self.num_stacks = num_stacks
12
+ self.num_output_channels= num_output_channels
13
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76ec9fb675327b7d1069eb69efb02800d53c51c6cdee67a72cc48e64ff2a39ce
3
+ size 332860784
modeling_revar.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional
2
+ from itertools import product
3
+ from collections import defaultdict
4
+ import torch
5
+ from torch import nn
6
+
7
+ import torch.nn.utils.parametrize as parametrize
8
+
9
+
10
+ def check_if_involution(indices: List[int]) -> bool:
11
+ return all(indices[indices[idx]] == idx for idx in range(len(indices)))
12
+
13
+
14
+ def get_conv1d_output_length(
15
+ input_length: int, kernel_size: int, stride_size: int = 1, pad_size: int = 0, dilation_rate: int = 1
16
+ ) -> int:
17
+ return (input_length + 2 * pad_size - dilation_rate * (kernel_size - 1) - 1) // stride_size + 1
18
+
19
+
20
+ def get_involution_indices(size: int) -> List[int]:
21
+ return list(reversed(range(size)))
22
+
23
+
24
+ class RCEWeight(nn.Module):
25
+ def __init__(
26
+ self, input_involution_indices: List[int], output_involution_indices: List[int]
27
+ ):
28
+ if not check_if_involution(input_involution_indices) or not check_if_involution(
29
+ output_involution_indices):
30
+ raise ValueError(
31
+ "`input_involution_indices` and `output_involution_indices` must be involutions"
32
+ )
33
+
34
+ super().__init__()
35
+ self._input_involution_indices = input_involution_indices
36
+ self._output_involution_indices = output_involution_indices
37
+ self._input_involution_index_tensor = None
38
+ self._output_involution_index_tensor = None
39
+ self._device = None
40
+
41
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
42
+ if self._device != x.device:
43
+ self._input_involution_index_tensor = torch.tensor(self._input_involution_indices, device=x.device)
44
+ self._output_involution_index_tensor = torch.tensor(self._output_involution_indices, device=x.device)
45
+ self._device = x.device
46
+
47
+ output_involution_indices = self._output_involution_index_tensor
48
+ input_involution_indices = self._input_involution_index_tensor
49
+ return (x + x[output_involution_indices][:, input_involution_indices].flip(2)) / 2
50
+
51
+
52
+ class IEBias(nn.Module):
53
+ def __init__(self, involution_indices: List[int]):
54
+ if not check_if_involution(involution_indices):
55
+ raise ValueError("`involution_indices` must be an involution")
56
+
57
+ super().__init__()
58
+ self._involution_indices = involution_indices
59
+ self._involution_index_tensor = None
60
+ self._device = None
61
+
62
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
63
+ if self._device != x.device:
64
+ self._involution_index_tensor = torch.tensor(self._involution_indices, device=x.device)
65
+ self._device = x.device
66
+
67
+ involution_indices = self._involution_index_tensor
68
+ return (x + x[involution_indices]) / 2
69
+
70
+
71
+ class IEWeight(nn.Module):
72
+ def __init__(
73
+ self, input_involution_indices: List[int], output_involution_indices: List[int]
74
+ ):
75
+ if not check_if_involution(input_involution_indices) or not check_if_involution(
76
+ output_involution_indices):
77
+ raise ValueError(
78
+ "`input_involution_indices` and `output_involution_indices` must be involutions"
79
+ )
80
+
81
+ super().__init__()
82
+ self._input_involution_indices = input_involution_indices
83
+ self._output_involution_indices = output_involution_indices
84
+ self._input_involution_index_tensor = None
85
+ self._output_involution_index_tensor = None
86
+ self._device = None
87
+
88
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
89
+ if self._device != x.device:
90
+ self._input_involution_index_tensor = torch.tensor(self._input_involution_indices, device=x.device)
91
+ self._output_involution_index_tensor = torch.tensor(self._output_involution_indices, device=x.device)
92
+ self._device = x.device
93
+
94
+ output_involution_indices = self._output_involution_index_tensor
95
+ input_involution_indices = self._input_involution_index_tensor
96
+ return (x + x[input_involution_indices][:, output_involution_indices]) / 2
97
+
98
+
99
+ class RCEByteNetBlock(nn.Module):
100
+ def __init__(self, outer_involution_indices: List[int], inner_dim: int, kernel_size: int, dilation_rate: int = 1):
101
+ outer_dim = len(outer_involution_indices)
102
+
103
+ if outer_dim % 2 != 0:
104
+ raise ValueError("`outer_involution_indices` must have an even length")
105
+
106
+ if inner_dim % 2 != 0:
107
+ raise ValueError("`inner_dim` must be even")
108
+
109
+ if kernel_size % 2 == 0:
110
+ raise ValueError("`kernel_size` must be odd")
111
+
112
+ super().__init__()
113
+ inner_involution_indices = get_involution_indices(inner_dim)
114
+
115
+ layers = [
116
+ nn.GroupNorm(1, outer_dim),
117
+ nn.GELU(),
118
+ nn.Conv1d(outer_dim, inner_dim, kernel_size=1),
119
+ nn.GroupNorm(1, inner_dim),
120
+ nn.GELU(),
121
+ nn.Conv1d(inner_dim, inner_dim, kernel_size, dilation=dilation_rate),
122
+ nn.GroupNorm(1, inner_dim),
123
+ nn.GELU(),
124
+ nn.Conv1d(inner_dim, outer_dim, kernel_size=1)
125
+ ]
126
+ parametrize.register_parametrization(
127
+ layers[2], "weight",
128
+ RCEWeight(outer_involution_indices, inner_involution_indices)
129
+ )
130
+ parametrize.register_parametrization(
131
+ layers[2], "bias",
132
+ IEBias(inner_involution_indices)
133
+ )
134
+ parametrize.register_parametrization(
135
+ layers[5], "weight",
136
+ RCEWeight(inner_involution_indices, inner_involution_indices)
137
+ )
138
+ parametrize.register_parametrization(
139
+ layers[5], "bias",
140
+ IEBias(inner_involution_indices)
141
+ )
142
+ parametrize.register_parametrization(
143
+ layers[8], "weight",
144
+ RCEWeight(inner_involution_indices, outer_involution_indices)
145
+ )
146
+ parametrize.register_parametrization(
147
+ layers[8], "bias",
148
+ IEBias(outer_involution_indices)
149
+ )
150
+ self.layers = nn.Sequential(*layers)
151
+ self._kernel_size = kernel_size
152
+ self._dilation_rate = dilation_rate
153
+
154
+ @property
155
+ def kernel_size(self):
156
+ return self._kernel_size
157
+
158
+ @property
159
+ def dilation_rate(self):
160
+ return self._dilation_rate
161
+
162
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
163
+ input_length = x.shape[2]
164
+ output_length = get_conv1d_output_length(input_length, self.kernel_size, dilation_rate=self.dilation_rate)
165
+ a = (input_length - output_length) // 2
166
+
167
+ if a == 0:
168
+ return self.layers(x) + x
169
+
170
+ return self.layers(x) + x[:, :, a:-a]
171
+
172
+
173
+ class RCEByteNet(nn.Module):
174
+ def __init__(
175
+ self,
176
+ input_involution_indices: List[int],
177
+ output_involution_indices: List[int],
178
+ dilation_rates: List[int],
179
+ outer_dim: int,
180
+ inner_dim: int,
181
+ kernel_size: int,
182
+ num_output_channels: int = 1,
183
+ pad_token_idx: Optional[int] = None
184
+ ):
185
+ if pad_token_idx is not None and input_involution_indices[pad_token_idx] != pad_token_idx:
186
+ raise ValueError("`input_involution_indices[pad_token_idx]` must be equal to `pad_token_idx`")
187
+
188
+ super().__init__()
189
+ vocab_size = len(input_involution_indices)
190
+ outer_involution_indices = get_involution_indices(outer_dim)
191
+
192
+ self.embedding = nn.Embedding(vocab_size, outer_dim, padding_idx=pad_token_idx)
193
+ parametrize.register_parametrization(
194
+ self.embedding, "weight",
195
+ IEWeight(input_involution_indices, outer_involution_indices)
196
+ )
197
+ nn.init.normal_(self.embedding.weight, std=2**0.5)
198
+ self.embedding.weight.data[self.embedding.padding_idx].zero_()
199
+ self.embedding.requires_grad = False
200
+
201
+ blocks = []
202
+ receptive_field_size = 1
203
+
204
+ for r in dilation_rates:
205
+ blocks.append(RCEByteNetBlock(outer_involution_indices, inner_dim, kernel_size, dilation_rate=r))
206
+ receptive_field_size += (kernel_size - 1) * r
207
+
208
+ self.blocks = nn.Sequential(*blocks)
209
+
210
+ self._num_output_channels = num_output_channels
211
+ output_dim = len(output_involution_indices)
212
+ output_involution_indices = [
213
+ i * len(output_involution_indices) + j
214
+ for i, j in product(range(num_output_channels), output_involution_indices)
215
+ ]
216
+
217
+ self.output_layers = nn.Sequential(
218
+ nn.GroupNorm(1, outer_dim), nn.GELU(),
219
+ nn.Conv1d(outer_dim, output_dim * num_output_channels, kernel_size=1)
220
+ )
221
+ parametrize.register_parametrization(
222
+ self.output_layers[-1], "weight", RCEWeight(outer_involution_indices, output_involution_indices)
223
+ )
224
+ parametrize.register_parametrization(self.output_layers[-1], "bias", IEBias(output_involution_indices))
225
+
226
+ def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
227
+ x = self.blocks(self.embedding(input_tensor).swapaxes(1, 2))
228
+ output_tensor = self.output_layers(x).swapaxes(1, 2)
229
+ output_dim = output_tensor.shape[2] // self._num_output_channels
230
+ shape = list(output_tensor.shape[:-1]) + [self._num_output_channels, output_dim]
231
+ return output_tensor.reshape(shape)
232
+
233
+ from transformers import PreTrainedModel
234
+ from .configuration_revar import ReVarConfig
235
+
236
+ class ReVarModel(PreTrainedModel):
237
+ config_class = ReVarConfig
238
+
239
+ def __init__(self, config, **kwargs):
240
+ super().__init__(config, **kwargs)
241
+
242
+ dilation_rates = config.num_stacks * [config.kernel_size**i for i in range(0, config.stack_size)]
243
+
244
+ self._model = RCEByteNet(
245
+ input_involution_indices = [3, 2, 1, 0, 4, 5],
246
+ output_involution_indices=[3, 2, 1, 0],
247
+ dilation_rates=dilation_rates,
248
+ outer_dim = config.outer_dim,
249
+ inner_dim = config.inner_dim,
250
+ kernel_size=config.kernel_size,
251
+ num_output_channels=config.num_output_channels,
252
+ pad_token_idx=5
253
+ )
254
+
255
+ def get_embeddings(self, input_ids: torch.Tensor):
256
+ return self._model.get_embeddings(input_ids)
257
+
258
+ def forward(self, input_ids: torch.Tensor):
259
+ output_tensor = self._model(input_ids)
260
+
261
+ results = defaultdict(dict)
262
+
263
+ for i, cell_type in enumerate(["A549", "HepG2", "K562", "SK-N-SH", "HCT116"]):
264
+ for j, allele in enumerate("ACGT"):
265
+ results[cell_type][allele] = output_tensor[:, :, i, j]
266
+
267
+ return results