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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags: []
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# Model Card for Model ID
|
| 7 |
+
|
| 8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
## Model Details
|
| 13 |
+
|
| 14 |
+
### Model Description
|
| 15 |
+
|
| 16 |
+
<!-- Provide a longer summary of what this model is. -->
|
| 17 |
+
|
| 18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
| 19 |
+
|
| 20 |
+
- **Developed by:** [More Information Needed]
|
| 21 |
+
- **Funded by [optional]:** [More Information Needed]
|
| 22 |
+
- **Shared by [optional]:** [More Information Needed]
|
| 23 |
+
- **Model type:** [More Information Needed]
|
| 24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
| 25 |
+
- **License:** [More Information Needed]
|
| 26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
| 27 |
+
|
| 28 |
+
### Model Sources [optional]
|
| 29 |
+
|
| 30 |
+
<!-- Provide the basic links for the model. -->
|
| 31 |
+
|
| 32 |
+
- **Repository:** [More Information Needed]
|
| 33 |
+
- **Paper [optional]:** [More Information Needed]
|
| 34 |
+
- **Demo [optional]:** [More Information Needed]
|
| 35 |
+
|
| 36 |
+
## Uses
|
| 37 |
+
|
| 38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
| 39 |
+
|
| 40 |
+
### Direct Use
|
| 41 |
+
|
| 42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
| 43 |
+
|
| 44 |
+
[More Information Needed]
|
| 45 |
+
|
| 46 |
+
### Downstream Use [optional]
|
| 47 |
+
|
| 48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
| 49 |
+
|
| 50 |
+
[More Information Needed]
|
| 51 |
+
|
| 52 |
+
### Out-of-Scope Use
|
| 53 |
+
|
| 54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
| 55 |
+
|
| 56 |
+
[More Information Needed]
|
| 57 |
+
|
| 58 |
+
## Bias, Risks, and Limitations
|
| 59 |
+
|
| 60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
| 61 |
+
|
| 62 |
+
[More Information Needed]
|
| 63 |
+
|
| 64 |
+
### Recommendations
|
| 65 |
+
|
| 66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 67 |
+
|
| 68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 69 |
+
|
| 70 |
+
## How to Get Started with the Model
|
| 71 |
+
|
| 72 |
+
Use the code below to get started with the model.
|
| 73 |
+
|
| 74 |
+
[More Information Needed]
|
| 75 |
+
|
| 76 |
+
## Training Details
|
| 77 |
+
|
| 78 |
+
### Training Data
|
| 79 |
+
|
| 80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
| 81 |
+
|
| 82 |
+
[More Information Needed]
|
| 83 |
+
|
| 84 |
+
### Training Procedure
|
| 85 |
+
|
| 86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 87 |
+
|
| 88 |
+
#### Preprocessing [optional]
|
| 89 |
+
|
| 90 |
+
[More Information Needed]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
#### Training Hyperparameters
|
| 94 |
+
|
| 95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 96 |
+
|
| 97 |
+
#### Speeds, Sizes, Times [optional]
|
| 98 |
+
|
| 99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 100 |
+
|
| 101 |
+
[More Information Needed]
|
| 102 |
+
|
| 103 |
+
## Evaluation
|
| 104 |
+
|
| 105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 106 |
+
|
| 107 |
+
### Testing Data, Factors & Metrics
|
| 108 |
+
|
| 109 |
+
#### Testing Data
|
| 110 |
+
|
| 111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
| 112 |
+
|
| 113 |
+
[More Information Needed]
|
| 114 |
+
|
| 115 |
+
#### Factors
|
| 116 |
+
|
| 117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 118 |
+
|
| 119 |
+
[More Information Needed]
|
| 120 |
+
|
| 121 |
+
#### Metrics
|
| 122 |
+
|
| 123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 124 |
+
|
| 125 |
+
[More Information Needed]
|
| 126 |
+
|
| 127 |
+
### Results
|
| 128 |
+
|
| 129 |
+
[More Information Needed]
|
| 130 |
+
|
| 131 |
+
#### Summary
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
## Model Examination [optional]
|
| 136 |
+
|
| 137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
| 138 |
+
|
| 139 |
+
[More Information Needed]
|
| 140 |
+
|
| 141 |
+
## Environmental Impact
|
| 142 |
+
|
| 143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 144 |
+
|
| 145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
| 146 |
+
|
| 147 |
+
- **Hardware Type:** [More Information Needed]
|
| 148 |
+
- **Hours used:** [More Information Needed]
|
| 149 |
+
- **Cloud Provider:** [More Information Needed]
|
| 150 |
+
- **Compute Region:** [More Information Needed]
|
| 151 |
+
- **Carbon Emitted:** [More Information Needed]
|
| 152 |
+
|
| 153 |
+
## Technical Specifications [optional]
|
| 154 |
+
|
| 155 |
+
### Model Architecture and Objective
|
| 156 |
+
|
| 157 |
+
[More Information Needed]
|
| 158 |
+
|
| 159 |
+
### Compute Infrastructure
|
| 160 |
+
|
| 161 |
+
[More Information Needed]
|
| 162 |
+
|
| 163 |
+
#### Hardware
|
| 164 |
+
|
| 165 |
+
[More Information Needed]
|
| 166 |
+
|
| 167 |
+
#### Software
|
| 168 |
+
|
| 169 |
+
[More Information Needed]
|
| 170 |
+
|
| 171 |
+
## Citation [optional]
|
| 172 |
+
|
| 173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 174 |
+
|
| 175 |
+
**BibTeX:**
|
| 176 |
+
|
| 177 |
+
[More Information Needed]
|
| 178 |
+
|
| 179 |
+
**APA:**
|
| 180 |
+
|
| 181 |
+
[More Information Needed]
|
| 182 |
+
|
| 183 |
+
## Glossary [optional]
|
| 184 |
+
|
| 185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 186 |
+
|
| 187 |
+
[More Information Needed]
|
| 188 |
+
|
| 189 |
+
## More Information [optional]
|
| 190 |
+
|
| 191 |
+
[More Information Needed]
|
| 192 |
+
|
| 193 |
+
## Model Card Authors [optional]
|
| 194 |
+
|
| 195 |
+
[More Information Needed]
|
| 196 |
+
|
| 197 |
+
## Model Card Contact
|
| 198 |
+
|
| 199 |
+
[More Information Needed]
|
config.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"NeoBERTLMHead"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "model.NeoBERTConfig",
|
| 7 |
+
"AutoModel": "model.NeoBERTLMHead"
|
| 8 |
+
},
|
| 9 |
+
"classifier_init_range": 0.02,
|
| 10 |
+
"decoder_init_range": 0.02,
|
| 11 |
+
"dim_head": 64,
|
| 12 |
+
"embedding_init_range": 0.02,
|
| 13 |
+
"hidden_size": 768,
|
| 14 |
+
"intermediate_size": 3072,
|
| 15 |
+
"kwargs": {
|
| 16 |
+
"classifier_init_range": 0.02,
|
| 17 |
+
"pretrained_model_name_or_path": "google-bert/bert-base-uncased",
|
| 18 |
+
"trust_remote_code": true
|
| 19 |
+
},
|
| 20 |
+
"max_length": 4096,
|
| 21 |
+
"model_type": "neobert",
|
| 22 |
+
"norm_eps": 1e-05,
|
| 23 |
+
"num_attention_heads": 12,
|
| 24 |
+
"num_hidden_layers": 28,
|
| 25 |
+
"pad_token_id": 0,
|
| 26 |
+
"pretrained_model_name_or_path": "google-bert/bert-base-uncased",
|
| 27 |
+
"torch_dtype": "float32",
|
| 28 |
+
"transformers_version": "4.48.2",
|
| 29 |
+
"trust_remote_code": true,
|
| 30 |
+
"vocab_size": 30522
|
| 31 |
+
}
|
model.py
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# From https://github.com/facebookresearch/llama/blob/main/llama/model.py
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 7 |
+
from torch.nn.functional import scaled_dot_product_attention
|
| 8 |
+
|
| 9 |
+
from typing import Optional
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from xformers.ops import SwiGLU
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_func
|
| 16 |
+
|
| 17 |
+
FLASH_ATTN_AVAILABLE = True
|
| 18 |
+
except ImportError:
|
| 19 |
+
FLASH_ATTN_AVAILABLE = False
|
| 20 |
+
|
| 21 |
+
from transformers import (
|
| 22 |
+
PreTrainedModel,
|
| 23 |
+
PretrainedConfig,
|
| 24 |
+
DataCollatorForLanguageModeling,
|
| 25 |
+
)
|
| 26 |
+
from transformers.modeling_outputs import (
|
| 27 |
+
BaseModelOutput,
|
| 28 |
+
MaskedLMOutput,
|
| 29 |
+
SequenceClassifierOutput,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
from .rotary import precompute_freqs_cis, apply_rotary_emb
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class DataCollatorWithPacking(DataCollatorForLanguageModeling):
|
| 36 |
+
def __init__(self, pack_sequences=False, **kwargs):
|
| 37 |
+
super().__init__(**kwargs)
|
| 38 |
+
self.pack_sequences = pack_sequences
|
| 39 |
+
|
| 40 |
+
def __call__(self, batch):
|
| 41 |
+
if self.pack_sequences:
|
| 42 |
+
# Add position_ids if not present
|
| 43 |
+
if "position_ids" not in batch[0]:
|
| 44 |
+
for item in batch:
|
| 45 |
+
item["position_ids"] = list(range(len(item["input_ids"])))
|
| 46 |
+
|
| 47 |
+
# Pack the sequences into a single list
|
| 48 |
+
input_ids_list = [item["input_ids"] for item in batch]
|
| 49 |
+
position_ids_list = [item["position_ids"] for item in batch]
|
| 50 |
+
seqlens = np.array([0] + [len(ids) for ids in input_ids_list])
|
| 51 |
+
|
| 52 |
+
packed_batch = {
|
| 53 |
+
"position_ids": np.concatenate(position_ids_list, axis=0),
|
| 54 |
+
"input_ids": np.concatenate(input_ids_list, axis=0),
|
| 55 |
+
"cu_seqlens": np.cumsum(seqlens),
|
| 56 |
+
"max_seqlen": max(seqlens),
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
batch = super().__call__([packed_batch])
|
| 60 |
+
batch["cu_seqlens"] = batch["cu_seqlens"].to(torch.int32).squeeze()
|
| 61 |
+
else:
|
| 62 |
+
batch = super().__call__(batch)
|
| 63 |
+
batch["attention_mask"] = batch["attention_mask"].to(torch.bool)
|
| 64 |
+
|
| 65 |
+
return batch
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class NeoBERTConfig(PretrainedConfig):
|
| 69 |
+
model_type = "neobert"
|
| 70 |
+
|
| 71 |
+
# All config parameters must have a default value.
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
hidden_size: int = 768,
|
| 75 |
+
num_hidden_layers: int = 28,
|
| 76 |
+
num_attention_heads: int = 12,
|
| 77 |
+
intermediate_size: int = 3072,
|
| 78 |
+
embedding_init_range: float = 0.02,
|
| 79 |
+
decoder_init_range: float = 0.02,
|
| 80 |
+
norm_eps: float = 1e-06,
|
| 81 |
+
vocab_size: int = 30522,
|
| 82 |
+
pad_token_id: int = 0,
|
| 83 |
+
max_length: int = 1024,
|
| 84 |
+
**kwargs,
|
| 85 |
+
):
|
| 86 |
+
super().__init__(**kwargs)
|
| 87 |
+
|
| 88 |
+
self.hidden_size = hidden_size
|
| 89 |
+
self.num_hidden_layers = num_hidden_layers
|
| 90 |
+
self.num_attention_heads = num_attention_heads
|
| 91 |
+
if hidden_size % num_attention_heads != 0:
|
| 92 |
+
raise ValueError("Hidden size must be divisible by the number of heads.")
|
| 93 |
+
self.dim_head = hidden_size // num_attention_heads
|
| 94 |
+
self.intermediate_size = intermediate_size
|
| 95 |
+
self.embedding_init_range = embedding_init_range
|
| 96 |
+
self.decoder_init_range = decoder_init_range
|
| 97 |
+
self.norm_eps = norm_eps
|
| 98 |
+
self.vocab_size = vocab_size
|
| 99 |
+
self.pad_token_id = pad_token_id
|
| 100 |
+
self.max_length = max_length
|
| 101 |
+
self.kwargs = kwargs
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class EncoderBlock(nn.Module):
|
| 105 |
+
"""Transformer encoder block."""
|
| 106 |
+
|
| 107 |
+
def __init__(self, config: NeoBERTConfig):
|
| 108 |
+
super().__init__()
|
| 109 |
+
|
| 110 |
+
self.config = config
|
| 111 |
+
|
| 112 |
+
# Attention
|
| 113 |
+
self.qkv = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size * 3, bias=False)
|
| 114 |
+
self.wo = nn.Linear(in_features=config.hidden_size, out_features=config.hidden_size, bias=False)
|
| 115 |
+
|
| 116 |
+
# Feedforward network
|
| 117 |
+
multiple_of = 8
|
| 118 |
+
intermediate_size = int(2 * config.intermediate_size / 3)
|
| 119 |
+
intermediate_size = multiple_of * ((intermediate_size + multiple_of - 1) // multiple_of)
|
| 120 |
+
self.ffn = SwiGLU(config.hidden_size, intermediate_size, config.hidden_size, bias=False)
|
| 121 |
+
|
| 122 |
+
# Layer norms
|
| 123 |
+
self.attention_norm = nn.RMSNorm(config.hidden_size, config.norm_eps)
|
| 124 |
+
self.ffn_norm = nn.RMSNorm(config.hidden_size, config.norm_eps)
|
| 125 |
+
|
| 126 |
+
def forward(
|
| 127 |
+
self,
|
| 128 |
+
x: torch.Tensor,
|
| 129 |
+
attention_mask: torch.Tensor,
|
| 130 |
+
freqs_cis: torch.Tensor,
|
| 131 |
+
output_attentions: bool,
|
| 132 |
+
max_seqlen: int = None,
|
| 133 |
+
cu_seqlens: torch.Tensor = None,
|
| 134 |
+
):
|
| 135 |
+
# Attention
|
| 136 |
+
attn_output, attn_weights = self._att_block(
|
| 137 |
+
self.attention_norm(x), attention_mask, freqs_cis, output_attentions, max_seqlen, cu_seqlens
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Residual
|
| 141 |
+
x = x + attn_output
|
| 142 |
+
|
| 143 |
+
# Feed-forward
|
| 144 |
+
x = x + self.ffn(self.ffn_norm(x))
|
| 145 |
+
|
| 146 |
+
return x, attn_weights
|
| 147 |
+
|
| 148 |
+
def _att_block(
|
| 149 |
+
self,
|
| 150 |
+
x: torch.Tensor,
|
| 151 |
+
attention_mask: torch.Tensor,
|
| 152 |
+
freqs_cis: torch.Tensor,
|
| 153 |
+
output_attentions: bool,
|
| 154 |
+
max_seqlen: int = None,
|
| 155 |
+
cu_seqlens: torch.Tensor = None,
|
| 156 |
+
):
|
| 157 |
+
batch_size, seq_len, _ = x.shape
|
| 158 |
+
|
| 159 |
+
xq, xk, xv = self.qkv(x).view(batch_size, seq_len, self.config.num_attention_heads, self.config.dim_head * 3).chunk(3, axis=-1)
|
| 160 |
+
|
| 161 |
+
xq, xk = apply_rotary_emb(xq, xk, freqs_cis)
|
| 162 |
+
|
| 163 |
+
# Attn block
|
| 164 |
+
attn_weights = None
|
| 165 |
+
|
| 166 |
+
# Flash attention if the tensors are packed
|
| 167 |
+
if cu_seqlens is not None:
|
| 168 |
+
attn = flash_attn_varlen_func(
|
| 169 |
+
q=xq.squeeze(0),
|
| 170 |
+
k=xk.squeeze(0),
|
| 171 |
+
v=xv.squeeze(0),
|
| 172 |
+
cu_seqlens_q=cu_seqlens,
|
| 173 |
+
cu_seqlens_k=cu_seqlens,
|
| 174 |
+
max_seqlen_q=max_seqlen,
|
| 175 |
+
max_seqlen_k=max_seqlen,
|
| 176 |
+
dropout_p=0.0,
|
| 177 |
+
causal=False,
|
| 178 |
+
)
|
| 179 |
+
# Eager attention if attention weights are needed in the output
|
| 180 |
+
elif output_attentions:
|
| 181 |
+
attn_weights = xq.permute(0, 2, 1, 3) @ xk.permute(0, 2, 3, 1) / (xq.size(-1) ** 0.5)
|
| 182 |
+
if attention_mask is not None:
|
| 183 |
+
attn_weights = attn_weights * attention_mask
|
| 184 |
+
attn_weights = attn_weights.softmax(-1)
|
| 185 |
+
attn = attn_weights @ xv.permute(0, 2, 1, 3)
|
| 186 |
+
attn = attn.transpose(1, 2)
|
| 187 |
+
# Fall back to SDPA otherwise
|
| 188 |
+
else:
|
| 189 |
+
attn = scaled_dot_product_attention(
|
| 190 |
+
query=xq.transpose(1, 2),
|
| 191 |
+
key=xk.transpose(1, 2),
|
| 192 |
+
value=xv.transpose(1, 2),
|
| 193 |
+
attn_mask=attention_mask,
|
| 194 |
+
dropout_p=0,
|
| 195 |
+
).transpose(1, 2)
|
| 196 |
+
|
| 197 |
+
return self.wo(attn.reshape(batch_size, seq_len, self.config.num_attention_heads * self.config.dim_head)), attn_weights
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class NeoBERTPreTrainedModel(PreTrainedModel):
|
| 201 |
+
config_class = NeoBERTConfig
|
| 202 |
+
_supports_cache_class = True
|
| 203 |
+
|
| 204 |
+
def _init_weights(self, module):
|
| 205 |
+
if isinstance(module, nn.Linear):
|
| 206 |
+
module.weight.data.uniform_(-self.config.decoder_init_range, self.config.decoder_init_range)
|
| 207 |
+
elif isinstance(module, nn.Embedding):
|
| 208 |
+
module.weight.data.uniform_(-self.config.embedding_init_range, self.config.embedding_init_range)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class NeoBERT(NeoBERTPreTrainedModel):
|
| 212 |
+
config_class = NeoBERTConfig
|
| 213 |
+
|
| 214 |
+
def __init__(self, config: NeoBERTConfig):
|
| 215 |
+
super().__init__(config)
|
| 216 |
+
|
| 217 |
+
self.config = config
|
| 218 |
+
|
| 219 |
+
self.encoder = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 220 |
+
|
| 221 |
+
# Ensures freqs_cis is moved to the same devices as the model. Non-persistent buffers are not saved in the state_dict.
|
| 222 |
+
freqs_cis = precompute_freqs_cis(config.hidden_size // config.num_attention_heads, config.max_length)
|
| 223 |
+
self.register_buffer("freqs_cis", freqs_cis, persistent=False)
|
| 224 |
+
|
| 225 |
+
self.transformer_encoder = nn.ModuleList()
|
| 226 |
+
for _ in range(config.num_hidden_layers):
|
| 227 |
+
self.transformer_encoder.append(EncoderBlock(config))
|
| 228 |
+
|
| 229 |
+
self.layer_norm = nn.RMSNorm(config.hidden_size, config.norm_eps)
|
| 230 |
+
|
| 231 |
+
# Initialize weights and apply final processing
|
| 232 |
+
self.post_init()
|
| 233 |
+
|
| 234 |
+
def forward(
|
| 235 |
+
self,
|
| 236 |
+
input_ids: torch.Tensor,
|
| 237 |
+
position_ids: torch.Tensor = None,
|
| 238 |
+
max_seqlen: int = None,
|
| 239 |
+
cu_seqlens: torch.Tensor = None,
|
| 240 |
+
attention_mask: torch.Tensor = None,
|
| 241 |
+
output_hidden_states: bool = False,
|
| 242 |
+
output_attentions: bool = False,
|
| 243 |
+
**kwargs,
|
| 244 |
+
):
|
| 245 |
+
# Initialize
|
| 246 |
+
hidden_states, attentions = [], []
|
| 247 |
+
|
| 248 |
+
# Expand and repeat: (Batch, Length) -> (Batch, Heads, Length, Length)
|
| 249 |
+
if attention_mask is not None:
|
| 250 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(1).repeat(1, self.config.num_attention_heads, attention_mask.size(-1), 1)
|
| 251 |
+
|
| 252 |
+
# Checks to be done if inputs are packed sequences
|
| 253 |
+
if cu_seqlens is not None:
|
| 254 |
+
assert (
|
| 255 |
+
FLASH_ATTN_AVAILABLE
|
| 256 |
+
), "Flash-attention is not available. Please ''pip install flash_attn'', or provide un-packed sequences."
|
| 257 |
+
assert not output_attentions, "Output attentions is not supported when sequences are packed."
|
| 258 |
+
assert max_seqlen is not None, "Missing max_seqlen. It must be provided when cu_seqlens are not None."
|
| 259 |
+
assert input_ids.shape[0] == 1, "Cumulative sequence lengths are provided but input_ids are not packed."
|
| 260 |
+
assert input_ids.is_cuda, "Packing uses an implementation of flash-attention and is only supported on GPU."
|
| 261 |
+
|
| 262 |
+
# RoPE
|
| 263 |
+
freqs_cis = self.freqs_cis[position_ids] if position_ids is not None else self.freqs_cis[: input_ids.shape[1]].unsqueeze(0)
|
| 264 |
+
|
| 265 |
+
# Embedding
|
| 266 |
+
x = self.encoder(input_ids)
|
| 267 |
+
|
| 268 |
+
# Transformer encoder
|
| 269 |
+
for layer in self.transformer_encoder:
|
| 270 |
+
x, attn = layer(x, attention_mask, freqs_cis, output_attentions, max_seqlen, cu_seqlens)
|
| 271 |
+
if output_hidden_states:
|
| 272 |
+
hidden_states.append(x)
|
| 273 |
+
if output_attentions:
|
| 274 |
+
attentions.append(attn)
|
| 275 |
+
|
| 276 |
+
# Final normalization layer
|
| 277 |
+
x = self.layer_norm(x)
|
| 278 |
+
|
| 279 |
+
# Return the output of the last hidden layer
|
| 280 |
+
return BaseModelOutput(
|
| 281 |
+
last_hidden_state=x,
|
| 282 |
+
hidden_states=hidden_states if output_hidden_states else None,
|
| 283 |
+
attentions=attentions if output_attentions else None,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class NeoBERTLMHead(NeoBERTPreTrainedModel):
|
| 288 |
+
config_class = NeoBERTConfig
|
| 289 |
+
|
| 290 |
+
def __init__(self, config: NeoBERTConfig):
|
| 291 |
+
super().__init__(config)
|
| 292 |
+
|
| 293 |
+
self.config = config
|
| 294 |
+
|
| 295 |
+
self.model = NeoBERT(config)
|
| 296 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
|
| 297 |
+
|
| 298 |
+
self.post_init()
|
| 299 |
+
|
| 300 |
+
def forward(
|
| 301 |
+
self,
|
| 302 |
+
input_ids: torch.Tensor,
|
| 303 |
+
position_ids: torch.Tensor = None,
|
| 304 |
+
max_seqlen: int = None,
|
| 305 |
+
cu_seqlens: torch.Tensor = None,
|
| 306 |
+
attention_mask: torch.Tensor = None,
|
| 307 |
+
output_hidden_states: bool = False,
|
| 308 |
+
output_attentions: bool = False,
|
| 309 |
+
**kwargs,
|
| 310 |
+
):
|
| 311 |
+
|
| 312 |
+
output = self.model.forward(
|
| 313 |
+
input_ids,
|
| 314 |
+
position_ids,
|
| 315 |
+
max_seqlen,
|
| 316 |
+
cu_seqlens,
|
| 317 |
+
attention_mask,
|
| 318 |
+
output_hidden_states,
|
| 319 |
+
output_attentions,
|
| 320 |
+
)
|
| 321 |
+
logits = self.decoder(output.last_hidden_state)
|
| 322 |
+
|
| 323 |
+
return MaskedLMOutput(
|
| 324 |
+
hidden_states=output.hidden_states if output_hidden_states else None,
|
| 325 |
+
attentions=output.attentions if output_attentions else None,
|
| 326 |
+
logits=logits,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class NeoBERTForSequenceClassification(NeoBERTPreTrainedModel):
|
| 331 |
+
config_class = NeoBERTConfig
|
| 332 |
+
|
| 333 |
+
def __init__(self, config: NeoBERTConfig):
|
| 334 |
+
super().__init__(config)
|
| 335 |
+
|
| 336 |
+
self.config = config
|
| 337 |
+
|
| 338 |
+
self.num_labels = getattr(config, "num_labels", 2)
|
| 339 |
+
self.classifier_dropout = getattr(config, "classifier_dropout", 0.1)
|
| 340 |
+
self.classifier_init_range = getattr(config, "classifier_init_range", 0.02)
|
| 341 |
+
|
| 342 |
+
self.model = NeoBERT(config)
|
| 343 |
+
|
| 344 |
+
self.dense = nn.Linear(self.config.hidden_size, self.config.hidden_size)
|
| 345 |
+
self.dropout = nn.Dropout(self.classifier_dropout)
|
| 346 |
+
self.classifier = nn.Linear(self.config.hidden_size, self.num_labels)
|
| 347 |
+
|
| 348 |
+
self.post_init()
|
| 349 |
+
|
| 350 |
+
def _init_weights(self, module):
|
| 351 |
+
if isinstance(module, nn.Linear):
|
| 352 |
+
module.weight.data.normal_(mean=0.0, std=self.classifier_init_range)
|
| 353 |
+
if module.bias is not None:
|
| 354 |
+
module.bias.data.zero_()
|
| 355 |
+
|
| 356 |
+
def forward(
|
| 357 |
+
self,
|
| 358 |
+
input_ids: torch.Tensor,
|
| 359 |
+
position_ids: torch.Tensor = None,
|
| 360 |
+
max_seqlen: int = None,
|
| 361 |
+
cu_seqlens: torch.Tensor = None,
|
| 362 |
+
attention_mask: torch.Tensor = None,
|
| 363 |
+
output_hidden_states: bool = False,
|
| 364 |
+
output_attentions: bool = False,
|
| 365 |
+
labels: Optional[torch.Tensor] = None,
|
| 366 |
+
return_dict: Optional[bool] = None,
|
| 367 |
+
):
|
| 368 |
+
|
| 369 |
+
output = self.model.forward(
|
| 370 |
+
input_ids,
|
| 371 |
+
position_ids,
|
| 372 |
+
max_seqlen,
|
| 373 |
+
cu_seqlens,
|
| 374 |
+
attention_mask,
|
| 375 |
+
output_hidden_states,
|
| 376 |
+
output_attentions,
|
| 377 |
+
)
|
| 378 |
+
hidden_states = output.last_hidden_state
|
| 379 |
+
|
| 380 |
+
x = hidden_states[:, 0, :]
|
| 381 |
+
x = self.dropout(x)
|
| 382 |
+
x = self.dense(x)
|
| 383 |
+
x = torch.tanh(x)
|
| 384 |
+
x = self.dropout(x)
|
| 385 |
+
|
| 386 |
+
logits = self.classifier(x)
|
| 387 |
+
|
| 388 |
+
loss = None
|
| 389 |
+
if labels is not None:
|
| 390 |
+
if self.config.problem_type is None:
|
| 391 |
+
if self.num_labels == 1:
|
| 392 |
+
self.config.problem_type = "regression"
|
| 393 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 394 |
+
self.config.problem_type = "single_label_classification"
|
| 395 |
+
else:
|
| 396 |
+
self.config.problem_type = "multi_label_classification"
|
| 397 |
+
|
| 398 |
+
if self.config.problem_type == "regression":
|
| 399 |
+
loss_fct = MSELoss()
|
| 400 |
+
if self.num_labels == 1:
|
| 401 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 402 |
+
else:
|
| 403 |
+
loss = loss_fct(logits, labels)
|
| 404 |
+
elif self.config.problem_type == "single_label_classification":
|
| 405 |
+
loss_fct = CrossEntropyLoss()
|
| 406 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 407 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 408 |
+
loss_fct = BCEWithLogitsLoss()
|
| 409 |
+
loss = loss_fct(logits, labels)
|
| 410 |
+
|
| 411 |
+
if not return_dict:
|
| 412 |
+
result = (logits,)
|
| 413 |
+
return ((loss,) + result) if loss is not None else result
|
| 414 |
+
|
| 415 |
+
return SequenceClassifierOutput(
|
| 416 |
+
loss=loss,
|
| 417 |
+
logits=logits,
|
| 418 |
+
hidden_states=output.hidden_states if output_hidden_states else None,
|
| 419 |
+
attentions=output.attentions if output_attentions else None,
|
| 420 |
+
)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b547ae956c4ef7024a444d93464a9028cc6594cf36830fd5069a7ef9a53d799f
|
| 3 |
+
size 980567608
|
rotary.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# From https://github.com/facebookresearch/llama/blob/main/llama/model.py
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from typing import Tuple
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
|
| 8 |
+
"""
|
| 9 |
+
Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
|
| 10 |
+
|
| 11 |
+
This function calculates a frequency tensor with complex exponentials using the given dimension 'dim'
|
| 12 |
+
and the end index 'end'. The 'theta' parameter scales the frequencies.
|
| 13 |
+
The returned tensor contains complex values in complex64 data type.
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
dim (int): Dimension of the frequency tensor.
|
| 17 |
+
end (int): End index for precomputing frequencies.
|
| 18 |
+
theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
|
| 19 |
+
|
| 20 |
+
Returns:
|
| 21 |
+
torch.Tensor: Precomputed frequency tensor with complex exponentials.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 25 |
+
t = torch.arange(end, device=freqs.device)
|
| 26 |
+
freqs = torch.outer(t, freqs).float()
|
| 27 |
+
return torch.polar(torch.ones_like(freqs), freqs)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
|
| 31 |
+
assert freqs_cis.shape[1:] == (x.shape[1], x.shape[-1])
|
| 32 |
+
return freqs_cis.contiguous().unsqueeze(2)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def apply_rotary_emb(
|
| 36 |
+
xq: torch.Tensor,
|
| 37 |
+
xk: torch.Tensor,
|
| 38 |
+
freqs_cis: torch.Tensor,
|
| 39 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 40 |
+
"""
|
| 41 |
+
Apply rotary embeddings to input tensors using the given frequency tensor.
|
| 42 |
+
|
| 43 |
+
This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
|
| 44 |
+
frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
|
| 45 |
+
is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
|
| 46 |
+
returned as real tensors.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
xq (torch.Tensor): Query tensor to apply rotary embeddings.
|
| 50 |
+
xk (torch.Tensor): Key tensor to apply rotary embeddings.
|
| 51 |
+
freqs_cis (torch.Tensor): Precomputed frequency tensor for complex exponentials.
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
|
| 55 |
+
"""
|
| 56 |
+
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
|
| 57 |
+
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
|
| 58 |
+
freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
|
| 59 |
+
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
|
| 60 |
+
xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
|
| 61 |
+
return xq_out.type_as(xq), xk_out.type_as(xk)
|