|
from transformers import PreTrainedModel |
|
import torch |
|
import torch.nn as nn |
|
from torch.nn import functional as F |
|
from .configuration_medts import MedTSConfig |
|
|
|
|
|
class FeedFoward(nn.Module): |
|
""" a simple linear layer followed by a non-linearity """ |
|
def __init__(self, n_embd, dropout): |
|
super().__init__() |
|
self.net = nn.Sequential( |
|
nn.Linear(n_embd, 4 * n_embd), |
|
nn.ReLU(), |
|
nn.Linear(4 * n_embd, n_embd), |
|
nn.Dropout(dropout), |
|
) |
|
|
|
def forward(self, x): |
|
return self.net(x) |
|
|
|
|
|
class Head(nn.Module): |
|
""" one head of self-attention """ |
|
def __init__(self, head_size, n_embd, block_size): |
|
super().__init__() |
|
self.key = nn.Linear(n_embd, head_size, bias=False) |
|
self.query = nn.Linear(n_embd, head_size, bias=False) |
|
self.value = nn.Linear(n_embd, head_size, bias=False) |
|
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size))) |
|
def forward(self, x): |
|
|
|
|
|
B,T,C = x.shape |
|
k = self.key(x) |
|
q = self.query(x) |
|
|
|
wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 |
|
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) |
|
wei = F.softmax(wei, dim=-1) |
|
|
|
v = self.value(x) |
|
out = wei @ v |
|
return out |
|
|
|
class MultiHeadAttention(nn.Module): |
|
""" multiple heads of self-attention in parallel """ |
|
def __init__(self, num_heads, head_size, n_embd, dropout, block_size): |
|
super().__init__() |
|
self.heads = nn.ModuleList([Head(head_size, n_embd, block_size) for _ in range(num_heads)]) |
|
self.proj = nn.Linear(head_size * num_heads, n_embd) |
|
self.dropout = nn.Dropout(dropout) |
|
def forward(self, x): |
|
out = torch.cat([h(x) for h in self.heads], dim=-1) |
|
out = self.dropout(self.proj(out)) |
|
return out |
|
|
|
class Block(nn.Module): |
|
""" Transformer block: communication followed by computation """ |
|
def __init__(self, n_embd, n_head, dropout, block_size): |
|
|
|
super().__init__() |
|
head_size = n_embd // n_head |
|
self.sa = MultiHeadAttention(n_head, head_size, n_embd, dropout, block_size) |
|
self.ffwd = FeedFoward(n_embd, dropout) |
|
self.ln1 = nn.LayerNorm(n_embd) |
|
self.ln2 = nn.LayerNorm(n_embd) |
|
|
|
def forward(self, x): |
|
x = x + self.sa(self.ln1(x)) |
|
x = x + self.ffwd(self.ln2(x)) |
|
return x |
|
|
|
|
|
class PatientsTimeSeriesModel(nn.Module): |
|
def __init__(self, vocab_size, n_embd, block_size, device, n_layer, n_head, dropout): |
|
''' |
|
args: |
|
- vocab_size: int, the number of unique tokens in the vocabulary, i.e. the number of unique tests results |
|
- n_embd: int, the dimension of the embedding, i.e. the number of tests results (same as vocab_size) |
|
- block_size: int, the length of the context |
|
''' |
|
super().__init__() |
|
|
|
self.position_embedding_table = nn.Embedding(block_size, vocab_size) |
|
|
|
self.blocks = nn.Sequential(*[Block(n_embd, n_head, dropout, block_size) for _ in range(n_layer)]) |
|
self.ln_f = nn.LayerNorm(n_embd) |
|
|
|
self.lm_prefix = nn.Linear(vocab_size, n_embd) |
|
self.lm_head = nn.Linear(n_embd, vocab_size) |
|
self.device = device |
|
self.apply(self._init_weights) |
|
|
|
def _init_weights(self, module): |
|
if isinstance(module, nn.Linear): |
|
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) |
|
if module.bias is not None: |
|
torch.nn.init.zeros_(module.bias) |
|
elif isinstance(module, nn.Embedding): |
|
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) |
|
|
|
def forward(self, tok_emb, targets=None): |
|
|
|
|
|
B, T, C = tok_emb.shape |
|
pos_emb = self.position_embedding_table(torch.arange(T, device=self.device)) |
|
x = tok_emb + pos_emb |
|
x = self.lm_prefix(x) |
|
x = self.blocks(x) |
|
x = self.ln_f(x) |
|
logits = self.lm_head(x) |
|
if targets is None: |
|
return {"logits": logits} |
|
else: |
|
B, T, C = logits.shape |
|
logits = logits.view(B*T, C) |
|
targets = targets.view(B*T, C) |
|
|
|
|
|
loss = self.mse_loss(logits, targets, reduction="mean") |
|
return {"logits": logits, "loss": loss} |
|
|
|
def mse_loss(self, out, target, reduction): |
|
mask = (target == 0) |
|
loss = (out[~mask]-target[~mask])**2 |
|
if reduction == "mean": |
|
return loss.mean() |
|
elif reduction == "None": |
|
return loss |
|
|
|
|
|
class MedTSModel(PreTrainedModel): |
|
config_class = MedTSConfig |
|
|
|
def __init__(self, config): |
|
super().__init__(config) |
|
|
|
self.model = PatientsTimeSeriesModel( |
|
vocab_size=config.vocab_size, |
|
n_embd=config.n_embd, |
|
block_size=config.block_size, |
|
device= 'mps' if torch.backends.mps.is_available() else 'cuda' if torch.cuda.is_available() else 'cpu', |
|
n_layer=config.n_layer, |
|
n_head=config.n_head, |
|
dropout=config.dropout |
|
) |
|
|
|
def forward(self, tensor, targets=None): |
|
return self.model(tensor, targets) |