Fill-Mask
Transformers
Safetensors
bert
rna
biology
bioinformatics
foundation-model
secondary-structure
custom_code
Run this model with HF Jobs
Run hunterkun/NvwaRNA-650M 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/hunterkun/NvwaRNA-650M. 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/hunterkun/NvwaRNA-650M 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 hunterkun/NvwaRNA-650M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use hunterkun/NvwaRNA-650M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="hunterkun/NvwaRNA-650M", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForMaskedLM tokenizer = AutoTokenizer.from_pretrained("hunterkun/NvwaRNA-650M", trust_remote_code=True) model = AutoModelForMaskedLM.from_pretrained("hunterkun/NvwaRNA-650M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download modeling_flexbert.py from hunterkun/NvwaRNA-650M: direct link, hf CLI and curl.
- Browser
- Download file 53.6 kB
-
https://huggingface.co/hunterkun/NvwaRNA-650M/resolve/main/modeling_flexbert.py
- Command line
-
hf download hf://hunterkun/NvwaRNA-650M/modeling_flexbert.py
-
curl -L -o modeling_flexbert.py https://huggingface.co/hunterkun/NvwaRNA-650M/resolve/main/modeling_flexbert.py
53.6 kB
# Copyright 2024 onwards Answer.AI, LightOn, and contributors
# License: Apache-2.0
# Minimal self-contained FlexBERT implementation for inference
import inspect
import math
import warnings
from collections import OrderedDict
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
import transformers
from transformers import BertConfig as TransformersBertConfig
from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput, ModelOutput
from transformers.models.bert.modeling_bert import BertPreTrainedModel
_TRANSFORMERS_MAJOR = int(transformers.__version__.split(".")[0])
# Try to import flash attention
IMPL_USE_FLASH2 = False
try:
from flash_attn import flash_attn_varlen_qkvpacked_func, flash_attn_qkvpacked_func
import importlib.metadata
installed_version = importlib.metadata.version("flash_attn")
if installed_version >= "2.5.7":
IMPL_USE_FLASH2 = True
except ImportError:
pass
try:
from flash_attn.layers.rotary import RotaryEmbedding
from flash_attn.ops.triton.rotary import apply_rotary
HAS_FLASH_ROTARY = True
except ImportError:
RotaryEmbedding = None
apply_rotary = None
HAS_FLASH_ROTARY = False
try:
from flash_attn.ops.triton.layer_norm import RMSNorm as TritonRMSNorm
except ImportError:
TritonRMSNorm = None
# ============================================================================
# Configuration
# ============================================================================
class FlexBertConfig(TransformersBertConfig):
def __init__(
self,
attention_layer: str = "base",
attention_probs_dropout_prob: float = 0.0,
attn_out_bias: bool = False,
attn_out_dropout_prob: float = 0.0,
attn_qkv_bias: bool = False,
bert_layer: str = "prenorm",
decoder_bias: bool = True,
embed_dropout_prob: float = 0.0,
embed_norm: bool = True,
final_norm: bool = False,
embedding_layer: str = "absolute_pos",
encoder_layer: str = "base",
loss_function: str = "cross_entropy",
loss_kwargs: dict = {},
mlp_dropout_prob: float = 0.0,
mlp_in_bias: bool = False,
mlp_layer: str = "mlp",
mlp_out_bias: bool = False,
norm_kwargs: dict = {},
normalization: str = "rmsnorm",
padding: str = "unpadded",
head_class_act: str = "silu",
head_class_bias: bool = False,
head_class_dropout: float = 0.0,
head_class_norm: str = False,
head_pred_act: str = "silu",
head_pred_bias: bool = False,
head_pred_dropout: float = 0.0,
head_pred_norm: bool = True,
pooling_type: str = "cls",
rotary_emb_dim: int | None = None,
rotary_emb_base: float = 10000.0,
rotary_emb_scale_base=None,
rotary_emb_interleaved: bool = False,
use_fa2: bool = True,
use_sdpa_attn_mask: bool = False,
allow_embedding_resizing: bool = False,
init_method: str = "default",
init_std: float = 0.02,
init_cutoff_factor: float = 2.0,
init_small_embedding: bool = False,
initial_attention_layer: str | None = None,
initial_bert_layer: str | None = None,
initial_mlp_layer: str | None = None,
num_initial_layers: int = 1,
skip_first_prenorm: bool = False,
deterministic_fa2: bool = False,
sliding_window: int = -1,
global_attn_every_n_layers: int = -1,
local_attn_rotary_emb_base: float = -1,
local_attn_rotary_emb_dim: int | None = None,
unpad_embeddings: bool = False,
pad_logits: bool = False,
compile_model: bool = False,
masked_prediction: bool = False,
**kwargs,
):
super().__init__(attention_probs_dropout_prob=attention_probs_dropout_prob, **kwargs)
self.attention_layer = attention_layer
self.attn_out_bias = attn_out_bias
self.attn_out_dropout_prob = attn_out_dropout_prob
self.attn_qkv_bias = attn_qkv_bias
self.bert_layer = bert_layer
self.decoder_bias = decoder_bias
self.embed_dropout_prob = embed_dropout_prob
self.embed_norm = embed_norm
self.final_norm = final_norm
self.embedding_layer = embedding_layer
self.encoder_layer = encoder_layer
self.loss_function = loss_function
self.loss_kwargs = loss_kwargs
self.mlp_dropout_prob = mlp_dropout_prob
self.mlp_in_bias = mlp_in_bias
self.mlp_layer = mlp_layer
self.mlp_out_bias = mlp_out_bias
self.norm_kwargs = norm_kwargs
self.normalization = normalization
self.padding = padding
self.head_class_act = head_class_act
self.head_class_bias = head_class_bias
self.head_class_dropout = head_class_dropout
self.head_class_norm = head_class_norm
self.head_pred_act = head_pred_act
self.head_pred_bias = head_pred_bias
self.head_pred_dropout = head_pred_dropout
self.head_pred_norm = head_pred_norm
self.pooling_type = pooling_type
self.rotary_emb_dim = rotary_emb_dim
self.rotary_emb_base = rotary_emb_base
self.rotary_emb_scale_base = rotary_emb_scale_base
self.rotary_emb_interleaved = rotary_emb_interleaved
self.use_fa2 = use_fa2
self.use_sdpa_attn_mask = use_sdpa_attn_mask
self.allow_embedding_resizing = allow_embedding_resizing
self.init_method = init_method
self.init_std = init_std
self.init_cutoff_factor = init_cutoff_factor
self.init_small_embedding = init_small_embedding
self.initial_attention_layer = initial_attention_layer
self.initial_bert_layer = initial_bert_layer
self.initial_mlp_layer = initial_mlp_layer
self.num_initial_layers = num_initial_layers
self.skip_first_prenorm = skip_first_prenorm
self.deterministic_fa2 = deterministic_fa2
self.sliding_window = sliding_window
self.global_attn_every_n_layers = global_attn_every_n_layers
self.local_attn_rotary_emb_base = local_attn_rotary_emb_base
self.local_attn_rotary_emb_dim = local_attn_rotary_emb_dim
self.unpad_embeddings = unpad_embeddings
self.pad_logits = pad_logits
self.compile_model = compile_model
self.masked_prediction = masked_prediction
PADDING = ["unpadded", "padded"]
def maybe_add_padding(config: FlexBertConfig, config_option: str) -> str:
if config.padding not in PADDING:
raise ValueError(f"Invalid padding type: {config.padding}, must be one of {PADDING}")
if not any(config_option.startswith(pad + "_") for pad in PADDING):
config_option = f"{config.padding}_{config_option}"
return config_option
# ============================================================================
# Activation Functions
# ============================================================================
class ClassInstantier(OrderedDict):
def __getitem__(self, key):
content = super().__getitem__(key)
cls, kwargs = content if isinstance(content, tuple) else (content, {})
return cls(**kwargs)
ACT2CLS = {
"celu": nn.CELU, "elu": nn.ELU, "gelu": nn.GELU,
"gelu_tanh": (nn.GELU, {"approximate": "tanh"}),
"hardtanh": nn.Hardtanh, "hardsigmoid": nn.Hardsigmoid,
"hardshrink": nn.Hardshrink, "hardswish": nn.Hardswish,
"leaky_relu": nn.LeakyReLU, "logsigmoid": nn.LogSigmoid,
"mish": nn.Mish, "prelu": nn.PReLU, "relu": nn.ReLU,
"relu6": nn.ReLU6, "rrelu": nn.RReLU, "selu": nn.SELU,
"sigmoid": nn.Sigmoid, "silu": nn.SiLU, "softmin": nn.Softmin,
"softplus": nn.Softplus, "softshrink": nn.Softshrink,
"softsign": nn.Softsign, "swish": nn.SiLU, "tanh": nn.Tanh,
"tanhshrink": nn.Tanhshrink, "threshold": nn.Threshold,
}
ACT2FN = ClassInstantier(ACT2CLS)
def get_act_fn(config: Union[FlexBertConfig, str]) -> nn.Module:
if isinstance(config, str):
return ACT2FN[config]
return ACT2FN[config.hidden_act]
# ============================================================================
# Normalization
# ============================================================================
class RMSNorm(nn.Module):
"""Llama2 RMSNorm implementation"""
def __init__(self, dim: int, eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float()).type_as(x)
return output * self.weight
def reset_parameters(self):
nn.init.ones_(self.weight)
NORM2CLS = {
"layernorm": nn.LayerNorm,
"rmsnorm": RMSNorm,
"triton_rmsnorm": TritonRMSNorm if TritonRMSNorm is not None else RMSNorm,
}
def get_norm_layer(config: FlexBertConfig, compiled_norm: bool = False) -> nn.Module:
norm = config.normalization
if compiled_norm and norm.startswith("triton_"):
norm = norm.replace("triton_", "")
signature = inspect.signature(NORM2CLS.get(norm, RMSNorm))
norm_kwargs = {k: v for k, v in getattr(config, 'norm_kwargs', {}).items() if k in signature.parameters}
return NORM2CLS.get(norm, RMSNorm)(config.hidden_size, **norm_kwargs)
# ============================================================================
# Padding utilities
# ============================================================================
def unpad_input(hidden_states: torch.Tensor, attention_mask: torch.Tensor):
"""Remove padding from input sequences."""
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
max_seqlen_in_batch = seqlens_in_batch.max().item()
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])[indices]
return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
def pad_input(hidden_states: torch.Tensor, indices: torch.Tensor, batch: int, seqlen: int):
"""Add padding back to sequences (supports arbitrary trailing dimensions)."""
output = torch.zeros(
batch * seqlen,
*hidden_states.shape[1:],
device=hidden_states.device,
dtype=hidden_states.dtype,
)
output[indices] = hidden_states
return output.view(batch, seqlen, *hidden_states.shape[1:])
def index_put_first_axis(values: torch.Tensor, indices: torch.Tensor, first_axis_dim: int) -> torch.Tensor:
output = torch.zeros(first_axis_dim, *values.shape[1:], device=values.device, dtype=values.dtype)
output[indices] = values
return output
# ============================================================================
# Rotary Embeddings
# ============================================================================
class ApplyRotaryEmbUnpad(torch.autograd.Function):
"""Apply rotary embeddings to unpadded sequences using triton."""
@staticmethod
def forward(ctx, qkv, cos, sin, cu_seqlens=None, max_seqlen=None):
# qkv: (total_nnz, 3, nheads, headdim)
total_nnz, three, nheads, headdim = qkv.shape
assert three == 3
qkv = qkv.contiguous()
qk = qkv[:, :2].view(total_nnz, -1, headdim)
apply_rotary(
qk, cos, sin,
seqlen_offsets=0,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
interleaved=False,
inplace=True,
)
ctx.save_for_backward(cos, sin, cu_seqlens)
ctx.max_seqlen = max_seqlen
return qkv
@staticmethod
def backward(ctx, do):
cos, sin, cu_seqlens = ctx.saved_tensors
do = do.contiguous()
total_nnz, three, nheads, headdim = do.shape
dqk = do[:, :2].view(total_nnz, -1, headdim)
apply_rotary(
dqk, cos, sin,
seqlen_offsets=0,
cu_seqlens=cu_seqlens,
max_seqlen=ctx.max_seqlen,
interleaved=False,
inplace=True,
conjugate=True,
)
return do, None, None, None, None
class UnpaddedRotaryEmbedding(nn.Module):
"""Rotary position embeddings for unpadded sequences.
Matches the original flash_attn-based implementation.
"""
def __init__(
self,
dim: int,
base: float = 10000.0,
interleaved: bool = False,
max_seqlen: Optional[int] = None,
scale_base: Optional[float] = None,
pos_idx_in_fp32: bool = True,
device=None,
dtype=None,
):
super().__init__()
self.dim = dim
self.base = float(base)
self.pos_idx_in_fp32 = pos_idx_in_fp32
self.interleaved = interleaved
self.scale_base = scale_base
# Generate and save the inverse frequency buffer (non trainable)
inv_freq = self._compute_inv_freq(device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
scale = (
(torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)
if scale_base is not None
else None
)
self.register_buffer("scale", scale, persistent=False)
self._seq_len_cached = 0
self._cos_cached = None
self._sin_cached = None
self._cos_k_cached = None
self._sin_k_cached = None
if max_seqlen is not None and device is not None and dtype is not None:
self._update_cos_sin_cache(max_seqlen, device=device, dtype=dtype)
def _compute_inv_freq(self, device=None):
return 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
if (
seqlen > self._seq_len_cached
or self._cos_cached is None
or self._cos_cached.device != device
or self._cos_cached.dtype != dtype
or (self.training and self._cos_cached.is_inference())
):
self._seq_len_cached = seqlen
if self.pos_idx_in_fp32:
t = torch.arange(seqlen, device=device, dtype=torch.float32)
if self.inv_freq.dtype != torch.float32:
inv_freq = self._compute_inv_freq(device=device)
else:
inv_freq = self.inv_freq
else:
t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
inv_freq = self.inv_freq
freqs = torch.outer(t, inv_freq)
if self.scale is None:
self._cos_cached = torch.cos(freqs).to(dtype)
self._sin_cached = torch.sin(freqs).to(dtype)
else:
power = (
torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) - seqlen // 2
) / self.scale_base
scale = self.scale.to(device=power.device) ** power.unsqueeze(1)
self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
def forward(
self,
qkv: torch.Tensor,
cu_seqlens: torch.Tensor,
max_seqlen: int,
seqlen_offset: int = 0,
):
"""
qkv: (total_nnz, 3, nheads, headdim)
cu_seqlens: (batch + 1,) cumulative sequence lengths
max_seqlen: int max seq length in the batch
seqlen_offset: int offset for KV cache inference
"""
if max_seqlen is not None:
self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
if HAS_FLASH_ROTARY and qkv.is_cuda:
return ApplyRotaryEmbUnpad.apply(
qkv, self._cos_cached, self._sin_cached, cu_seqlens, max_seqlen
)
else:
# Fallback: pure PyTorch implementation
return self._apply_rotary_pytorch(qkv, cu_seqlens, max_seqlen)
def _apply_rotary_pytorch(self, qkv, cu_seqlens, max_seqlen):
"""Pure PyTorch fallback for rotary embeddings (matches flash_attn apply_rotary)."""
q, k, v = qkv.unbind(dim=1)
# Create position ids for packed sequences
position_ids = torch.zeros(qkv.shape[0], dtype=torch.long, device=qkv.device)
for i in range(len(cu_seqlens) - 1):
start, end = cu_seqlens[i].item(), cu_seqlens[i + 1].item()
position_ids[start:end] = torch.arange(end - start, device=qkv.device)
# _cos_cached/_sin_cached have shape (seqlen, dim // 2); duplicate to match full head dim
cos_half = self._cos_cached[position_ids].unsqueeze(1)
sin_half = self._sin_cached[position_ids].unsqueeze(1)
cos = torch.cat([cos_half, cos_half], dim=-1)
sin = torch.cat([sin_half, sin_half], dim=-1)
# Apply rotary embedding
q_embed = (q * cos) + (self._rotate_half(q) * sin)
k_embed = (k * cos) + (self._rotate_half(k) * sin)
return torch.stack([q_embed, k_embed, v], dim=1)
def _rotate_half(self, x):
x1, x2 = x.chunk(2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
def extra_repr(self) -> str:
return f"dim={self.dim}, base={self.base}, scale_base={self.scale_base}"
# ============================================================================
# Attention
# ============================================================================
class FlexBertAttentionBase(nn.Module):
"""Base class for FlexBERT attention."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__()
self.config = config
self.layer_id = layer_id
def _init_weights(self, reset_params: bool = False):
raise NotImplementedError
def forward(self, hidden_states: torch.Tensor, **kwargs) -> torch.Tensor:
raise NotImplementedError
def extra_repr(self) -> str:
repr_str = ""
if hasattr(self, "num_attention_heads"):
repr_str += f"num_attention_heads={self.num_attention_heads}"
if hasattr(self, "attn_head_size"):
repr_str += f", attn_head_size={self.attn_head_size}"
if hasattr(self, "sliding_window"):
repr_str += f", sliding_window={self.sliding_window if self.sliding_window != (-1, -1) else False}"
if hasattr(self, "use_fa2"):
repr_str += f", use_fa2={self.use_fa2}"
if hasattr(self, "deterministic_fa2"):
repr_str += f", deterministic_fa2={self.deterministic_fa2}"
return repr_str
class FlexBertUnpadRopeAttention(FlexBertAttentionBase):
"""FlexBERT attention with rotary embeddings for unpadded sequences."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__(config, layer_id)
self.num_attention_heads = config.num_attention_heads
self.attn_head_size = config.hidden_size // config.num_attention_heads
self.all_head_size = self.num_attention_heads * self.attn_head_size
self.p_dropout = config.attention_probs_dropout_prob
self.deterministic_fa2 = config.deterministic_fa2
self.Wqkv = nn.Linear(config.hidden_size, 3 * self.all_head_size, bias=config.attn_qkv_bias)
self.Wo = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attn_out_bias)
self.out_drop = nn.Dropout(config.attn_out_dropout_prob) if config.attn_out_dropout_prob > 0 else nn.Identity()
# Sliding window configuration - must be set before rotary embeddings
# Original logic: layer_id % global_attn_every_n_layers == 0 means global attention
if config.global_attn_every_n_layers > 0:
if config.sliding_window == -1:
raise ValueError("global_attn_every_n_layers requires sliding_window to be set")
if layer_id % config.global_attn_every_n_layers != 0:
self.sliding_window = (config.sliding_window // 2, config.sliding_window // 2)
else:
self.sliding_window = (-1, -1)
else:
self.sliding_window = (config.sliding_window // 2, config.sliding_window // 2)
# Rotary embeddings configuration
if config.rotary_emb_dim is None:
config.rotary_emb_dim = self.attn_head_size
rotary_base = config.rotary_emb_base
rotary_dim = config.rotary_emb_dim
# Use different rotary settings for local (sliding window) attention
if self.sliding_window != (-1, -1):
if config.local_attn_rotary_emb_base != -1:
rotary_base = config.local_attn_rotary_emb_base
if config.local_attn_rotary_emb_dim is not None:
rotary_dim = config.local_attn_rotary_emb_dim
# Use UnpaddedRotaryEmbedding which supports cu_seqlens for packed sequences
self.rotary_emb = UnpaddedRotaryEmbedding(
dim=rotary_dim,
base=rotary_base,
scale_base=config.rotary_emb_scale_base,
interleaved=config.rotary_emb_interleaved,
)
self.use_fa2 = config.use_fa2
self.use_sdpa_attn_mask = config.use_sdpa_attn_mask
# Warn if defaulting to pytorch because of import issues
if not IMPL_USE_FLASH2 and self.use_fa2:
warnings.warn(
"Unable to import flash_attn; defaulting FlexBERT attention implementation to PyTorch's"
" SDPA kernel. This requires padding and unpadding inputs, which will add some overhead."
)
self.use_fa2 = False
def _init_weights(self, reset_params: bool = False):
pass # Simplified for inference
def _build_sdpa_mask(
self,
batch_size: int,
seqlen: int,
attn_mask: Optional[torch.Tensor],
device: torch.device,
) -> Optional[torch.Tensor]:
"""Build boolean attention mask (B, 1, S, S) combining padding and sliding window."""
mask = None
if attn_mask is not None:
key_valid = attn_mask[:, None, None, :seqlen].to(dtype=torch.bool, device=device)
mask = key_valid.expand(batch_size, 1, seqlen, seqlen)
if self.sliding_window != (-1, -1):
w_left, w_right = self.sliding_window
pos = torch.arange(seqlen, device=device)
diff = pos.unsqueeze(0) - pos.unsqueeze(1) # diff[q, k] = k - q
win_mask = (diff >= -w_left) & (diff <= w_right)
win_mask = win_mask.unsqueeze(0).unsqueeze(0) # (1, 1, S, S)
mask = win_mask.expand(batch_size, 1, seqlen, seqlen) if mask is None else (mask & win_mask)
if mask is not None:
# Guard padded query rows against all-False masks that cause NaN in softmax
no_valid = ~mask.any(dim=-1, keepdim=True)
if no_valid.any():
eye = torch.eye(seqlen, dtype=torch.bool, device=device).unsqueeze(0).unsqueeze(0)
mask = mask | (no_valid & eye)
return mask
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor,
max_seqlen: int,
indices: Optional[torch.Tensor] = None,
attn_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
bs, dim = hidden_states.shape
qkv = self.Wqkv(hidden_states)
# only needed for inference when we have KV cache
seqlen_offset = 0
# (total_seqlen, 3, nheads, headdim)
qkv = qkv.view(-1, 3, self.num_attention_heads, self.attn_head_size)
qkv = self.rotary_emb(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, seqlen_offset=seqlen_offset)
attn_weights = None
if self.use_fa2 and IMPL_USE_FLASH2 and qkv.is_cuda and not output_attentions:
convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
if convert_dtype:
orig_dtype = qkv.dtype
qkv = qkv.to(torch.bfloat16)
attn = flash_attn_varlen_qkvpacked_func(
qkv,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
dropout_p=self.p_dropout if self.training else 0.0,
deterministic=self.deterministic_fa2,
window_size=self.sliding_window,
)
if convert_dtype:
attn = attn.to(orig_dtype)
attn = attn.view(bs, dim)
else:
# Standard attention fallback (CPU, non-FlashAttention, or output_attentions=True)
batch_size = cu_seqlens.shape[0] - 1
seqlen = attn_mask.shape[-1] if attn_mask is not None else max_seqlen
qkv_padded = pad_input(qkv, indices, batch_size, seqlen) # (B, S, 3, H, D)
q, k, v = qkv_padded.permute(0, 3, 2, 1, 4).unbind(dim=2) # each (B, H, S, D)
sdpa_mask = self._build_sdpa_mask(batch_size, seqlen, attn_mask, q.device)
if output_attentions:
scale = 1.0 / math.sqrt(self.attn_head_size)
scores = torch.matmul(q.float(), k.float().transpose(-2, -1)) * scale
if sdpa_mask is not None:
scores = scores.masked_fill(~sdpa_mask, float("-inf"))
attn_weights = F.softmax(scores, dim=-1)
if attn_mask is not None:
q_valid = attn_mask[:, None, :seqlen, None].to(dtype=attn_weights.dtype, device=attn_weights.device)
attn_weights = attn_weights * q_valid
attn = torch.matmul(attn_weights.to(v.dtype), v)
else:
attn = F.scaled_dot_product_attention(
q,
k,
v,
dropout_p=self.p_dropout if self.training else 0.0,
attn_mask=sdpa_mask,
)
attn = attn.transpose(1, 2).contiguous().view(batch_size * seqlen, dim)
attn = attn[indices] if indices is not None else attn.view(bs, dim)
out = self.out_drop(self.Wo(attn))
if output_attentions:
return out, attn_weights
return out
def extra_repr(self) -> str:
repr_str = f"num_attention_heads={self.num_attention_heads}"
repr_str += f", attn_head_size={self.attn_head_size}"
repr_str += f", sliding_window={self.sliding_window if self.sliding_window != (-1, -1) else False}"
repr_str += f", use_fa2={self.use_fa2}"
repr_str += f", deterministic_fa2={self.deterministic_fa2}"
return repr_str
class FlexBertPaddedRopeAttention(FlexBertAttentionBase):
"""FlexBERT attention with rotary embeddings for padded sequences."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__(config, layer_id)
self.num_attention_heads = config.num_attention_heads
self.attn_head_size = config.hidden_size // config.num_attention_heads
self.all_head_size = self.num_attention_heads * self.attn_head_size
self.p_dropout = config.attention_probs_dropout_prob
self.deterministic_fa2 = config.deterministic_fa2
self.Wqkv = nn.Linear(config.hidden_size, 3 * self.all_head_size, bias=config.attn_qkv_bias)
self.Wo = nn.Linear(config.hidden_size, config.hidden_size, bias=config.attn_out_bias)
self.out_drop = nn.Dropout(config.attn_out_dropout_prob) if config.attn_out_dropout_prob > 0 else nn.Identity()
self.use_fa2 = config.use_fa2
self.use_sdpa_attn_mask = config.use_sdpa_attn_mask
# Sliding window configuration
if config.global_attn_every_n_layers > 0:
if config.sliding_window == -1:
raise ValueError("global_attn_every_n_layers requires sliding_window to be set")
if layer_id % config.global_attn_every_n_layers != 0:
self.sliding_window = (config.sliding_window // 2, config.sliding_window // 2)
else:
self.sliding_window = (-1, -1)
else:
self.sliding_window = (config.sliding_window // 2, config.sliding_window // 2)
if config.rotary_emb_dim is None:
config.rotary_emb_dim = self.attn_head_size
rotary_base = config.rotary_emb_base
rotary_dim = config.rotary_emb_dim
if self.sliding_window != (-1, -1):
if config.local_attn_rotary_emb_base != -1:
rotary_base = config.local_attn_rotary_emb_base
if config.local_attn_rotary_emb_dim is not None:
rotary_dim = config.local_attn_rotary_emb_dim
# For padded attention, use flash_attn's RotaryEmbedding if available
if RotaryEmbedding is not None:
self.rotary_emb = RotaryEmbedding(
dim=rotary_dim,
base=rotary_base,
scale_base=config.rotary_emb_scale_base,
interleaved=config.rotary_emb_interleaved,
)
self._use_flash_rotary = True
else:
self.rotary_emb = None
self._use_flash_rotary = False
# Create cos/sin cache for manual application
self._rotary_dim = rotary_dim
self._rotary_base = rotary_base
if not IMPL_USE_FLASH2 and self.use_fa2:
self.use_fa2 = False
if not self.use_fa2 and self.sliding_window[0] > 0:
raise ValueError("Sliding window is not implemented for the PyTorch SDPA path. Use the FA2 backend.")
def _init_weights(self, reset_params: bool = False):
pass
def forward(
self,
hidden_states: torch.Tensor,
attn_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> torch.Tensor:
bs, seqlen, dim = hidden_states.shape
qkv = self.Wqkv(hidden_states)
seqlen_offset = 0
# Reshape to (batch, seqlen, 3, nheads, headdim)
qkv = qkv.view(bs, seqlen, 3, self.num_attention_heads, self.attn_head_size)
if self.use_fa2 and IMPL_USE_FLASH2:
# Apply RoPE
if self._use_flash_rotary:
qkv = self.rotary_emb(qkv, seqlen_offset=seqlen_offset, max_seqlen=None)
convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
if convert_dtype:
orig_dtype = qkv.dtype
qkv = qkv.to(torch.bfloat16)
attn = flash_attn_qkvpacked_func(
qkv,
dropout_p=self.p_dropout if self.training else 0.0,
deterministic=self.deterministic_fa2,
window_size=self.sliding_window,
)
if convert_dtype:
attn = attn.to(orig_dtype)
else:
# Apply rotary embeddings manually if flash rotary not available
if self._use_flash_rotary:
qkv = self.rotary_emb(qkv, seqlen_offset=seqlen_offset, max_seqlen=None)
q, k, v = qkv.transpose(3, 1).unbind(dim=2)
else:
q, k, v = qkv.unbind(dim=2)
# Create position-based cos/sin
position_ids = torch.arange(seqlen, device=hidden_states.device)
inv_freq = 1.0 / (self._rotary_base ** (torch.arange(0, self._rotary_dim, 2, device=hidden_states.device, dtype=torch.float32) / self._rotary_dim))
freqs = torch.outer(position_ids.float(), inv_freq)
cos = torch.cos(freqs).to(q.dtype).unsqueeze(0).unsqueeze(2)
sin = torch.sin(freqs).to(q.dtype).unsqueeze(0).unsqueeze(2)
def rotate_half(x):
x1, x2 = x.chunk(2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
q = (q * cos) + (rotate_half(q) * sin)
k = (k * cos) + (rotate_half(k) * sin)
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
attn = F.scaled_dot_product_attention(
q,
k,
v,
dropout_p=self.p_dropout if self.training else 0.0,
attn_mask=attn_mask[:, None, None, :seqlen].to(torch.bool).expand(bs, 1, seqlen, seqlen)
if self.use_sdpa_attn_mask and attn_mask is not None
else None,
).transpose(1, 2)
attn = attn.view(bs, seqlen, dim)
return self.out_drop(self.Wo(attn))
def extra_repr(self) -> str:
repr_str = f"num_attention_heads={self.num_attention_heads}"
repr_str += f", attn_head_size={self.attn_head_size}"
repr_str += f", sliding_window={self.sliding_window if self.sliding_window != (-1, -1) else False}"
repr_str += f", use_fa2={self.use_fa2}"
repr_str += f", deterministic_fa2={self.deterministic_fa2}"
return repr_str
def get_attention_layer(config: FlexBertConfig, layer_id: Optional[int] = None) -> FlexBertAttentionBase:
attention_layer = maybe_add_padding(config, config.attention_layer)
if "unpad" in attention_layer and "rope" in attention_layer:
return FlexBertUnpadRopeAttention(config, layer_id)
elif "rope" in attention_layer:
return FlexBertPaddedRopeAttention(config, layer_id)
else:
return FlexBertUnpadRopeAttention(config, layer_id) # default
# ============================================================================
# MLP
# ============================================================================
class FlexBertMLPBase(nn.Module):
"""Base class for FlexBERT MLP."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__()
self.config = config
self.layer_id = layer_id
def _init_weights(self, reset_params: bool = False):
raise NotImplementedError
class FlexBertMLP(FlexBertMLPBase):
"""Standard MLP for FlexBERT."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__(config, layer_id)
self.Wi = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_in_bias)
self.act = get_act_fn(config.hidden_act)
self.drop = nn.Dropout(config.mlp_dropout_prob) if config.mlp_dropout_prob > 0 else nn.Identity()
self.Wo = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_out_bias)
def _init_weights(self, reset_params: bool = False):
pass
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.Wo(self.drop(self.act(self.Wi(hidden_states))))
class FlexBertGLU(FlexBertMLPBase):
"""GLU-based MLP for FlexBERT."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__(config, layer_id)
self.Wi = nn.Linear(config.hidden_size, config.intermediate_size * 2, bias=config.mlp_in_bias)
self.act = get_act_fn(config.hidden_act)
self.drop = nn.Dropout(config.mlp_dropout_prob) if config.mlp_dropout_prob > 0 else nn.Identity()
self.Wo = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_out_bias)
def _init_weights(self, reset_params: bool = False):
pass
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
input, gate = self.Wi(hidden_states).chunk(2, dim=-1)
return self.Wo(self.drop(self.act(input) * gate))
def get_mlp_layer(config: FlexBertConfig, layer_id: Optional[int] = None) -> FlexBertMLPBase:
if "glu" in config.mlp_layer:
return FlexBertGLU(config, layer_id)
return FlexBertMLP(config, layer_id)
# ============================================================================
# Encoder Layers
# ============================================================================
class FlexBertLayerBase(nn.Module):
"""Base class for FlexBERT encoder layers."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__()
self.config = config
self.layer_id = layer_id
def _init_weights(self, reset_params: bool = False):
if hasattr(self, "attn"):
self.attn._init_weights(reset_params)
if hasattr(self, "mlp"):
self.mlp._init_weights(reset_params)
class FlexBertUnpadPreNormLayer(FlexBertLayerBase):
"""FlexBERT layer with pre-normalization for unpadded sequences."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__(config, layer_id)
if config.skip_first_prenorm and config.embed_norm and layer_id == 0:
self.attn_norm = nn.Identity()
else:
self.attn_norm = get_norm_layer(config)
self.attn = get_attention_layer(config, layer_id)
self.mlp_norm = get_norm_layer(config)
self.mlp = get_mlp_layer(config, layer_id)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor,
max_seqlen: int,
indices: Optional[torch.Tensor] = None,
attn_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
attn_res = self.attn(
self.attn_norm(hidden_states),
cu_seqlens,
max_seqlen,
indices,
attn_mask,
output_attentions=output_attentions,
)
if output_attentions:
attn_out, attn_weights = attn_res
else:
attn_out, attn_weights = attn_res, None
hidden_states = hidden_states + attn_out
mlp_out = self.mlp(self.mlp_norm(hidden_states))
out = hidden_states + mlp_out
if output_attentions:
return out, attn_weights
return out
class FlexBertPaddedPreNormLayer(FlexBertLayerBase):
"""FlexBERT layer with pre-normalization for padded sequences."""
def __init__(self, config: FlexBertConfig, layer_id: Optional[int] = None):
super().__init__(config, layer_id)
if config.skip_first_prenorm and config.embed_norm and layer_id == 0:
self.attn_norm = nn.Identity()
else:
self.attn_norm = get_norm_layer(config)
self.attn = get_attention_layer(config, layer_id)
self.mlp_norm = get_norm_layer(config)
self.mlp = get_mlp_layer(config, layer_id)
def forward(
self,
hidden_states: torch.Tensor,
attn_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> torch.Tensor:
attn_out = self.attn(self.attn_norm(hidden_states), attn_mask=attn_mask)
hidden_states = hidden_states + attn_out
mlp_out = self.mlp(self.mlp_norm(hidden_states))
return hidden_states + mlp_out
def get_encoder_layer(config: FlexBertConfig, layer_id: Optional[int] = None) -> FlexBertLayerBase:
bert_layer = maybe_add_padding(config, config.bert_layer)
if "unpad" in bert_layer:
return FlexBertUnpadPreNormLayer(config, layer_id)
return FlexBertPaddedPreNormLayer(config, layer_id)
# ============================================================================
# Encoder
# ============================================================================
class FlexBertEncoderBase(nn.Module):
"""Base class for FlexBERT encoder."""
def __init__(self, config: FlexBertConfig):
super().__init__()
self.config = config
def _init_weights(self, reset_params: bool = False):
for layer in self.layers:
layer._init_weights(reset_params)
class FlexBertUnpadEncoder(FlexBertEncoderBase):
"""FlexBERT encoder for unpadded sequences."""
def __init__(self, config: FlexBertConfig):
super().__init__(config)
self.layers = nn.ModuleList([
get_encoder_layer(config, layer_id=i) for i in range(config.num_hidden_layers)
])
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
indices: Optional[torch.Tensor] = None,
cu_seqlens: Optional[torch.Tensor] = None,
max_seqlen: Optional[int] = None,
output_attentions: bool = False,
output_hidden_states: bool = False,
) -> Union[torch.Tensor, Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, ...]], Optional[Tuple[torch.Tensor, ...]]]]:
batch, seqlen = hidden_states.shape[:2]
all_hidden_states = (hidden_states,) if output_hidden_states else None
all_attentions = () if output_attentions else None
if cu_seqlens is None or max_seqlen is None:
hidden_states, indices, cu_seqlens, max_seqlen = unpad_input(hidden_states, attention_mask)
for layer in self.layers:
layer_out = layer(
hidden_states,
cu_seqlens,
max_seqlen,
indices,
attention_mask,
output_attentions=output_attentions,
)
if output_attentions:
hidden_states, attn_weights = layer_out
all_attentions = all_attentions + (attn_weights,)
else:
hidden_states = layer_out
if output_hidden_states:
all_hidden_states = all_hidden_states + (pad_input(hidden_states, indices, batch, seqlen),)
padded_out = pad_input(hidden_states, indices, batch, seqlen)
if output_attentions or output_hidden_states:
return padded_out, all_hidden_states, all_attentions
return padded_out
class FlexBertPaddedEncoder(FlexBertEncoderBase):
"""FlexBERT encoder for padded sequences."""
def __init__(self, config: FlexBertConfig):
super().__init__(config)
self.layers = nn.ModuleList([
get_encoder_layer(config, layer_id=i) for i in range(config.num_hidden_layers)
])
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
**kwargs,
) -> torch.Tensor:
for layer in self.layers:
hidden_states = layer(hidden_states, attn_mask=attention_mask)
return hidden_states
def get_encoder(config: FlexBertConfig) -> FlexBertEncoderBase:
if config.padding == "unpadded":
return FlexBertUnpadEncoder(config)
return FlexBertPaddedEncoder(config)
# ============================================================================
# Embeddings
# ============================================================================
class FlexBertEmbeddingsBase(nn.Module):
"""Base class for FlexBERT embeddings."""
def __init__(self, config: FlexBertConfig):
super().__init__()
self.config = config
def _init_weights(self, reset_params: bool = False):
raise NotImplementedError
class FlexBertSansPositionEmbeddings(FlexBertEmbeddingsBase):
"""FlexBERT embeddings without position embeddings."""
def __init__(self, config: FlexBertConfig):
super().__init__(config)
self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.norm = get_norm_layer(config) if config.embed_norm else nn.Identity()
self.drop = nn.Dropout(config.embed_dropout_prob) if config.embed_dropout_prob > 0 else nn.Identity()
def _init_weights(self, reset_params: bool = False):
pass
def forward(self, input_ids: torch.LongTensor, position_ids: Optional[torch.LongTensor] = None) -> torch.Tensor:
return self.drop(self.norm(self.tok_embeddings(input_ids)))
class FlexBertAbsoluteEmbeddings(FlexBertEmbeddingsBase):
"""FlexBERT embeddings with absolute position embeddings."""
def __init__(self, config: FlexBertConfig):
super().__init__(config)
self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.norm = get_norm_layer(config) if config.embed_norm else nn.Identity()
self.drop = nn.Dropout(config.embed_dropout_prob) if config.embed_dropout_prob > 0 else nn.Identity()
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
def _init_weights(self, reset_params: bool = False):
pass
def forward(self, input_ids: torch.LongTensor, position_ids: Optional[torch.LongTensor] = None) -> torch.Tensor:
if position_ids is None:
position_ids = self.position_ids[:, :input_ids.shape[1]]
embeddings = self.tok_embeddings(input_ids)
embeddings = embeddings + self.position_embeddings(position_ids)
return self.drop(self.norm(embeddings))
def get_embedding_layer(config: FlexBertConfig) -> FlexBertEmbeddingsBase:
if config.embedding_layer == "absolute_pos":
return FlexBertAbsoluteEmbeddings(config)
return FlexBertSansPositionEmbeddings(config)
# ============================================================================
# Model
# ============================================================================
class FlexBertPredictionHead(nn.Module):
"""Prediction head for FlexBERT MLM."""
def __init__(self, config: FlexBertConfig):
super().__init__()
self.config = config
self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=config.head_pred_bias)
self.act = get_act_fn(config.head_pred_act)
self.norm = get_norm_layer(config) if config.head_pred_norm else nn.Identity()
self.drop = nn.Dropout(config.head_pred_dropout) if config.head_pred_dropout > 0 else nn.Identity()
def _init_weights(self, reset_params: bool = False):
pass
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.drop(self.norm(self.act(self.dense(hidden_states))))
class FlexBertPreTrainedModel(BertPreTrainedModel):
"""FlexBERT pretrained model base class."""
config_class = FlexBertConfig
_tp_plan = {} # Empty dict to indicate no tensor parallelism plan (fixes caching_allocator_warmup error)
def _init_module_weights(self, module: nn.Module):
pass
class FlexBertModel(FlexBertPreTrainedModel):
"""FlexBERT model (encoder only)."""
def __init__(self, config: FlexBertConfig):
super().__init__(config)
self.embeddings = get_embedding_layer(config)
self.encoder = get_encoder(config)
self.final_norm = get_norm_layer(config) if config.final_norm else None
self.unpad_embeddings = config.unpad_embeddings
self.post_init()
def get_input_embeddings(self):
return self.embeddings.tok_embeddings
def set_input_embeddings(self, value):
self.embeddings.tok_embeddings = value
def forward(
self,
input_ids: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
indices: Optional[torch.Tensor] = None,
cu_seqlens: Optional[torch.Tensor] = None,
max_seqlen: Optional[int] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[Tuple, BaseModelOutput]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
output_attentions = output_attentions if output_attentions is not None else getattr(self.config, "output_attentions", False)
output_hidden_states = output_hidden_states if output_hidden_states is not None else getattr(self.config, "output_hidden_states", False)
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
embedding_output = self.embeddings(input_ids, position_ids)
if output_attentions or output_hidden_states:
encoder_outputs, all_hidden_states, all_attentions = self.encoder(
hidden_states=embedding_output,
attention_mask=attention_mask,
indices=indices,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
else:
encoder_outputs = self.encoder(
hidden_states=embedding_output,
attention_mask=attention_mask,
indices=indices,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
all_hidden_states = None
all_attentions = None
if self.final_norm is not None:
encoder_outputs = self.final_norm(encoder_outputs)
if all_hidden_states is not None:
all_hidden_states = all_hidden_states[:-1] + (encoder_outputs,)
if not return_dict:
return tuple(v for v in (encoder_outputs, all_hidden_states, all_attentions) if v is not None)
return BaseModelOutput(
last_hidden_state=encoder_outputs,
hidden_states=all_hidden_states,
attentions=all_attentions,
)
class FlexBertForMaskedLM(FlexBertPreTrainedModel):
"""FlexBERT for masked language modeling."""
# transformers 5.x requires a dict {target: source}; 4.x uses a list
_tied_weights_keys = (
{"decoder.weight": "bert.embeddings.tok_embeddings.weight"}
if _TRANSFORMERS_MAJOR >= 5
else ["decoder.weight"]
)
def __init__(self, config: FlexBertConfig):
super().__init__(config)
self.bert = FlexBertModel(config)
self.head = FlexBertPredictionHead(config)
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=config.decoder_bias)
self.loss_fn = nn.CrossEntropyLoss()
self.post_init()
def get_input_embeddings(self):
return self.bert.embeddings.tok_embeddings
def get_output_embeddings(self):
return self.decoder
def set_output_embeddings(self, new_embeddings):
self.decoder = new_embeddings
def mark_tied_weights_as_initialized(self, loading_info):
# Work around transformers 5.x bug where is_remote_code() strips tied keys
# from loading_info.missing_keys right after setting _is_hf_initialized=True,
# which prevents tie_weights() from tying decoder.weight and leaves it on meta.
for tied_param in getattr(self, "all_tied_weights_keys", {}).keys():
param = self.get_parameter(tied_param)
param._is_hf_initialized = True
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
indices: Optional[torch.Tensor] = None,
cu_seqlens: Optional[torch.Tensor] = None,
max_seqlen: Optional[int] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[Tuple, MaskedLMOutput]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
indices=indices,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
)
last_hidden_state = outputs.last_hidden_state
prediction_scores = self.decoder(self.head(last_hidden_state))
loss = None
if labels is not None:
loss = self.loss_fn(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + tuple(
v for v in (outputs.hidden_states, outputs.attentions) if v is not None
)
return ((loss,) + output) if loss is not None else output
return MaskedLMOutput(
loss=loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
__all__ = [
"FlexBertConfig",
"FlexBertModel",
"FlexBertForMaskedLM",
"FlexBertPreTrainedModel",
]
# Copyright 2024 onwards Answer.AI, LightOn, and contributors
# License: Apache-2.0
# Minimal self-contained FlexBERT implementation for inference
import inspect
import math
import warnings
from collections import OrderedDict
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
import transformers
from transformers import BertConfig as TransformersBertConfig
from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput, ModelOutput
from transformers.models.bert.modeling_bert import BertPreTrainedModel
_TRANSFORMERS_MAJOR = int(transformers.__version__.split(".")[0])
# Try to import flash attention
IMPL_USE_FLASH2 = False
try:
from flash_attn import flash_attn_varlen_qkvpacked_func, flash_attn_qkvpacked_func
import importlib.metadata
installed_version = importlib.metadata.version("flash_attn")
if installed_version >= "2.5.7":
IMPL_USE_FLASH2 = True
except ImportError:
pass
try:
from flash_attn.layers.rotary import RotaryEmbedding
from flash_attn.ops.triton.rotary import apply_rotary
HAS_FLASH_ROTARY = True
except ImportError:
RotaryEmbedding = None
apply_rotary = None
HAS_FLASH_ROTARY = False
try:
from flash_attn.ops.triton.layer_norm import RMSNorm as TritonRMSNorm
except ImportError:
TritonRMSNorm = None
# ============================================================================
# Configuration
# ============================================================================
class FlexBertConfig(TransformersBertConfig):
def __init__(
self,
attention_layer: str = "base",
attention_probs_dropout_prob: float = 0.0,
attn_out_bias: bool = False,
attn_out_dropout_prob: float = 0.0,
attn_qkv_bias: bool = False,
bert_layer: str = "prenorm",
decoder_bias: bool = True,
embed_dropout_prob: float = 0.0,
embed_norm: bool = True,
final_norm: bool = False,
embedding_layer: str = "absolute_pos",
encoder_layer: str = "base",
loss_function: str = "cross_entropy",
loss_kwargs: dict = {},
mlp_dropout_prob: float = 0.0,
mlp_in_bias: bool = False,
mlp_layer: str = "mlp",
mlp_out_bias: bool = False,
norm_kwargs: dict = {},
normalization: str = "rmsnorm",
padding: str = "unpadded",
head_class_act: str = "silu",
head_class_bias: bool = False,
head_class_dropout: float = 0.0,
head_class_norm: str = False,
head_pred_act: str = "silu",
head_pred_bias: bool = False,
head_pred_dropout: float = 0.0,
head_pred_norm: bool = True,
pooling_type: str = "cls",
rotary_emb_dim: int | None = None,
rotary_emb_base: float = 10000.0,
rotary_emb_scale_base=None,
rotary_emb_interleaved: bool = False,
use_fa2: bool = True,
use_sdpa_attn_mask: bool = False,
allow_embedding_resizing: bool = False,
init_method: str = "default",
init_std: float = 0.02,
init_cutoff_factor: float = 2.0,
init_small_embedding: bool = False,
initial_attention_layer: str | None = None,
initial_bert_layer: str | None = None,
initial_mlp_layer: str | None = None,
num_initial_layers: int = 1,