Commit 86e9458c by Andrea Mancini

added model_comparison notebook and cpf

parent d04ed1b2
......@@ -20,7 +20,8 @@ Train 80%, Val 10 %, Test 10%
| | Sequences | Classes | Train Accuracy | Train F1 | Val Accuracy | Val F1 | Test Accuracy | Test F1 | Dom Start (± 3) | Dom End (± 3) |
|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
| TRX | 28601 | 8 | 0.985 ± 0.03 | 0.985 ± 0.03 | 0.912 ± 0.0 | 0.912 ± 0.0 | 0.905 ± 0.01 | 0.905 ± 0.01 | 0.823 | 0.819 |
| SH3 | 11148 | 7 | 0.869 ± 0.01 | 0.856 ± 0.01 | 0.867 ± 0.0 | 0.855 ± 0.0 | 0.825 ± 0.01 | 0.832 ± 0.01 | 0.978 | 0.980 |
| SH3 | 8088 | 7 | 0.999 ± 0.0 | 0.999 ± 0.0 | 0.902 ± 0.0 | 0.902± 0.0 | 0.887 ± 0.0 | 0.887 ± 0.0 | 0.969 ± 0.0 | 0.980 ± 0.0 |
| CPF | 14135 | 8 | 0.987 ± 0.0 | 0.987 ± 0.0 | 0.982 ± 0.0 | 0.982 ± 0.0 | 0.976 ± 0.0 | 0.976 ± 0.0 | 0.963 ± 0.0 | 0.909 ± 0.0 |
---
## 🛠️ Usage
......@@ -44,8 +45,9 @@ Get started with just a few steps:
| Model | # Classes | # tokens | # Epoch | #Val F1 score | # Checkpoint |
|:---:|:---:|:---:|:---:|:---:|:---:|
| TRX model | 8 | 1024 | 7 | 0.92 | [🔗 Download](https://zenodo.org/records/15005140/files/trx_8_classes.tar?download=1) |
| SH3 model | 7 | 1024 | 9 | 0.87 | [🔗 Download](https://zenodo.org/records/15005140/files/sh3_7_classes.tar?download=1) |
| TRX model | 8 | 1024 | 7 | 0.92 | [🔗 Download](https://zenodo.org/records/17351600/files/trx_8class_model.tar?download=1) |
| SH3 model | 7 | 1024 | 10 | 0.91 | [🔗 Download](https://zenodo.org/records/17351600/files/sh3_7class_model.tar?download=1) |
| CPF model | 8 | 1024 | 10 | 0.99 | [🔗 Download](https://zenodo.org/records/17351600/files/cpf_8class_model.tar?download=1) |
### 4️⃣ Create dataset from ProfileView tree
......
from collections import defaultdict
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from utils.data_utils import compute_dataset_info, make_plot_distribution, make_splits
from transformers import AutoTokenizer, T5Tokenizer
from transformers.models.auto.tokenization_auto import AutoTokenizer
from torch.utils.data import Dataset, DataLoader
from typing import Dict
......@@ -135,7 +134,7 @@ class EsmSpanDataset:
return class_weights
def get_data_loaders(self, model_version, batch_size=8, shuffle=True) -> Dict[str,DataLoader]:
def get_data_loaders(self, model_version, size=32, val_size=32, shuffle=True) -> Dict[str,DataLoader]:
tokenizer = AutoTokenizer.from_pretrained(model_version)
......@@ -143,12 +142,12 @@ class EsmSpanDataset:
train_ds = _MyDataset(self.train_df, tokenizer)
train_loader = DataLoader(
train_ds, batch_size=batch_size, shuffle=shuffle, pin_memory=True, num_workers=4
train_ds, batch_size=size, shuffle=shuffle, pin_memory=True, num_workers=4
)
val_ds = _MyDataset(self.val_df, tokenizer)
val_loader = DataLoader(
val_ds, batch_size=batch_size, shuffle=False, pin_memory=True, num_workers=4
val_ds, batch_size=val_size, shuffle=False, pin_memory=True, num_workers=4
)
return dict(train_loader=train_loader, val_loader=val_loader)
......@@ -157,7 +156,7 @@ class EsmSpanDataset:
ds = _MyDataset(self.dataframe, tokenizer)
loader = DataLoader(
ds, batch_size=batch_size, shuffle=shuffle, pin_memory=True, num_workers=4
ds, batch_size=size, shuffle=shuffle, pin_memory=True, num_workers=4
)
return dict(train_loader=loader)
......
This source diff could not be displayed because it is too large. You can view the blob instead.
images/architecture.png

80.2 KB | W: | H:

images/architecture.png

95.4 KB | W: | H:

images/architecture.png
images/architecture.png
images/architecture.png
images/architecture.png
  • 2-up
  • Swipe
  • Onion skin
......@@ -17,18 +17,31 @@ class DomainSpanESM(nn.Module):
self.config = config
# ESM model
self.esm = EsmModel.from_pretrained(self.config.version, add_pooling_layer=False)
for param in self.esm.parameters():
param.requires_grad = False
if 'esm' in self.config.version:
# ESM model
self.esm = EsmModel.from_pretrained(self.config.version, add_pooling_layer=False)
for param in self.esm.parameters():
param.requires_grad = False
if not self.config.freeze:
warm_layers = self.esm.encoder.layer[-6:]
for param in warm_layers.parameters():
param.requires_grad = True
hidd_size = self.esm.config.hidden_size
if not self.config.freeze:
warm_layers = self.esm.encoder.layer[-6:]
for param in warm_layers.parameters():
param.requires_grad = True
else:
hidd_size = self.esm.config.hidden_size
if 'prot' in self.config.version:
self.t5 = T5EncoderModel.from_pretrained(self.config.version, torch_dtype=torch.float16)
else:
self.t5 = T5EncoderModel.from_pretrained(self.config.version)
for param in self.t5.parameters():
param.requires_grad = False
hidd_size = self.t5.config.d_model
in_size = hidd_size
out_size = hidd_size #128
......@@ -59,8 +72,14 @@ class DomainSpanESM(nn.Module):
def forward(self, inputs, start=None, end=None):
# Get hidden states from ESM
last_hidd = self.esm(**inputs)[0]
last_hidd = last_hidd[:, 1:, :] # [B, T, H]
if 'esm' in self.config.version:
last_hidd = self.esm(**inputs)[0]
last_hidd = last_hidd[:, 1:, :]
else:
last_hidd = self.t5(**inputs).last_hidden_state
if 'prot' in self.config.version:
last_hidd = last_hidd.to(torch.float32)
batch_size, seq_len, hidden_dim = last_hidd.shape
......@@ -86,21 +105,24 @@ class DomainSpanESM(nn.Module):
end_loss = ce_span(end_logits, end)
span_loss = (start_loss + end_loss) / 2.0
# Create base mask from attention mask
mask = inputs['attention_mask'][:, 1:].float() # [B, T]
# mask from attention mask
if 'esm' in self.config.version:
mask = inputs['attention_mask'][:, 1:].float()
else:
mask = inputs['attention_mask'].float()
# Apply domain span masking if needed
if start_pred_pos is not None and end_pred_pos is not None:
valid_span = start_pred_pos < end_pred_pos
if valid_span.any():
arange = torch.arange(seq_len, device=start_pred_pos.device).unsqueeze(0) # [1, T]
arange = torch.arange(seq_len, device=start_pred_pos.device).unsqueeze(0)
s_exp = start_pred_pos[valid_span].unsqueeze(1)
e_exp = end_pred_pos[valid_span].unsqueeze(1)
span_mask = ((arange >= s_exp) & (arange <= e_exp)).float()
mask[valid_span] = span_mask
x = (last_hidd * mask.unsqueeze(-1)).sum(dim=1) / (mask.sum(dim=1, keepdim=True) + 1e-8) # [B, H]
x = (last_hidd * mask.unsqueeze(-1)).sum(dim=1) / (mask.sum(dim=1, keepdim=True) + 1e-8)
logits = self.clf_head(x)
......
......@@ -222,8 +222,8 @@ class TrainDomSpanESM:
return history
def _print_log(self, epoch, lr, loss_train, metrics_train, loss_val=None, metrics_val=None):
@staticmethod
def _print_log(epoch, lr, loss_train, metrics_train, loss_val=None, metrics_val=None):
log = f'Epoch: {epoch+1}'
log += f' Lr: {lr :4f}'
......
from typing import Dict, List
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
......@@ -6,7 +7,7 @@ from sklearn.model_selection import train_test_split
from collections import defaultdict
def make_splits(eval_size, targets, seed, stratify=True):
def make_splits(eval_size, targets, seed, stratify=True) -> Dict[str,List[int]]:
data_idx = np.arange(len(targets))
......@@ -14,7 +15,7 @@ def make_splits(eval_size, targets, seed, stratify=True):
data_idx, test_size=eval_size, random_state=seed, stratify=targets if stratify else None
)
split_dict = defaultdict(pd.DataFrame)
split_dict = defaultdict(list)
split_dict['train'] = train_idx
split_dict['val'] = test_idx
......
......@@ -79,5 +79,5 @@ def save_model(model, filepath: Path|str):
torch.save({
'model_state_dict': model.state_dict(),
'config': model.config.to_dict(),
'config': model.config.to_dict() if hasattr(model, 'config') else None,
}, filepath)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment