Fill-Mask
Transformers
Safetensors
prokbert
bioinformatics
genomics
sequence embedding
genomic language models
nucleotide
dna-sequence
promoter-prediction
phage
custom_code
Run this model with HF Jobs
Run neuralbioinfo/prokbert-mini-long on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/neuralbioinfo/prokbert-mini-long. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/neuralbioinfo/prokbert-mini-long on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use neuralbioinfo/prokbert-mini-long with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use neuralbioinfo/prokbert-mini-long with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="neuralbioinfo/prokbert-mini-long", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("neuralbioinfo/prokbert-mini-long", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Adding curriculum face model
Browse files5 unmodified lines678910111213141516111 unmodified lines1281291301311321331341351361 unmodified line13813914014114214314414514614714814915015115215315415530 unmodified lines18618718818919019119219319429 unmodified lines22422522622722822923014 unmodified lines24524624724824925025125220 unmodified lines2732742752762772782793 unmodified lines2832842855 unmodified linesimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers import MegatronBertConfig, MegatronBertModel, MegatronBertForMaskedLM, MegatronBertPreTrainedModel, PreTrainedModelfrom transformers.modeling_outputs import SequenceClassifierOutputfrom transformers.utils.hub import cached_file#from prokbert.training_utils import compute_metrics_eval_predictionclass BertForBinaryClassificationWithPooling(nn.Module):"""ProkBERT model for binary classification with custom pooling.111 unmodified linesreturn modelclass ProkBertConfig(MegatronBertConfig):model_type = "prokbert"1 unmodified lineself,kmer: int = 6,shift: int = 1,num_labels: int = 2,classification_dropout_rate: float = 0.1,**kwargs,):super().__init__(**kwargs)self.kmer = kmerself.shift = shiftself.num_labels = num_labelsself.classification_dropout_rate = classification_dropout_rateclass ProkBertClassificationConfig(ProkBertConfig):model_type = "prokbert"30 unmodified linesif isinstance(module, nn.Linear) and module.bias is not None:module.bias.data.zero_()class ProkBertModel(MegatronBertModel):config_class = ProkBertConfig29 unmodified linesself.bert = ProkBertModel(config)self.weighting_layer = nn.Linear(self.config.hidden_size, 1)self.dropout = nn.Dropout(self.config.classification_dropout_rate)self.classifier = nn.Linear(self.config.hidden_size, self.config.num_labels)self.loss_fct = torch.nn.CrossEntropyLoss()self.post_init()14 unmodified linesr"""labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If`config.num_labels > 1` a classification loss is computed (Cross-Entropy)."""return_dict = return_dict if return_dict is not None else self.config.use_return_dict20 unmodified lineslogits = self.classifier(pooled_output)loss = Noneif labels is not None:loss = self.loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))classification_output = SequenceClassifierOutput(loss=loss,3 unmodified lines)return classification_output5 unmodified lines678910111213141516171819202122232425262728293031111 unmodified lines1431441451461471481 unmodified line15015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418530 unmodified lines21621721821922022129 unmodified lines25125225325425525625714 unmodified lines27227327427527627727827920 unmodified lines3003013023033043053063 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954965 unmodified linesimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn.parameter import Parameterfrom transformers import MegatronBertConfig, MegatronBertModel, MegatronBertForMaskedLM, MegatronBertPreTrainedModel, PreTrainedModelfrom transformers.modeling_outputs import SequenceClassifierOutputfrom transformers.utils.hub import cached_fileimport math#from prokbert.training_utils import compute_metrics_eval_predictiondef l2_norm(input, axis=1, epsilon=1e-12):norm = torch.norm(input, 2, axis, True)norm = torch.clamp(norm, min=epsilon) # Avoid zero divisionoutput = torch.div(input, norm)return outputdef initialize_linear_kaiming(layer: nn.Linear):if isinstance(layer, nn.Linear):nn.init.kaiming_uniform_(layer.weight, nonlinearity='linear')if layer.bias is not None:nn.init.zeros_(layer.bias)class BertForBinaryClassificationWithPooling(nn.Module):"""ProkBERT model for binary classification with custom pooling.111 unmodified linesreturn modelclass ProkBertConfig(MegatronBertConfig):model_type = "prokbert"1 unmodified lineself,kmer: int = 6,shift: int = 1,num_class_labels: int = 2,classification_dropout_rate: float = 0.1,**kwargs,):super().__init__(**kwargs)self.kmer = kmerself.shift = shiftself.num_class_labels = num_class_labelsself.classification_dropout_rate = classification_dropout_rateclass ProkBertConfigCurr(ProkBertConfig):model_type = "prokbert"def __init__(self,bert_base_model = "neuralbioinfo/prokbert-mini",curricular_face_m = 0.5,curricular_face_s=64.,curricular_num_labels = 2,curriculum_hidden_size = -1,classification_dropout_rate = 0.0,**kwargs,):super().__init__( **kwargs)self.curricular_num_labels = curricular_num_labelsself.curricular_face_m = curricular_face_mself.curricular_face_s = curricular_face_sself.bert_base_model = bert_base_modelself.curriculum_hidden_size = curriculum_hidden_sizeself.classification_dropout_rate = classification_dropout_rateclass ProkBertClassificationConfig(ProkBertConfig):model_type = "prokbert"30 unmodified linesif isinstance(module, nn.Linear) and module.bias is not None:module.bias.data.zero_()class ProkBertModel(MegatronBertModel):config_class = ProkBertConfig29 unmodified linesself.bert = ProkBertModel(config)self.weighting_layer = nn.Linear(self.config.hidden_size, 1)self.dropout = nn.Dropout(self.config.classification_dropout_rate)self.classifier = nn.Linear(self.config.hidden_size, self.config.num_class_labels)self.loss_fct = torch.nn.CrossEntropyLoss()self.post_init()14 unmodified linesr"""labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,config.num_labels - 1]`. If `config.num_class_labels == 1` a regression loss is computed (Mean-Square loss), If`config.num_class_labels > 1` a classification loss is computed (Cross-Entropy)."""return_dict = return_dict if return_dict is not None else self.config.use_return_dict20 unmodified lineslogits = self.classifier(pooled_output)loss = Noneif labels is not None:loss = self.loss_fct(logits.view(-1, self.config.num_class_labels), labels.view(-1))classification_output = SequenceClassifierOutput(loss=loss,3 unmodified lines)return classification_outputclass CurricularFace(nn.Module):def __init__(self, in_features, out_features, m=0.5, s=64.):super(CurricularFace, self).__init__()self.in_features = in_featuresself.out_features = out_featuresself.m = mself.s = sself.cos_m = math.cos(m)self.sin_m = math.sin(m)self.threshold = math.cos(math.pi - m)self.mm = math.sin(math.pi - m) * mself.kernel = Parameter(torch.Tensor(in_features, out_features))self.register_buffer('t', torch.zeros(1))def forward(self, embeddings, label):# Normalize embeddings and the classifier kernelembeddings = l2_norm(embeddings, axis=1)kernel_norm = l2_norm(self.kernel, axis=0)# Compute cosine similarity between embeddings and kernel columnscos_theta = torch.mm(embeddings, kernel_norm)cos_theta = cos_theta.clamp(-1, 1) # for numerical stability# print(f"cos theta")# print(cos_theta)# Clone original cosine values (used later for analysis if needed)with torch.no_grad():origin_cos = cos_theta.clone()# Get the cosine values corresponding to the ground-truth classestarget_logit = cos_theta[torch.arange(0, embeddings.size(0)), label].view(-1, 1)sin_theta = torch.sqrt(1.0 - torch.pow(target_logit, 2))cos_theta_m = target_logit * self.cos_m - sin_theta * self.sin_m # cos(target + margin)# Create a mask for positions where the cosine similarity exceeds the modified valuemask = (cos_theta > cos_theta_m) #.to(dtype=torch.uint8)# Apply the margin condition: for values greater than threshold, use cosine with margin;# otherwise subtract a fixed term.final_target_logit = torch.where(target_logit > self.threshold,cos_theta_m,target_logit - self.mm)# Update the buffer 't' (used to control the weight of hard examples)with torch.no_grad():self.t = target_logit.mean() * 0.01 + (1 - 0.01) * self.t# For the positions in the mask, re-scale the logitstry:hard_example = cos_theta[mask]except Exception as e:print("Label max")print(torch.max(label))print("Shapes:")print(embeddings.shape)print(label.shape)hard_example = cos_theta[mask]cos_theta[mask] = hard_example * (self.t + hard_example)# Replace the logits of the target classes with the modified target logitfinal_target_logit = final_target_logit.to(cos_theta.dtype)cos_theta.scatter_(1, label.view(-1, 1).long(), final_target_logit)output = cos_theta * self.sreturn output, origin_cos * self.sclass ProkBertForCurricularClassification(ProkBertPreTrainedModel):config_class = ProkBertConfigCurrbase_model_prefix = "bert"def __init__(self, config):super().__init__(config)self.config = configself.bert = ProkBertModel(config)# A weighting layer for pooling the sequence outputself.weighting_layer = nn.Linear(self.config.hidden_size, 1)self.dropout = nn.Dropout(self.config.classification_dropout_rate)if config.curriculum_hidden_size != -1:self.linear = nn.Linear(self.config.hidden_size, config.curriculum_hidden_size)# Replace the simple classifier with the CurricularFace head.# Defaults m=0.5 and s=64 are used, but these can be adjusted if needed.self.curricular_face = CurricularFace(config.curriculum_hidden_size,self.config.curricular_num_labels,m=self.config.curricular_face_m,s=self.config.curricular_face_s)else:self.linear = nn.Identity()self.curricular_face = CurricularFace(self.config.hidden_size,self.config.curricular_num_labels,m=self.config.curricular_face_m,s=self.config.curricular_face_s)self.loss_fct = torch.nn.CrossEntropyLoss()self.post_init()def _init_weights(self, module: nn.Module):# first let the base class init everything elsesuper()._init_weights(module)# then catch our pooling head and zero itif module is getattr(self, "weighting_layer", None):nn.init.xavier_uniform_(module.weight)nn.init.zeros_(module.bias)if module is getattr(self, "linear", None):initialize_linear_kaiming(module)if module is getattr(self, "curricular_face", None):nn.init.kaiming_uniform_(module.kernel, a=math.sqrt(self.config.curricular_num_labels))def forward(self,input_ids: Optional[torch.LongTensor] = None,attention_mask: Optional[torch.FloatTensor] = None,token_type_ids: Optional[torch.LongTensor] = None,position_ids: Optional[torch.LongTensor] = None,head_mask: Optional[torch.FloatTensor] = 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, SequenceClassifierOutput]:return_dict = return_dict if return_dict is not None else self.config.use_return_dict# Get the outputs from the base ProkBert modeloutputs = 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,output_attentions=output_attentions,output_hidden_states=output_hidden_states,return_dict=return_dict,)sequence_output = outputs[0] # (batch_size, seq_length, hidden_size)# Pool the sequence output using a learned weighting (attention-like)weights = self.weighting_layer(sequence_output) # (batch_size, seq_length, 1)# Ensure mask shape matchesif attention_mask.dim() == 2:mask = attention_maskelif attention_mask.dim() == 4:mask = attention_mask.squeeze(1).squeeze(1) # (batch_size, seq_length)else:raise ValueError(f"Unexpected attention_mask shape {attention_mask.shape}")# Apply mask (masked positions -> -inf before softmax)weights = weights.masked_fill(mask.unsqueeze(-1) == 0, float('-inf'))# Normalizeweights = torch.nn.functional.softmax(weights, dim=1) # (batch_size, seq_length)# Weighted pooling#weights = weights.unsqueeze(-1) # (batch_size, seq_length, 1)pooled_output = torch.sum(weights * sequence_output, dim=1) # (batch_size, hidden_size)# Classifier headpooled_output = self.dropout(pooled_output)pooled_output = self.linear(pooled_output)# CurricularFace requires the embeddings and the corresponding labels.# Note: During inference (labels is None), we just return l2 norm of bert part of the modelif labels is None:return l2_norm(pooled_output, axis = 1)else:logits, origin_cos = self.curricular_face(pooled_output, labels)loss = Noneif labels is not None:loss = self.loss_fct(logits, labels.view(-1))return SequenceClassifierOutput(loss=loss,logits=logits,hidden_states=outputs.hidden_states,attentions=outputs.attentions,)
models.py+224-13