MCPcopy Create free account
hub / github.com/AnswerDotAI/ModernBERT / FlexBertUnpadEncoder

Class FlexBertUnpadEncoder

src/bert_layers/layers.py:613–662  ·  view source on GitHub ↗

A stack of BERT layers providing the backbone of FlexBERT. This module is modeled after the Hugging Face BERT's :class:`~transformers.model.bert.modeling_bert.BertAlibiEncoder`, but with substantial modifications to implement unpadding and ALiBi. Compared to the analogous Hugging Face

Source from the content-addressed store, hash-verified

611
612
613class FlexBertUnpadEncoder(FlexBertEncoderBase):
614 """A stack of BERT layers providing the backbone of FlexBERT.
615
616 This module is modeled after the Hugging Face BERT's :class:`~transformers.model.bert.modeling_bert.BertAlibiEncoder`,
617 but with substantial modifications to implement unpadding and ALiBi.
618
619 Compared to the analogous Hugging Face BERT module, this module handles unpadding to reduce unnecessary computation
620 at padded tokens, and pre-computes attention biases to implement ALiBi.
621 """
622
623 def __init__(self, config: FlexBertConfig):
624 super().__init__()
625 self.layers = nn.ModuleList([get_bert_layer(config, layer_id=i) for i in range(config.num_hidden_layers)])
626 self.num_attention_heads = config.num_attention_heads
627
628 def forward(
629 self,
630 hidden_states: torch.Tensor,
631 attention_mask: torch.Tensor,
632 indices: Optional[torch.Tensor] = None,
633 cu_seqlens: Optional[torch.Tensor] = None,
634 max_seqlen: Optional[int] = None,
635 ) -> torch.Tensor:
636 if indices is None and cu_seqlens is None and max_seqlen is None:
637 attention_mask_bool = attention_mask.bool()
638 batch, seqlen = hidden_states.shape[:2]
639 hidden_states, indices, cu_seqlens, max_seqlen = bert_padding.unpad_input(
640 hidden_states, attention_mask_bool
641 )
642
643 for layer_module in self.layers:
644 hidden_states = layer_module(
645 hidden_states,
646 cu_seqlens,
647 max_seqlen,
648 indices,
649 attn_mask=attention_mask,
650 )
651
652 return bert_padding.pad_input(hidden_states, indices, batch, seqlen)
653 else:
654 for layer_module in self.layers:
655 hidden_states = layer_module(
656 hidden_states,
657 cu_seqlens,
658 max_seqlen,
659 indices,
660 attn_mask=attention_mask,
661 )
662 return hidden_states
663
664
665class FlexBertPaddedEncoder(FlexBertEncoderBase):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected