File size: 7,757 Bytes
bfca2b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import math
import torch
import torch.nn as nn
from typing import Optional, Tuple, Union
from dataclasses import dataclass
from transformers import PreTrainedModel
from transformers.modeling_outputs import ModelOutput
from transformers.models.esm import EsmPreTrainedModel, EsmModel
from transformers.models.bert import BertPreTrainedModel, BertModel
from .configuration_protst import ProtSTConfig


@dataclass
class EsmProteinRepresentationOutput(ModelOutput):

    protein_feature: torch.FloatTensor = None
    residue_feature: torch.FloatTensor = None


@dataclass
class BertTextRepresentationOutput(ModelOutput):

    text_feature: torch.FloatTensor = None
    word_feature: torch.FloatTensor = None


@dataclass
class ProtSTClassificationOutput(ModelOutput):

    loss: Optional[torch.FloatTensor] = None
    logits: torch.FloatTensor = None

class ProtSTHead(nn.Module):
    def __init__(self, config, out_dim=512):
        super().__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.out_proj = nn.Linear(config.hidden_size, out_dim)

    def forward(self, x):
        x = self.dense(x)
        x = nn.functional.relu(x)
        x = self.out_proj(x)
        return x


class BertForPubMed(BertPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)

        self.pad_token_id = config.pad_token_id
        self.cls_token_id = config.cls_token_id
        self.sep_token_id = config.sep_token_id

        self.bert = BertModel(config, add_pooling_layer=False)
        self.text_mlp = ProtSTHead(config)
        self.word_mlp = ProtSTHead(config)

        self.post_init() # NOTE

    def forward(
        self,
        input_ids: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        token_type_ids: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.Tensor] = None,
        head_mask: Optional[torch.Tensor] = None,
        inputs_embeds: Optional[torch.Tensor] = None,
        encoder_hidden_states: Optional[torch.Tensor] = None,
        encoder_attention_mask: Optional[torch.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple[torch.Tensor], ModelOutput]:
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.bert(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_attention_mask,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        word_feature = outputs.last_hidden_state
        is_special = (input_ids == self.cls_token_id) | (input_ids == self.sep_token_id) | (input_ids == self.pad_token_id)
        special_mask = (~is_special).to(torch.int64).unsqueeze(-1)
        pooled_feature = ((word_feature * special_mask).sum(1) / (special_mask.sum(1) + 1.0e-6)).to(word_feature.dtype)
        pooled_feature = self.text_mlp(pooled_feature)
        word_feature = self.word_mlp(word_feature)

        if not return_dict:
            return (pooled_feature, word_feature)

        return BertTextRepresentationOutput(text_feature=pooled_feature, word_feature=word_feature)
        



class EsmForProteinRepresentation(EsmPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)

        self.cls_token_id = config.cls_token_id
        self.pad_token_id = config.pad_token_id
        self.eos_token_id = config.eos_token_id

        self.esm = EsmModel(config, add_pooling_layer=False)

        self.post_init() # NOTE

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        head_mask: Optional[torch.Tensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, EsmProteinRepresentationOutput]:

        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.esm(
            input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        residue_feature = outputs.last_hidden_state  # [batch_size, seq_len, hidden_dim]

        # mean readout
        is_special = (
            (input_ids == self.cls_token_id) | (input_ids == self.eos_token_id) | (input_ids == self.pad_token_id)
        )
        special_mask = (~is_special).to(torch.int64).unsqueeze(-1)
        protein_feature = ((residue_feature * special_mask).sum(1) / (special_mask.sum(1) + 1.0e-6)).to(residue_feature.dtype)

        return EsmProteinRepresentationOutput(
            protein_feature=protein_feature, residue_feature=residue_feature
        )


class ProtSTPreTrainedModel(PreTrainedModel):
    config_class = ProtSTConfig


class ProtSTForProteinPropertyPrediction(ProtSTPreTrainedModel):
    def __init__(self, config):
        super().__init__(config)

        self.config = config
        self.protein_model = EsmForProteinRepresentation(config.protein_config)
        self.classifier = ProtSTHead(config.protein_config, out_dim=config.num_labels)

        self.post_init() # NOTE

    def forward(
        self,
        input_ids: Optional[torch.LongTensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        position_ids: Optional[torch.LongTensor] = None,
        head_mask: Optional[torch.Tensor] = None,
        inputs_embeds: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, ProtSTClassificationOutput]:
        r"""
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the protein classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Returns:
        Examples:
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.protein_model(
            input_ids,
            attention_mask=attention_mask,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        logits = self.classifier(outputs.protein_feature) # [bsz, xxx] -> [bsz, num_labels]

        loss = None
        if labels is not None:
            loss_fct = nn.CrossEntropyLoss()

            labels = labels.to(logits.device)
            loss = loss_fct(logits.view(-1, logits.shape[-1]), labels.view(-1))

        if not return_dict:
            output = (logits,)
            return ((loss,) + output) if loss is not None else output

        return ProtSTClassificationOutput(loss=loss, logits=logits)