import torch from torch import nn from transformers import T5ForConditionalGeneration, T5Config, T5Tokenizer from transformers.modeling_outputs import BaseModelOutput import os def share_weight_t5(t5_model, num_layers, nosharelayers=0): """ Share encoder-decoder weights within a T5 model. Mirrors the exact behavior of utils/share_weight.py:share_weight_t5 to ensure compatibility with saved checkpoints. """ start_layer = nosharelayers end_layer = num_layers - nosharelayers for i in range(start_layer, end_layer): # qkvo weights t5_model.decoder.block[i].layer[0].SelfAttention.q.weight = \ t5_model.encoder.block[i].layer[0].SelfAttention.q.weight t5_model.decoder.block[i].layer[0].SelfAttention.k.weight = \ t5_model.encoder.block[i].layer[0].SelfAttention.k.weight t5_model.decoder.block[i].layer[0].SelfAttention.v.weight = \ t5_model.encoder.block[i].layer[0].SelfAttention.v.weight t5_model.decoder.block[i].layer[0].SelfAttention.o.weight = \ t5_model.encoder.block[i].layer[0].SelfAttention.o.weight # qkvo layer norm t5_model.decoder.block[i].layer[0].layer_norm.weight = \ t5_model.encoder.block[i].layer[0].layer_norm.weight # ffn (block[0] is intentional - preserves training behavior) t5_model.decoder.block[0].layer[2].DenseReluDense.wi.weight = \ t5_model.encoder.block[i].layer[1].DenseReluDense.wi.weight t5_model.decoder.block[0].layer[2].DenseReluDense.wo.weight = \ t5_model.encoder.block[i].layer[1].DenseReluDense.wo.weight class OuroborosModel(nn.Module): """ Ouroboros: Bidirectional Protein-Text Generation Model. Two T5 models connected by cross-modal projection layers. """ def __init__(self, t5config_path="t5config_large.json", text_share_param=True, protein_share_param=True, share_fc=True, use_mean_pooling=False, protein_tokenizer_name="Rostlab/prot_t5_xl_uniref50", text_tokenizer_name="google-t5/t5-base", protein_tokenizer_path=None, text_tokenizer_path=None): super().__init__() self.text_share_param = text_share_param self.protein_share_param = protein_share_param self.use_mean_pooling = use_mean_pooling # Tokenizers: try local path first (for offline/rjob), fall back to HF hub (for Spaces) if protein_tokenizer_path is not None and os.path.isdir(protein_tokenizer_path): self.protein_tokenizer = T5Tokenizer.from_pretrained( protein_tokenizer_path, do_lower_case=False) else: self.protein_tokenizer = T5Tokenizer.from_pretrained( protein_tokenizer_name, do_lower_case=False) if text_tokenizer_path is not None and os.path.isdir(text_tokenizer_path): self.text_tokenizer = T5Tokenizer.from_pretrained(text_tokenizer_path) else: self.text_tokenizer = T5Tokenizer.from_pretrained(text_tokenizer_name) print(f"Protein vocab: {self.protein_tokenizer.vocab_size}") print(f"Text vocab: {self.text_tokenizer.vocab_size}") # Build protein T5 configs_p = T5Config.from_json_file(t5config_path) configs_p.vocab_size = 128 # ProtT5 vocab size self.p_t5_model = T5ForConditionalGeneration(configs_p) if protein_share_param: share_weight_t5(self.p_t5_model, configs_p.num_layers) print("Applied protein_share_param") self.p_t5_encoder = self.p_t5_model.get_encoder() # Build text T5 configs_t = T5Config.from_json_file(t5config_path) configs_t.vocab_size = 32128 # Original T5-base vocab size (training config) self.t_t5_model = T5ForConditionalGeneration(configs_t) if text_share_param: share_weight_t5(self.t_t5_model, configs_t.num_layers) print("Applied text_share_param") self.t_t5_encoder = self.t_t5_model.get_encoder() # Cross-modal projection layers self.t_model_dim = self.t_t5_model.model_dim self.p_model_dim = self.p_t5_model.model_dim print(f"Text model dim: {self.t_model_dim}, Protein model dim: {self.p_model_dim}") self.fc_p2t = nn.Linear(self.p_model_dim, self.t_model_dim, bias=False) self.fc_t2p = nn.Linear(self.t_model_dim, self.p_model_dim, bias=False) if share_fc: self.fc_t2p.weight = nn.Parameter(self.fc_p2t.weight.T.contiguous()) print("Applied share_fc") print(f"Total parameters: {sum(p.numel() for p in self.parameters()):,}") def load_checkpoint(self, path): """Load pretrained weights from a .pt checkpoint file.""" state_dict = torch.load(path, map_location='cpu', weights_only=True) new_state_dict = {} for key, value in state_dict.items(): new_key = key.replace('module.', '') new_state_dict[new_key] = value missing, unexpected = self.load_state_dict(new_state_dict, strict=False) if missing: print(f"[WARN] Missing keys: {missing}") if unexpected: print(f"[WARN] Unexpected keys: {unexpected}") print(f"Loaded checkpoint from {path}") def _encode_text(self, text_ids, text_mask): outputs = self.t_t5_encoder(input_ids=text_ids, attention_mask=text_mask) last_hidden_state = outputs.last_hidden_state if self.use_mean_pooling: masked = last_hidden_state * text_mask.unsqueeze(-1) pooled = masked.sum(dim=1) / text_mask.sum(dim=1, keepdim=True) pooled = pooled.unsqueeze(1) seq_condition = self.fc_t2p(pooled) else: seq_condition = self.fc_t2p(last_hidden_state) return BaseModelOutput(last_hidden_state=seq_condition) def _encode_protein(self, protein_ids, protein_mask): outputs = self.p_t5_encoder(input_ids=protein_ids, attention_mask=protein_mask) last_hidden_state = outputs.last_hidden_state if self.use_mean_pooling: masked = last_hidden_state * protein_mask.unsqueeze(-1) pooled = masked.sum(dim=1) / protein_mask.sum(dim=1, keepdim=True) pooled = pooled.unsqueeze(1) text_condition = self.fc_p2t(pooled) else: text_condition = self.fc_p2t(last_hidden_state) return BaseModelOutput(last_hidden_state=text_condition) def protein_to_text(self, protein_sequences, use_greedy=False, **gen_kwargs): """ Protein sequence(s) -> Text description(s). Input: list of protein strings, e.g. ["M A K N ...", "M T D ..."] Output: list of text strings """ protein_input = self.protein_tokenizer( protein_sequences, return_tensors="pt", padding='max_length', truncation=True, max_length=512 ) protein_ids = protein_input['input_ids'].to(self._device) protein_mask = protein_input['attention_mask'].to(self._device) text_condition = self._encode_protein(protein_ids, protein_mask) if use_greedy: output_ids = self.t_t5_model.generate( encoder_outputs=text_condition, max_length=self._max_length, repetition_penalty=1.0, num_beams=1, do_sample=False, num_return_sequences=1, ) else: num_beams = max(gen_kwargs.get('num_beams', 4), gen_kwargs.get('num_return_sequences', 1)) output_ids = self.t_t5_model.generate( encoder_outputs=text_condition, max_length=self._max_length, temperature=gen_kwargs.get('temperature', 1.0), top_k=gen_kwargs.get('top_k', 40), top_p=gen_kwargs.get('top_p', 0.9), repetition_penalty=1.0, num_beams=num_beams, do_sample=True, num_return_sequences=1, ) output_texts = self.text_tokenizer.batch_decode(output_ids, skip_special_tokens=True) return output_texts def text_to_protein(self, text_descriptions, use_greedy=False, **gen_kwargs): """ Text description(s) -> Protein sequence(s). Input: list of text strings Output: list of protein strings (spaces removed) """ text_input = self.text_tokenizer( text_descriptions, return_tensors="pt", padding='max_length', truncation=True, max_length=512 ) text_ids = text_input['input_ids'].to(self._device) text_mask = text_input['attention_mask'].to(self._device) seq_condition = self._encode_text(text_ids, text_mask) num_return = gen_kwargs.get('num_return_sequences', 1) if use_greedy: output_ids = self.p_t5_model.generate( encoder_outputs=seq_condition, max_length=self._max_length, repetition_penalty=1.0, num_beams=1, do_sample=False, num_return_sequences=1, ) else: num_beams = max(gen_kwargs.get('num_beams', 4), num_return) output_ids = self.p_t5_model.generate( encoder_outputs=seq_condition, max_length=self._max_length, temperature=gen_kwargs.get('temperature', 1.0), top_k=gen_kwargs.get('top_k', 40), top_p=gen_kwargs.get('top_p', 0.9), repetition_penalty=1.0, num_beams=num_beams, do_sample=True, num_return_sequences=num_return, ) output_proteins = self.protein_tokenizer.batch_decode(output_ids, skip_special_tokens=True) output_proteins = [s.replace(" ", "") for s in output_proteins] return output_proteins @property def _device(self): return next(self.parameters()).device @property def _max_length(self): return getattr(self, 'max_generation_length', 512) def create_default_model(device="cuda", fp16=True, protein_tokenizer_path=None, text_tokenizer_path=None): """Create and load the default Ouroboros model.""" model = OuroborosModel( t5config_path=os.path.join(os.path.dirname(__file__), "t5config_large.json"), text_share_param=True, protein_share_param=True, share_fc=True, use_mean_pooling=False, protein_tokenizer_path=protein_tokenizer_path, text_tokenizer_path=text_tokenizer_path, ) if fp16 and device != "cpu": model = model.half() model.to(device) model.eval() return model