CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
modular_evolla.py1024 linesDownload Raw Back to evolla
1# coding=utf-82# Copyright 2025 Westlake Representational Learning Lab (Fajie Yuan Lab) team and the HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8#     http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15 16import warnings17from dataclasses import dataclass18from typing import Optional, Union19 20import torch21from torch import Tensor, nn22 23from ...cache_utils import Cache, DynamicCache24from ...generation import GenerationMixin25from ...masking_utils import create_causal_mask26from ...modeling_outputs import (27    BaseModelOutputWithPast,28    BaseModelOutputWithPoolingAndCrossAttentions,29    CausalLMOutputWithPast,30    ModelOutput,31)32from ...modeling_utils import ModuleUtilsMixin, PreTrainedModel, get_parameter_dtype33from ...utils import (34    auto_docstring,35    can_return_tuple,36    logging,37)38from ...utils.deprecation import deprecate_kwarg39from ...utils.generic import OutputRecorder, check_model_inputs40from ..esm.modeling_esm import (41    EsmAttention,42    EsmEmbeddings,43    EsmEncoder,44    EsmIntermediate,45    EsmLayer,46    EsmOutput,47    EsmPooler,48    EsmSelfAttention,49    EsmSelfOutput,50)51from ..llama.modeling_llama import (52    LlamaAttention,53    LlamaDecoderLayer,54    LlamaMLP,55    LlamaPreTrainedModel,56    LlamaRMSNorm,57    LlamaRotaryEmbedding,58)59from .configuration_evolla import EvollaConfig, SaProtConfig60 61 62logger = logging.get_logger(__name__)63 64 65class EvollaSaProtEmbeddings(EsmEmbeddings):66    def __init__(self, config):67        super().__init__(config)68        # remove the position_ids in EsmEmbeddings69        self.position_ids = None70 71 72def rotate_half_esm(x):73    x1, x2 = x.chunk(2, dim=-1)74    return torch.cat((-x2, x1), dim=-1)75 76 77def apply_rotary_pos_emb_esm(x, cos, sin):78    cos = cos[:, :, : x.shape[-2], :]79    sin = sin[:, :, : x.shape[-2], :]80 81    return (x * cos) + (rotate_half_esm(x) * sin)82 83 84class EvollaSaProtRotaryEmbedding(nn.Module):85    """86    Rotary position embeddings based on those in87    [RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer). Query and keys are transformed by rotation88    matrices which depend on their relative positions.89    """90 91    inv_freq: torch.Tensor  # fix linting for `register_buffer`92 93    def __init__(self, dim: int):94        super().__init__()95        # Generate and save the inverse frequency buffer (non trainable)96        inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))97        self.register_buffer("inv_freq", inv_freq)98 99        self._seq_len_cached = None100        self._cos_cached = None101        self._sin_cached = None102 103    def _update_cos_sin_tables(self, x, seq_dimension=2):104        seq_len = x.shape[seq_dimension]105 106        # Reset the tables if the sequence length has changed,107        # or if we're on a new device (possibly due to tracing for instance)108        if seq_len != self._seq_len_cached or self._cos_cached.device != x.device:109            self._seq_len_cached = seq_len110            t = torch.arange(x.shape[seq_dimension], device=x.device).type_as(self.inv_freq)111            freqs = torch.outer(t, self.inv_freq)112            emb = torch.cat((freqs, freqs), dim=-1).to(x.device)113 114            self._cos_cached = emb.cos()[None, None, :, :]115            self._sin_cached = emb.sin()[None, None, :, :]116 117        return self._cos_cached, self._sin_cached118 119    def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:120        self._cos_cached, self._sin_cached = self._update_cos_sin_tables(k, seq_dimension=-2)121 122        return (123            apply_rotary_pos_emb_esm(q, self._cos_cached, self._sin_cached).to(dtype=q.dtype),124            apply_rotary_pos_emb_esm(k, self._cos_cached, self._sin_cached).to(dtype=k.dtype),125        )126 127 128class EvollaSaProtSelfAttention(EsmSelfAttention):129    def __init__(self, config, position_embedding_type=None, layer_idx=None, is_cross_attention=False):130        nn.Module.__init__(self)131        self.config = config132 133        if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):134            raise ValueError(135                f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "136                f"heads ({config.num_attention_heads})"137            )138 139        self.num_attention_heads = config.num_attention_heads140        self.attention_head_size = int(config.hidden_size / config.num_attention_heads)141        self.all_head_size = self.num_attention_heads * self.attention_head_size142 143        self.query = nn.Linear(config.hidden_size, self.all_head_size)144        self.key = nn.Linear(config.hidden_size, self.all_head_size)145        self.value = nn.Linear(config.hidden_size, self.all_head_size)146 147        self.dropout = config.attention_probs_dropout_prob148        self.position_embedding_type = position_embedding_type or getattr(149            config, "position_embedding_type", "absolute"150        )151        self.rotary_embeddings = None152        if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":153            self.max_position_embeddings = config.max_position_embeddings154            self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)155        elif self.position_embedding_type == "rotary":156            self.rotary_embeddings = EvollaSaProtRotaryEmbedding(dim=self.attention_head_size)157 158        self.is_decoder = config.is_decoder159        self.layer_idx = layer_idx160        self.scaling = 1.0161        self.is_causal = self.is_decoder and not is_cross_attention162 163 164class EvollaSaProtSelfOutput(EsmSelfOutput):165    pass166 167 168class EvollaSaProtAttention(EsmAttention):169    pass170 171 172class EvollaSaProtIntermediate(EsmIntermediate):173    pass174 175 176class EvollaSaProtOutput(EsmOutput):177    pass178 179 180class EvollaSaProtLayer(EsmLayer):181    pass182 183 184class EvollaSaProtEncoder(EsmEncoder):185    pass186 187 188class EvollaSaProtPooler(EsmPooler):189    pass190 191 192@auto_docstring193class EvollaSaProtPreTrainedModel(PreTrainedModel):194    config: SaProtConfig195    _no_split_modules = ["EvollaSaProtLayer"]196    _supports_flash_attn = True197    _supports_sdpa = True198    _supports_attention_backend = True199 200    _can_record_outputs = {201        "hidden_states": EvollaSaProtLayer,202        "attentions": [OutputRecorder(EvollaSaProtSelfAttention, index=1, layer_name="attention")],203        "cross_attentions": [204            OutputRecorder(EvollaSaProtSelfAttention, index=1, layer_name="crossattention"),205        ],206    }207 208    def _init_weights(self, module):209        """Initialize the weights"""210        std = self.config.initializer_range211        if isinstance(module, nn.Linear):212            module.weight.data.normal_(mean=0.0, std=std)213            if module.bias is not None:214                module.bias.data.zero_()215        elif isinstance(module, nn.Embedding):216            module.weight.data.normal_(mean=0.0, std=std)217            if module.padding_idx is not None:218                module.weight.data[module.padding_idx].zero_()219        elif isinstance(module, nn.LayerNorm):220            module.bias.data.zero_()221            module.weight.data.fill_(1.0)222 223 224class EvollaSaProtProteinEncoder(EvollaSaProtPreTrainedModel):225    def __init__(self, config: SaProtConfig):226        super().__init__(config)227        self.embeddings = EvollaSaProtEmbeddings(config)228        self.encoder = EvollaSaProtEncoder(config)229 230    def get_input_embeddings(self):231        return self.embeddings.word_embeddings232 233    def set_input_embeddings(self, value):234        self.embeddings.word_embeddings = value235 236    def _prune_heads(self, heads_to_prune):237        """238        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base239        class PreTrainedModel240        """241        for layer, heads in heads_to_prune.items():242            self.encoder.layer[layer].attention.prune_heads(heads)243 244    @check_model_inputs()245    def forward(246        self,247        input_ids: Optional[torch.Tensor],248        attention_mask: Optional[torch.Tensor] = None,249    ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:250        input_shape = input_ids.size()251        batch_size, seq_length = input_shape252 253        device = input_ids.device254        if attention_mask is None:255            attention_mask = torch.ones(((batch_size, seq_length)), device=device)256 257        inputs_embeds = self.embeddings(input_ids=input_ids, attention_mask=attention_mask)258        extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)259        encoder_outputs = self.encoder(inputs_embeds, attention_mask=extended_attention_mask)260        sequence_output = encoder_outputs[0]261 262        return BaseModelOutputWithPoolingAndCrossAttentions(263            last_hidden_state=sequence_output,264            hidden_states=encoder_outputs.hidden_states,265            attentions=encoder_outputs.attentions,266            cross_attentions=encoder_outputs.cross_attentions,267        )268 269    def get_extended_attention_mask(270        self,271        attention_mask: Tensor,272        input_shape: tuple[int],273        device: Optional[torch.device] = None,274        dtype: Optional[torch.dtype] = None,275    ) -> Tensor:276        """277        Makes broadcastable attention and causal masks so that future and masked tokens are ignored.278 279        Arguments:280            attention_mask (`torch.Tensor`):281                Mask with ones indicating tokens to attend to, zeros for tokens to ignore.282            input_shape (`Tuple[int]`):283                The shape of the input to the model.284 285        Returns:286            `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.287        """288        if dtype is None:289            dtype = get_parameter_dtype(self)290 291        if not (attention_mask.dim() == 2 and self.config.is_decoder):292            # show warning only if it won't be shown in `create_extended_attention_mask_for_decoder`293            if device is not None:294                warnings.warn(295                    "The `device` argument is deprecated and will be removed in v5 of Transformers.", FutureWarning296                )297        # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]298        # ourselves in which case we just need to make it broadcastable to all heads.299        if attention_mask.dim() == 3:300            extended_attention_mask = attention_mask[:, None, :, :]301        elif attention_mask.dim() == 2:302            # Provided a padding mask of dimensions [batch_size, seq_length]303            # - if the model is a decoder, apply a causal mask in addition to the padding mask304            # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]305            if self.config.is_decoder:306                extended_attention_mask = ModuleUtilsMixin.create_extended_attention_mask_for_decoder(307                    input_shape, attention_mask, device308                )309            else:310                extended_attention_mask = attention_mask[:, None, None, :]311        else:312            raise ValueError(313                f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"314            )315 316        # Since attention_mask is 1.0 for positions we want to attend and 0.0 for317        # masked positions, this operation will create a tensor which is 0.0 for318        # positions we want to attend and the dtype's smallest value for masked positions.319        # Since we are adding it to the raw scores before the softmax, this is320        # effectively the same as removing these entirely.321        extended_attention_mask = extended_attention_mask.to(dtype=dtype)  # fp16 compatibility322        extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(dtype).min323        return extended_attention_mask324 325 326class EvollaSequenceCompressorAttention(nn.Module):327    def __init__(self, dim, dim_head=64, heads=8):328        super().__init__()329        self.scale = dim_head**-0.5330        self.heads = heads331        inner_dim = dim_head * heads332 333        self.norm_media = nn.LayerNorm(dim)334        self.norm_latents = nn.LayerNorm(dim)335 336        self.to_q = nn.Linear(dim, inner_dim, bias=False)337        self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)338        self.to_out = nn.Linear(inner_dim, dim, bias=False)339 340    def forward(self, x, latents, mask):341        """342        Args:343            x (torch.Tensor): image features344                shape (b, n1, D)345            latent (torch.Tensor): latent features346                shape (b, n2, D);  n2: num of latent tokens347        """348        x = self.norm_media(x)349        latents = self.norm_latents(latents)350 351        h = self.heads352 353        q = self.to_q(latents)354        kv_input = torch.cat((x, latents), dim=-2)355        k, v = self.to_kv(kv_input).chunk(356            2, dim=-1357        )  # each: batch_size, max_protein_length+num_latents, dim_head*num_heads358 359        q = q.view(q.size(0), q.size(1), h, -1).permute(0, 2, 1, 3)360        k = k.view(k.size(0), k.size(1), h, -1).permute(0, 2, 1, 3)361        v = v.view(v.size(0), v.size(1), h, -1).permute(0, 2, 1, 3)362        q = q * self.scale  # batch_size, num_heads, num_latents, dim_head363 364        # attention365        sim = torch.matmul(q, k.transpose(-1, -2))366        sim = sim - sim.amax(dim=-1, keepdim=True).detach()367        bs, nh, skd, okd = sim.shape368        ones = torch.ones(nh, skd).to(mask.device)  # Create a tensor of ones with shape (nh, skd)369        mask_exp = mask[:, None, None, :]370        ones_exp = ones[None, :, :, None]371        mask = mask_exp * ones_exp372 373        sim = sim.masked_fill((1 - mask).bool(), -1e4)374        attn = sim.softmax(dim=-1)375        out = torch.matmul(attn, v)376        out = out.permute(0, 2, 1, 3)377 378        # [batch, seq, head, features] -> [batch, seq, head*features]379        out = out.reshape(out.size(0), out.size(1), -1)380 381        return self.to_out(out)382 383 384class EvollaFeedForward(nn.Module):385    def __init__(self, dim, mult=4):386        super().__init__()387        inner_dim = int(dim * mult)388 389        self.norm = nn.LayerNorm(dim)390        self.fc1 = nn.Linear(dim, inner_dim, bias=False)391        self.activation = nn.GELU()392        self.fc2 = nn.Linear(inner_dim, dim, bias=False)393 394    def forward(self, x):395        return self.fc2(self.activation(self.fc1(self.norm(x))))396 397 398class EvollaSequenceCompressorResampler(nn.Module):399    def __init__(self, config: EvollaConfig):400        super().__init__()401        protein_repr_dim = config.protein_encoder_config.hidden_size402        self.num_latents = config.resampler_num_latents403        self.latents = nn.Parameter(torch.randn(self.num_latents, protein_repr_dim), requires_grad=True)404        self.layers = nn.ModuleList([])405        for _ in range(config.resampler_depth):406            self.layers.append(407                nn.ModuleList(408                    [409                        EvollaSequenceCompressorAttention(410                            dim=protein_repr_dim, dim_head=config.resampler_dim_head, heads=config.resampler_heads411                        ),412                        EvollaFeedForward(dim=protein_repr_dim, mult=config.resampler_ff_mult),413                    ]414                )415            )416 417        self.norm = nn.LayerNorm(config.hidden_size)418        self.protein_projector = nn.Linear(protein_repr_dim, config.hidden_size)419 420    def forward(self, embeds, mask):421        b = embeds.shape[0]422 423        bs, _ = mask.shape  # bs, max_protein_length424        latent_mask = torch.ones(bs, self.num_latents).to(mask.device)425        mask = torch.cat((mask, latent_mask), dim=1)  # bs, max_protein_length + num_latents426 427        # blocks428        ones = torch.ones(b).to(self.latents.device)429        latents = self.latents[None] * ones.view(-1, 1, 1)  # [b,n,d]430        latents = latents.to(embeds.dtype)431        for attn, ff in self.layers:432            latents = attn(embeds, latents, mask) + latents433            latents = ff(latents) + latents434 435        transformed_feature = self.protein_projector(latents)436 437        return self.norm(transformed_feature)438 439 440@dataclass441@auto_docstring442class EvollaProteinEncoderModelOutput(ModelOutput):443    sequence_compressor_output: Optional[torch.FloatTensor] = None444    last_hidden_state: Optional[torch.FloatTensor] = None445    hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None446    attentions: Optional[tuple[torch.FloatTensor, ...]] = None447 448 449class EvollaProteinEncoder(nn.Module):450    def __init__(self, config: EvollaConfig):451        super().__init__()452        self.model = EvollaSaProtProteinEncoder(config=config.protein_encoder_config)453        self.sequence_compressor_resampler = EvollaSequenceCompressorResampler(config=config)454 455    @can_return_tuple456    def forward(self, input_ids: torch.LongTensor, attention_mask: torch.FloatTensor, **kwargs):457        protein_output = self.model(input_ids=input_ids, attention_mask=attention_mask)458        protein_embeds = protein_output.last_hidden_state459        sequence_repr = self.sequence_compressor_resampler(protein_embeds, attention_mask)460 461        return EvollaProteinEncoderModelOutput(462            sequence_compressor_output=sequence_repr,463            last_hidden_state=protein_output.last_hidden_state,464        )465 466 467class EvollaSequenceAlignerCrossAttention(nn.Module):468    def __init__(469        self,470        config,471        protein_encoder_dim: Optional[int] = None,472        structure_encoder_dim: Optional[int] = None,473        msa_encoder_dim: Optional[int] = None,474    ):475        super().__init__()476 477        self.hidden_size = config.hidden_size478        self.num_attention_heads = config.num_attention_heads479        self.scale = self.num_attention_heads**-0.5480        self.attention_head_size = int(self.hidden_size / self.num_attention_heads)481        self.all_head_size = self.num_attention_heads * self.attention_head_size482 483        attention_probs_dropout_prob = config.aligner_attention_probs_dropout_prob484        enable_bias = config.aligner_enable_bias485        ffn_mult = config.aligner_ffn_mult486 487        self.query = nn.Linear(self.hidden_size, self.all_head_size)488        if protein_encoder_dim is not None:489            self.key_protein = nn.Linear(protein_encoder_dim, self.all_head_size)490            self.value_protein = nn.Linear(protein_encoder_dim, self.all_head_size)491        else:492            self.key_protein = None493            self.value_protein = None494 495        if structure_encoder_dim is not None:496            self.key_structure = nn.Linear(structure_encoder_dim, self.all_head_size)497            self.value_structure = nn.Linear(structure_encoder_dim, self.all_head_size)498        else:499            self.key_structure = None500            self.value_structure = None501 502        if msa_encoder_dim is not None:503            self.key_msa = nn.Linear(msa_encoder_dim, self.all_head_size)504            self.value_msa = nn.Linear(msa_encoder_dim, self.all_head_size)505        else:506            self.key_msa = None507            self.value_msa = None508 509        self.attention_norm = EvollaRMSNorm(self.hidden_size)510 511        self.dropout = nn.Dropout(attention_probs_dropout_prob)512 513        self.out_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=enable_bias)514 515        self.ff = EvollaFeedForward(self.hidden_size, ffn_mult)516        self.gate_attention = nn.Parameter(torch.tensor([0.0]))517        self.gate_ffw = nn.Parameter(torch.tensor([0.0]))518 519    def cross_attention(520        self,521        query_states,522        protein_key_value_states,523        structure_key_value_states,524        msa_key_value_states,525        query_attn_mask,526        protein_kv_attn_mask,527        structure_kv_attn_mask,528        msa_kv_attn_mask,529    ):530        """531        query_states: text532        key_value_states: protein533        query_states: [bs, query_seq_len, dim]534        key_value_states: [bs, kv_seq_len, dim]535        query_attn_mask: [bs, query_seq_len]536        kv_attn_mask: [bs, kv_seq_len]537        """538 539        # Concatenate protein and structure540        kv_attn_mask = [protein_kv_attn_mask, structure_kv_attn_mask, msa_kv_attn_mask]541        kv_attn_mask = [_ for _ in kv_attn_mask if _ is not None]542        if not kv_attn_mask:543            raise ValueError("At least one modality should be provided for cross attention.")544        kv_attn_mask = torch.cat(kv_attn_mask, dim=1)545 546        query_layer = self.attention_norm(query_states)547 548        # Warning: This place might cause issues, refers to549        # https://discuss.pytorch.org/t/cuda-error-cublas-status-not-supported-when-calling-cublasltmatmul-from-torch-nn-functional-linear/170214/13550        # Solution: add `DISABLE_ADDMM_CUDA_LT=1` as environment variable551        # Apply linear transformation to input_query, input_key, and input_value552        query_layer = self.query(query_layer)  # [bs, querylength, dim]553 554        if self.key_protein is not None and self.value_protein is not None:555            protein_key_value_states = protein_key_value_states.to(query_states)556            key_layer_protein = self.key_protein(protein_key_value_states)  # [bs, keylength, dim]557            value_layer_protein = self.value_protein(protein_key_value_states)  # [bs, keylength, dim]558        else:559            key_layer_protein = None560            value_layer_protein = None561 562        if self.key_structure is not None and self.value_structure is not None:563            structure_key_value_states = structure_key_value_states.to(query_states)564            key_layer_structure = self.key_structure(structure_key_value_states)  # [bs, keylength, dim]565            value_layer_structure = self.value_structure(structure_key_value_states)  # [bs, keylength, dim]566        else:567            key_layer_structure = None568            value_layer_structure = None569 570        if self.key_msa is not None and self.value_msa is not None:571            msa_key_value_states = msa_key_value_states.to(query_states)572            key_layer_msa = self.key_msa(msa_key_value_states)  # [bs, keylength, dim]573            value_layer_msa = self.value_msa(msa_key_value_states)  # [bs, keylength, dim]574        else:575            key_layer_msa = None576            value_layer_msa = None577 578        key_layer = [key_layer_protein, key_layer_structure, key_layer_msa]579        key_layer = [_ for _ in key_layer if _ is not None]580        key_layer = torch.cat(key_layer, dim=1)581 582        value_layer = [value_layer_protein, value_layer_structure, value_layer_msa]583        value_layer = [_ for _ in value_layer if _ is not None]584        value_layer = torch.cat(value_layer, dim=1)585 586        new_query_layer_shape = query_layer.size()[:-1] + (587            self.num_attention_heads,588            self.attention_head_size,589        )590        query_layer = query_layer.view(*new_query_layer_shape).permute(0, 2, 1, 3)591 592        new_key_layer_shape = key_layer.size()[:-1] + (593            self.num_attention_heads,594            self.attention_head_size,595        )596        key_layer = key_layer.view(*new_key_layer_shape).permute(0, 2, 1, 3)597 598        new_value_layer_shape = value_layer.size()[:-1] + (599            self.num_attention_heads,600            self.attention_head_size,601        )602        value_layer = value_layer.view(*new_value_layer_shape).permute(0, 2, 1, 3)603 604        query_layer = query_layer * self.scale605 606        # attention_mask: [bs, 1, querylength, keylength]607        if query_attn_mask is None:608            query_attn_mask = torch.ones(query_states.size(0), query_states.size(1)).to(query_states.device)609        attention_mask = query_attn_mask[:, None, :, None] * kv_attn_mask[:, None, None, :]610        # Compute the scaled dot-product attention scores611        attn_weights = torch.matmul(query_layer, key_layer.transpose(-1, -2))  # [bs, numheads, querylength, keylength]612        attn_weights = attn_weights - attn_weights.amax(dim=-1, keepdim=True).detach()  # To stabilize score613        attention_scores = attn_weights.masked_fill(614            (1 - attention_mask).bool(), torch.finfo(attn_weights.dtype).min615        )  # [bs, numheads, querylength, keylength]616 617        attention_probs = nn.Softmax(dim=-1)(attention_scores)618 619        # attention_probs_dropped = self.dropout(attention_probs)620 621        context_layer = torch.matmul(attention_probs, value_layer)  # [bs, numheads, querylength, dim/numheads]622 623        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()624        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)625        context_layer = context_layer.view(*new_context_layer_shape)626 627        context_layer = self.out_proj(context_layer)628 629        return context_layer630 631    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")632    def forward(633        self,634        query_states,635        protein_kv_states,636        structure_kv_states,637        msa_kv_states,638        query_attn_mask,639        protein_kv_attn_mask=None,640        structure_kv_attn_mask=None,641        msa_kv_attn_mask=None,642        protein_batch_mask=None,643        structure_batch_mask=None,644        msa_batch_mask=None,645        past_key_values=None,646    ):647        if protein_kv_states is not None:648            bs, protein_kv_seq_len, dim = protein_kv_states.shape649            if protein_kv_attn_mask is None:650                protein_kv_attn_mask = (651                    torch.ones(bs, protein_kv_seq_len).to(protein_batch_mask.device)652                    * protein_batch_mask.expand(size=(protein_kv_seq_len, bs)).T653                ).to(protein_kv_states.device)654        else:655            protein_kv_attn_mask = None656 657        if structure_kv_states is not None:658            bs, structure_kv_seq_len, dim = structure_kv_states.shape659            if structure_kv_attn_mask is None:660                structure_kv_attn_mask = (661                    torch.ones(bs, structure_kv_seq_len).to(protein_batch_mask.device)662                    * structure_batch_mask.expand(size=(structure_kv_seq_len, bs)).T663                ).to(structure_kv_states.device)664        else:665            structure_kv_attn_mask = None666 667        if msa_kv_states is not None:668            bs, msa_kv_seq_len, dim = msa_kv_states.shape669            if msa_kv_attn_mask is None:670                msa_kv_attn_mask = (671                    torch.ones(bs, msa_kv_seq_len).to(protein_batch_mask.device)672                    * msa_batch_mask.expand(size=(msa_kv_seq_len, bs)).T673                ).to(msa_kv_states.device)674        else:675            msa_kv_attn_mask = None676        hidden_states = query_states677        # only when there's at least one valid modality, crossattention will be performed678        if (679            (protein_kv_states is not None and protein_kv_attn_mask.any())680            or (structure_kv_states is not None and structure_kv_attn_mask.any())681            or (msa_kv_states is not None and msa_kv_attn_mask.any())682        ):683            residual = hidden_states684            hidden_states = self.cross_attention(685                query_states=hidden_states,686                protein_key_value_states=protein_kv_states,687                structure_key_value_states=structure_kv_states,688                msa_key_value_states=msa_kv_states,689                query_attn_mask=query_attn_mask,690                protein_kv_attn_mask=protein_kv_attn_mask,691                structure_kv_attn_mask=structure_kv_attn_mask,692                msa_kv_attn_mask=msa_kv_attn_mask,693            )  # [bs, query_seq_len, dim]694            # tanh gate695            hidden_states = torch.tanh(self.gate_attention) * hidden_states696 697            hidden_states = residual + hidden_states  # input_query698 699            residual = hidden_states700            hidden_states = self.ff(hidden_states) * torch.tanh(self.gate_ffw)701            hidden_states = residual + hidden_states702 703        return hidden_states704 705 706class EvollaRMSNorm(LlamaRMSNorm):707    pass708 709 710class EvollaRotaryEmbedding(LlamaRotaryEmbedding):711    pass712 713 714class EvollaMLP(LlamaMLP):715    pass716 717 718class EvollaAttention(LlamaAttention):719    pass720 721 722class EvollaDecoderLayer(LlamaDecoderLayer):723    def __init__(self, config: EvollaConfig, layer_idx: int):724        super().__init__(config, layer_idx)725        if (layer_idx + 1) % max(config.num_hidden_layers // config.aligner_num_add_layers, 1) == 0:726            self.adapter = EvollaSequenceAlignerCrossAttention(727                config,728                protein_encoder_dim=config.hidden_size,729            )730 731    @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")732    def forward(733        self,734        hidden_states: torch.Tensor,735        position_embeddings: tuple[torch.Tensor, torch.Tensor],736        attention_mask: Optional[torch.Tensor] = None,737        position_ids: Optional[torch.LongTensor] = None,738        past_key_values: Optional[Cache] = None,739        use_cache: Optional[bool] = False,740        cache_position: Optional[torch.LongTensor] = None,741        protein_kv_states: Optional[torch.Tensor] = None,742        structure_kv_states: Optional[torch.Tensor] = None,743        msa_kv_states: Optional[torch.Tensor] = None,744        protein_batch_mask: Optional[torch.Tensor] = None,745        structure_batch_mask: Optional[torch.Tensor] = None,746        msa_batch_mask: Optional[torch.Tensor] = None,747        query_attn_mask: Optional[torch.Tensor] = None,748        **kwargs,749    ):750        residual = hidden_states751 752        hidden_states = self.input_layernorm(hidden_states)753 754        # Self Attention755        hidden_states, _ = self.self_attn(756            hidden_states=hidden_states,757            attention_mask=attention_mask,758            position_ids=position_ids,759            past_key_values=past_key_values,760            use_cache=use_cache,761            cache_position=cache_position,762            position_embeddings=position_embeddings,763            **kwargs,764        )765        hidden_states = residual + hidden_states766 767        # Fully Connected768        residual = hidden_states769        hidden_states = self.post_attention_layernorm(hidden_states)770        hidden_states = self.mlp(hidden_states)771        hidden_states = residual + hidden_states772 773        if hasattr(self, "adapter"):774            hidden_states = self.adapter(775                query_states=hidden_states,776                protein_kv_states=protein_kv_states,777                structure_kv_states=structure_kv_states,778                msa_kv_states=msa_kv_states,779                query_attn_mask=query_attn_mask,780                protein_batch_mask=protein_batch_mask,781                structure_batch_mask=structure_batch_mask,782                msa_batch_mask=msa_batch_mask,783            )784 785        return hidden_states786 787 788class EvollaPreTrainedModel(LlamaPreTrainedModel):789    _supports_flash_attn = False  # see dependency on `EvollaSaProtProteinEncoder`790    _supports_flex_attn = False  # see dependency on `EvollaSaProtProteinEncoder`791    _supports_attention_backend = False792    _no_split_modules = [793        "EvollaDecoderLayer",794        "EvollaSequenceCompressorResampler",795        "EvollaSequenceAlignerCrossAttention",796    ]797 798    def _init_weights(self, module):799        std = self.config.initializer_range800        PreTrainedModel._init_weights(self, module)801        if isinstance(module, EvollaSequenceAlignerCrossAttention):802            module.gate_attention.zero_()803            module.gate_ffw.zero_()804            module.attention_norm.weight.data.fill_(1.0)805        elif isinstance(module, EvollaSequenceCompressorResampler):806            module.latents.data.normal_(mean=0.0, std=std)807 808 809class EvollaModel(EvollaPreTrainedModel):810    def __init__(self, config: EvollaConfig):811        super().__init__(config)812        self.padding_idx = config.pad_token_id813        self.vocab_size = config.vocab_size814        self.embed_tokens = nn.Embedding(self.vocab_size, config.hidden_size, self.padding_idx)815        self.protein_encoder = EvollaProteinEncoder(config=config)816        self.layers = nn.ModuleList(817            [818                EvollaDecoderLayer(819                    config=config,820                    layer_idx=layer_idx,821                )822                for layer_idx in range(config.num_hidden_layers)823            ]824        )825 826        self.norm = EvollaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)827        self.rotary_emb = EvollaRotaryEmbedding(config=config)828        self.gradient_checkpointing = getattr(config, "gradient_checkpointing", False)829        self.post_init()830 831    def get_input_embeddings(self):832        return self.embed_tokens833 834    def set_input_embeddings(self, value):835        self.embed_tokens = value836 837    @auto_docstring838    @check_model_inputs()839    def forward(840        self,841        input_ids: Optional[torch.LongTensor] = None,842        attention_mask: Optional[torch.Tensor] = None,843        position_ids: Optional[torch.LongTensor] = None,844        past_key_values: Optional[Cache] = None,845        inputs_embeds: Optional[torch.FloatTensor] = None,846        use_cache: Optional[bool] = None,847        cache_position: Optional[torch.LongTensor] = None,848        protein_input_ids: Optional[torch.LongTensor] = None,849        protein_attention_mask: Optional[torch.Tensor] = None,850        structure_feats: Optional[torch.FloatTensor] = None,851        msa_feats: Optional[torch.FloatTensor] = None,852        structure_batch_mask: Optional[torch.Tensor] = None,853        msa_batch_mask: Optional[torch.Tensor] = None,854        **kwargs,855    ) -> Union[tuple, BaseModelOutputWithPast]:856        r"""857        protein_input_ids (torch.LongTensor):858            The input IDs for the protein sequence in structure-aware tokens. Should be of shape `(batch_size, protein_seq_length)` and type `torch.LongTensor`.859        protein_attention_mask (torch.Tensor):860            The attention mask for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.Tensor`.861        structure_feats (torch.FloatTensor):862            The input IDs for purely structure-based features. Should be of shape `(batch_size, structure_seq_length, structure_feat_dim)` and type `torch.FloatTensor`. Dummy input for now.863        msa_feats (torch.FloatTensor):864            The input IDs for purely MSA-based features. Should be of shape `(batch_size, msa_seq_length, msa_feat_dim)` and type `torch.FloatTensor`. Dummy input for now.865        structure_batch_mask (torch.Tensor):866            The batch mask to decide which protein sequences are purely structure-based. Should be of shape `(batch_size)` and type `torch.Tensor`. Should be paired with `structure_feats`. Dummpy input for now.867        msa_batch_mask (torch.Tensor):868            The batch mask to decide which protein sequences are purely MSA-based. Should be of shape `(batch_size)` and type `torch.Tensor`. Should be paired with `msa_feats`. Dummpy input for now.869        """870        if (input_ids is None) ^ (inputs_embeds is not None):871            raise ValueError("You must specify exactly one of input_ids or inputs_embeds")872 873        if inputs_embeds is None:874            inputs_embeds = self.embed_tokens(input_ids)875 876        if use_cache and past_key_values is None:877            past_key_values = DynamicCache(config=self.config)878 879        if cache_position is None:880            past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0881            cache_position = torch.arange(882                past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device883            )884 885        if position_ids is None:886            position_ids = cache_position.unsqueeze(0)887 888        protein_feats = None889        protein_batch_mask = None890        # If provided, actually compute them891        if protein_input_ids is not None and protein_attention_mask is not None:892            protein_outputs = self.protein_encoder(893                input_ids=protein_input_ids,894                attention_mask=protein_attention_mask,895            )896            protein_feats = protein_outputs.sequence_compressor_output897            protein_batch_mask = torch.tensor([True] * protein_input_ids.shape[0], device=protein_input_ids.device)898 899        causal_mask = create_causal_mask(900            config=self.config,901            input_embeds=inputs_embeds,902            attention_mask=attention_mask,903            cache_position=cache_position,904            past_key_values=past_key_values,905        )906 907        hidden_states = inputs_embeds908 909        # create position embeddings to be shared across the decoder layers910        position_embeddings = self.rotary_emb(hidden_states, position_ids)911 912        for decoder_layer in self.layers:913            hidden_states = decoder_layer(914                hidden_states,915                attention_mask=causal_mask,916                position_ids=position_ids,917                past_key_values=past_key_values,918                use_cache=use_cache,919                cache_position=cache_position,920                position_embeddings=position_embeddings,921                protein_kv_states=protein_feats,922                structure_kv_states=structure_feats,923                msa_kv_states=msa_feats,924                protein_batch_mask=protein_batch_mask,925                structure_batch_mask=structure_batch_mask,926                msa_batch_mask=msa_batch_mask,927                query_attn_mask=attention_mask,928                **kwargs,929            )930 931        hidden_states = self.norm(hidden_states)932 933        output = BaseModelOutputWithPast(934            last_hidden_state=hidden_states,935            past_key_values=past_key_values,936        )937        return output938 939 940class EvollaForProteinText2Text(EvollaPreTrainedModel, GenerationMixin):941    def __init__(self, config):942        super().__init__(config)943        self.model = EvollaModel(config)944        self.vocab_size = config.vocab_size945        self.lm_head = nn.Linear(config.hidden_size, self.vocab_size, bias=False)946 947        self.post_init()948 949    def get_input_embeddings(self):950        return self.model.get_input_embeddings()951 952    def set_input_embeddings(self, value):953        return self.model.set_input_embeddings(value)954 955    @can_return_tuple956    @auto_docstring957    def forward(958        self,959        input_ids: Optional[torch.LongTensor] = None,  # text input ids960        attention_mask: Optional[torch.Tensor] = None,  # text attention mask961        inputs_embeds: Optional[torch.FloatTensor] = None,  # text input embeddings962        labels: Optional[torch.LongTensor] = None,963        protein_input_ids: Optional[torch.LongTensor] = None,964        protein_attention_mask: Optional[torch.Tensor] = None,965        use_cache: Optional[bool] = None,966        **kwargs,967    ):968        r"""969        protein_input_ids (torch.LongTensor):970            The input IDs for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.LongTensor`.971        protein_attention_mask (torch.Tensor):972            The attention mask for the protein sequence. Should be of shape `(batch_size, protein_seq_length)` and type `torch.Tensor`.973 974        Example:975 976        ```python977        >>> from transformers import EvollaProcessor, EvollaForProteinText2Text978        >>> model = EvollaForProteinText2Text.from_pretrained("westlake/Evolla-10B-hf")979        >>> processor = EvollaProcessor.from_pretrained("westlake/Evolla-10B-hf")980 981        >>> protein_information = {982            "aa_seq": "your amino acid sequence",983            "foldseek": "your foldseek sequence",984        }985        >>> question = "What is the function of this protein?"986        >>> message = [987            {"role": "system", "content": "You are an AI expert that can answer any questions about protein."},988            {"role": "user", "content": question},989        ]990 991        >>> inputs = processor(proteins=[protein_information], messages_list=[message], return_tensors="pt", padding="longest")992        >>> outputs = model.generate(**inputs)993 994        >>> print(processor.batch_decode(outputs, skip_special_tokens=True))995        ```"""996 997        outputs = self.model(998            input_ids=input_ids,999            attention_mask=attention_mask,1000            inputs_embeds=inputs_embeds,1001            protein_input_ids=protein_input_ids,1002            protein_attention_mask=protein_attention_mask,1003            use_cache=use_cache,1004            **kwargs,1005        )1006        hidden_states = outputs[0]1007        logits = self.lm_head(hidden_states)1008 1009        loss = None1010        if labels is not None:1011            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **kwargs)1012 1013        lm_outputs = CausalLMOutputWithPast(1014            loss=loss,1015            logits=logits,1016            past_key_values=outputs.past_key_values,1017            hidden_states=outputs.hidden_states,1018            attentions=outputs.attentions,1019        )1020        return lm_outputs1021 1022 1023__all__ = ["EvollaForProteinText2Text", "EvollaModel", "EvollaPreTrainedModel"]1024 
Aluode/PerceptionLabPortable · CoolFace