ammarnasr commited on
Commit
a2364f4
1 Parent(s): 3bcfd32

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +18 -0
  3. configuration_medts.py +23 -0
  4. model.safetensors +3 -0
  5. modeling_medts.py +150 -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
+ "MedTSModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_medts.MedTSConfig",
7
+ "AutoModel": "modeling_medts.MedTSModel"
8
+ },
9
+ "block_size": 32,
10
+ "dropout": 0.1,
11
+ "model_type": "MedTS",
12
+ "n_embd": 512,
13
+ "n_head": 2,
14
+ "n_layer": 2,
15
+ "torch_dtype": "float32",
16
+ "transformers_version": "4.41.1",
17
+ "vocab_size": 4
18
+ }
configuration_medts.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class MedTSConfig(PretrainedConfig):
5
+ model_type = "MedTS"
6
+
7
+ def __init__(
8
+ self,
9
+ vocab_size = 4,
10
+ n_embd = 128,
11
+ block_size=32,
12
+ n_layer=2,
13
+ n_head=2,
14
+ dropout=0.1,
15
+ **kwargs,
16
+ ):
17
+ self.vocab_size = vocab_size
18
+ self.n_embd = n_embd
19
+ self.block_size = block_size
20
+ self.n_layer = n_layer
21
+ self.n_head = n_head
22
+ self.dropout = dropout
23
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef3fe4e70562e0b33085b10f917213dbf96230cd6f5ddb55d17da512c2e3b76a
3
+ size 25250512
modeling_medts.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+ from .configuration_medts import MedTSConfig
6
+
7
+
8
+ class FeedFoward(nn.Module):
9
+ """ a simple linear layer followed by a non-linearity """
10
+ def __init__(self, n_embd, dropout):
11
+ super().__init__()
12
+ self.net = nn.Sequential(
13
+ nn.Linear(n_embd, 4 * n_embd),
14
+ nn.ReLU(),
15
+ nn.Linear(4 * n_embd, n_embd),
16
+ nn.Dropout(dropout),
17
+ )
18
+
19
+ def forward(self, x):
20
+ return self.net(x)
21
+
22
+
23
+ class Head(nn.Module):
24
+ """ one head of self-attention """
25
+ def __init__(self, head_size, n_embd, block_size):
26
+ super().__init__()
27
+ self.key = nn.Linear(n_embd, head_size, bias=False)
28
+ self.query = nn.Linear(n_embd, head_size, bias=False)
29
+ self.value = nn.Linear(n_embd, head_size, bias=False)
30
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
31
+ def forward(self, x):
32
+ # input of size (batch, time-step, channels)
33
+ # output of size (batch, time-step, head size)
34
+ B,T,C = x.shape
35
+ k = self.key(x) # (B,T,hs)
36
+ q = self.query(x) # (B,T,hs)
37
+ # compute attention scores ("affinities")
38
+ wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
39
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
40
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
41
+ # perform the weighted aggregation of the values
42
+ v = self.value(x) # (B,T,hs)
43
+ out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
44
+ return out
45
+
46
+ class MultiHeadAttention(nn.Module):
47
+ """ multiple heads of self-attention in parallel """
48
+ def __init__(self, num_heads, head_size, n_embd, dropout, block_size):
49
+ super().__init__()
50
+ self.heads = nn.ModuleList([Head(head_size, n_embd, block_size) for _ in range(num_heads)])
51
+ self.proj = nn.Linear(head_size * num_heads, n_embd)
52
+ self.dropout = nn.Dropout(dropout)
53
+ def forward(self, x):
54
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
55
+ out = self.dropout(self.proj(out))
56
+ return out
57
+
58
+ class Block(nn.Module):
59
+ """ Transformer block: communication followed by computation """
60
+ def __init__(self, n_embd, n_head, dropout, block_size):
61
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
62
+ super().__init__()
63
+ head_size = n_embd // n_head
64
+ self.sa = MultiHeadAttention(n_head, head_size, n_embd, dropout, block_size)
65
+ self.ffwd = FeedFoward(n_embd, dropout)
66
+ self.ln1 = nn.LayerNorm(n_embd)
67
+ self.ln2 = nn.LayerNorm(n_embd)
68
+
69
+ def forward(self, x):
70
+ x = x + self.sa(self.ln1(x))
71
+ x = x + self.ffwd(self.ln2(x))
72
+ return x
73
+
74
+
75
+ class PatientsTimeSeriesModel(nn.Module):
76
+ def __init__(self, vocab_size, n_embd, block_size, device, n_layer, n_head, dropout):
77
+ '''
78
+ args:
79
+ - vocab_size: int, the number of unique tokens in the vocabulary, i.e. the number of unique tests results
80
+ - n_embd: int, the dimension of the embedding, i.e. the number of tests results (same as vocab_size)
81
+ - block_size: int, the length of the context
82
+ '''
83
+ super().__init__()
84
+ # each token directly reads off the logits for the next token from a lookup table
85
+ self.position_embedding_table = nn.Embedding(block_size, vocab_size)
86
+ # self.sa =Head(n_embd, n_embd, block_size)
87
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head, dropout, block_size) for _ in range(n_layer)])
88
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
89
+
90
+ self.lm_prefix = nn.Linear(vocab_size, n_embd) # linear layer to project the tokens to the embedding dimension
91
+ self.lm_head = nn.Linear(n_embd, vocab_size) # linear layer to project the embeddings to the vocabulary size
92
+ self.device = device
93
+ self.apply(self._init_weights)
94
+
95
+ def _init_weights(self, module):
96
+ if isinstance(module, nn.Linear):
97
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
98
+ if module.bias is not None:
99
+ torch.nn.init.zeros_(module.bias)
100
+ elif isinstance(module, nn.Embedding):
101
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
102
+
103
+ def forward(self, tok_emb, targets=None):
104
+ # tok_emb and targets are both (B,T,C) tensors
105
+ # where B is the batch size, T is the number of time steps and C is the number of tests results
106
+ B, T, C = tok_emb.shape
107
+ pos_emb = self.position_embedding_table(torch.arange(T, device=self.device)) # (T,Vocab_size)
108
+ x = tok_emb + pos_emb # (B,T,Vocab_size)
109
+ x = self.lm_prefix(x) # (B,T,C)
110
+ x = self.blocks(x) # (B,T,C)
111
+ x = self.ln_f(x) # (B,T,C)
112
+ logits = self.lm_head(x) # (B,T,vocab_size)
113
+ if targets is None:
114
+ return {"logits": logits}
115
+ else:
116
+ B, T, C = logits.shape
117
+ logits = logits.view(B*T, C)
118
+ targets = targets.view(B*T, C)
119
+ # TODO: Add padding mask to the loss computation
120
+ # loss = F.mse_loss(logits, targets)
121
+ loss = self.mse_loss(logits, targets, reduction="mean")
122
+ return {"logits": logits, "loss": loss}
123
+
124
+ def mse_loss(self, out, target, reduction):
125
+ mask = (target == 0)
126
+ loss = (out[~mask]-target[~mask])**2
127
+ if reduction == "mean":
128
+ return loss.mean()
129
+ elif reduction == "None":
130
+ return loss
131
+
132
+
133
+ class MedTSModel(PreTrainedModel):
134
+ config_class = MedTSConfig
135
+
136
+ def __init__(self, config):
137
+ super().__init__(config)
138
+
139
+ self.model = PatientsTimeSeriesModel(
140
+ vocab_size=config.vocab_size,
141
+ n_embd=config.n_embd,
142
+ block_size=config.block_size,
143
+ device= 'mps' if torch.backends.mps.is_available() else 'cuda' if torch.cuda.is_available() else 'cpu',
144
+ n_layer=config.n_layer,
145
+ n_head=config.n_head,
146
+ dropout=config.dropout
147
+ )
148
+
149
+ def forward(self, tensor, targets=None):
150
+ return self.model(tensor, targets)