Spaces:
Runtime error
Runtime error
File size: 7,372 Bytes
231edce |
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 |
import numpy as np
import torch
import torch.nn as nn
from transformers.models.distilbert.modeling_distilbert import Transformer as T
from .pooling import create_pool1d_layer
class Config:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class Transformer(nn.Module):
"""
If predict_sequence is True, then the model will predict an output
for each element in the sequence. If False, then the model will
predict a single output for the sequence.
e.g., classifying each image in a CT scan vs the entire CT scan
"""
def __init__(self,
num_classes,
embedding_dim=512,
hidden_dim=1024,
n_layers=4,
n_heads=16,
dropout=0.2,
attention_dropout=0.1,
output_attentions=False,
activation='gelu',
output_hidden_states=False,
chunk_size_feed_forward=0,
predict_sequence=True,
pool=None
):
super().__init__()
config = Config(**{
'dim': embedding_dim,
'hidden_dim': hidden_dim,
'n_layers': n_layers,
'n_heads': n_heads,
'dropout': dropout,
'attention_dropout': attention_dropout,
'output_attentions': output_attentions,
'activation': activation,
'output_hidden_states': output_hidden_states,
'chunk_size_feed_forward': chunk_size_feed_forward
})
self.transformer = T(config)
self.predict_sequence = predict_sequence
if not predict_sequence:
if isinstance(pool, str):
self.pool_layer = create_pool1d_layer(pool)
if pool == "catavgmax":
embedding_dim *= 2
else:
self.pool_layer = nn.Identity()
self.classifier = nn.Linear(embedding_dim, num_classes)
def extract_features(self, x):
x, mask = x
x = self.transformer(x, attn_mask=mask, head_mask=[None]*x.size(1))
x = x[0]
if not self.predict_sequence:
if isinstance(self.pool_layer, nn.Identity):
# Just take the last vector in the sequence
x = x[:, 0]
else:
x = self.pool_layer(x.transpose(-1, -2))
return x
def classify(self, x):
if not self.predict_sequence:
if isinstance(self.pool_layer, nn.Identity):
# Just take the last vector in the sequence
x = x[:, 0]
else:
x = self.pool_layer(x.transpose(-1, -2))
out = self.classifier(x)
if self.classifier.out_features == 1:
return out[..., 0]
else:
return out
def forward_tr(self, x, mask):
output = self.transformer(x, attn_mask=mask, head_mask=[None]*x.size(1))
return self.classify(output[0])
def forward(self, x):
x, mask = x
return self.forward_tr(x, mask)
class DualTransformer(nn.Module):
"""
Essentially the same as above except predicts both sequence and study labels.
"""
def __init__(self,
num_classes,
embedding_dim=512,
hidden_dim=1024,
n_layers=4,
n_heads=16,
dropout=0.2,
attention_dropout=0.1,
output_attentions=False,
activation='gelu',
output_hidden_states=False,
chunk_size_feed_forward=0,
pool=None
):
super().__init__()
config = Config(**{
'dim': embedding_dim,
'hidden_dim': hidden_dim,
'n_layers': n_layers,
'n_heads': n_heads,
'dropout': dropout,
'attention_dropout': attention_dropout,
'output_attentions': output_attentions,
'activation': activation,
'output_hidden_states': output_hidden_states,
'chunk_size_feed_forward': chunk_size_feed_forward
})
self.transformer = T(config)
self.pool_layer = nn.Identity()
self.classifier1 = nn.Linear(embedding_dim, num_classes)
self.classifier2 = nn.Linear(embedding_dim, num_classes)
def classify(self, x):
if isinstance(self.pool_layer, nn.Identity):
# Just take the last vector in the sequence
x_summ = x[:, 0]
else:
x_summ = self.pool_layer(x.transpose(-1, -2))
# Element-wise labels
out1 = self.classifier1(x)[:, :, 0]
# Single label for whole sequence
out2 = self.classifier2(x_summ)
out = torch.cat([out1, out2], dim=1)
return out
def forward_tr(self, x, mask):
output = self.transformer(x, attn_mask=mask, head_mask=[None]*x.size(1))
return self.classify(output[0])
def forward(self, x):
x, mask = x
return self.forward_tr(x, mask)
class DualTransformerV2(nn.Module):
"""
More complicated variant of DualTransformer.
Returns tuple of: (element-wise prediction, sequence prediction)
"""
def __init__(self,
num_seq_classes,
num_classes,
embedding_dim=512,
hidden_dim=1024,
n_layers=4,
n_heads=16,
dropout=0.2,
attention_dropout=0.1,
output_attentions=False,
activation='gelu',
output_hidden_states=False,
chunk_size_feed_forward=0,
pool=None
):
super().__init__()
config = Config(**{
'dim': embedding_dim,
'hidden_dim': hidden_dim,
'n_layers': n_layers,
'n_heads': n_heads,
'dropout': dropout,
'attention_dropout': attention_dropout,
'output_attentions': output_attentions,
'activation': activation,
'output_hidden_states': output_hidden_states,
'chunk_size_feed_forward': chunk_size_feed_forward
})
self.transformer = T(config)
self.pool_layer = nn.Identity()
self.classifier1 = nn.Linear(embedding_dim, num_seq_classes)
self.classifier2 = nn.Linear(embedding_dim, num_classes)
def classify(self, x):
if isinstance(self.pool_layer, nn.Identity):
# Just take the last vector in the sequence
x_summ = x[:, 0]
else:
x_summ = self.pool_layer(x.transpose(-1, -2))
# Element-wise labels
out1 = self.classifier1(x)
if self.classifier1.out_features == 1:
out1 = out1[:, :, 0]
# Single label for whole sequence
out2 = self.classifier2(x_summ)
return out1, out2
def forward_tr(self, x, mask):
output = self.transformer(x, attn_mask=mask, head_mask=[None]*x.size(1))
return self.classify(output[0])
def forward(self, x):
x, mask = x
return self.forward_tr(x, mask)
|