Upload folder using huggingface_hub
Browse files- LICENSE +31 -0
- README.md +448 -0
- config.json +100 -0
- config.py +262 -0
- config.yaml +88 -0
- generation_config.json +4 -0
- model-00001-of-00006.safetensors +3 -0
- model-00002-of-00006.safetensors +3 -0
- model-00003-of-00006.safetensors +3 -0
- model-00004-of-00006.safetensors +3 -0
- model-00005-of-00006.safetensors +3 -0
- model-00006-of-00006.safetensors +3 -0
- model.py +951 -0
- model.safetensors.index.json +512 -0
- norm.py +21 -0
- source/aleph_alpha_homepage_badge.svg +46 -0
- source/aleph_alpha_logo.svg +13 -0
- source/aleph_alpha_logo_thumbnail.png +0 -0
- splitter.py +39 -0
- transformer_backbone.py +1553 -0
LICENSE
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The following applies to all files in this repository, unless otherwise noted:
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Aleph Alpha Research GmbH. All rights reserved.
|
| 4 |
+
|
| 5 |
+
This project is licensed under the terms of the Open Aleph License 1.0, available at
|
| 6 |
+
https://github.com/Aleph-Alpha/.github/blob/main/oal.pdf
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
Excerpt from the license text:
|
| 10 |
+
|
| 11 |
+
Subject to the terms and conditions of this License, the Licensor grants you a non-exclusive, worldwide,
|
| 12 |
+
non-transferable, non-sublicensable, and royalty-free limited right to use, copy, modify, distribute, make
|
| 13 |
+
otherwise publicly available, and reproduce the Works and Derivative Works under Licensor’s copyright,
|
| 14 |
+
for any Non-Commercial and Non-Administrative purpose.
|
| 15 |
+
You may not use, copy, modify, distribute, make otherwise publicly available, reproduce, or sublicense the
|
| 16 |
+
Works or Derivative Works except as expressly provided under and in accordance with this License.
|
| 17 |
+
Your rights granted under this License will automatically terminate if you fail to comply with any of the
|
| 18 |
+
terms of this License.
|
| 19 |
+
|
| 20 |
+
EXCEPT FOR DAMAGES CAUSED BY INTENT OR FRAUDULENTLY CONCEALED
|
| 21 |
+
DEFECTS, AND EXCEPT FOR DAMAGES RESULTING FROM BREACH OF ANY
|
| 22 |
+
WARRANTY OR GUARANTEE EXPRESSLY GIVEN BY LICENSOR IN THE OPEN ALEPH LICENSE,
|
| 23 |
+
IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY
|
| 24 |
+
DAMAGES ARISING OUT OF THE OPEN ALEPH LICENSE OR THE USE OF THE WORK. ANY
|
| 25 |
+
MANDATORY STATUTORY LIABILITY UNDER APPLICABLE LAW REMAINS
|
| 26 |
+
UNAFFECTED.
|
| 27 |
+
|
| 28 |
+
EXCEPT AS EXPRESSLY STATED IN THIS LICENSE OR REQUIRED BY APPLICABLE
|
| 29 |
+
LAW, THE WORKS ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
|
| 30 |
+
OF ANY KIND INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES REGARDING
|
| 31 |
+
THE CONTENTS, ACCURACY, OR FITNESS FOR A PARTICULAR PURPOSE.
|
README.md
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
- de
|
| 5 |
+
license: other
|
| 6 |
+
thumbnail: https://huggingface.co/Aleph-Alpha/Llama-TFree-HAT-Pretrained-8B-DPO/raw/main/source/aleph_alpha_logo_thumbnail.png
|
| 7 |
+
license_name: open-aleph-license
|
| 8 |
+
license_link: LICENSE
|
| 9 |
+
tags:
|
| 10 |
+
- Aleph Alpha Research
|
| 11 |
+
- pytorch
|
| 12 |
+
- Hierarchical Autoregressive Transformer
|
| 13 |
+
- HAT
|
| 14 |
+
model-index:
|
| 15 |
+
- name: TFree-HAT-Pretrained-8B-Base
|
| 16 |
+
results: []
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
<div align="center">
|
| 20 |
+
<img src="source/aleph_alpha_logo.svg" width="60%" alt="Aleph Alpha Research Logo" />
|
| 21 |
+
</div>
|
| 22 |
+
|
| 23 |
+
<div align="center" style="line-height: 1;">
|
| 24 |
+
<a href="https://aleph-alpha.com/research/" target="_blank" style="margin: 2px;">
|
| 25 |
+
<img alt="Homepage" src="source/aleph_alpha_homepage_badge.svg" style="display: inline-block; vertical-align: middle;" />
|
| 26 |
+
</a>
|
| 27 |
+
<a href="https://huggingface.co/Aleph-Alpha" target="_blank" style="margin: 2px;">
|
| 28 |
+
<img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-AlephAlpha%20Research-e3ff00?color=e3ff00&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
|
| 29 |
+
</a>
|
| 30 |
+
</div>
|
| 31 |
+
|
| 32 |
+
<div align="center" style="line-height: 1;">
|
| 33 |
+
<a href="https://twitter.com/Aleph__Alpha" target="_blank" style="margin: 2px;">
|
| 34 |
+
<img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-AlephAlpha_Research-white?logo=x&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
|
| 35 |
+
</a>
|
| 36 |
+
<a href="https://huggingface.co/Aleph-Alpha/TFree-HAT-Pretrained-8B-Base/blob/main/LICENSE" style="margin: 2px;">
|
| 37 |
+
<img alt="License" src="https://img.shields.io/badge/License-Open Aleph License-white?&color=white" style="display: inline-block; vertical-align: middle;"/>
|
| 38 |
+
</a>
|
| 39 |
+
</div>
|
| 40 |
+
|
| 41 |
+
<hr>
|
| 42 |
+
|
| 43 |
+
# TFree-HAT-Pretrained-8B-Base
|
| 44 |
+
<!-- markdownlint-disable first-line-h1 -->
|
| 45 |
+
<!-- markdownlint-disable html -->
|
| 46 |
+
<!-- markdownlint-disable no-duplicate-header -->
|
| 47 |
+
|
| 48 |
+
This model card provides an overview of our **TFree-HAT-Pretrained-8B-Base** model , which is a foundation model developed by Aleph Alpha Research* and publicly available under the Open Aleph License, a license explicitly allowing for non-commercial research and educational use.
|
| 49 |
+
|
| 50 |
+
The model is based on our Hierarchical Autoregressive Transformer (HAT) architecture which is described originally in our [paper](https://arxiv.org/abs/2501.10322). This novel architecture integrates character-level encoding and decoding with the word-level backbone, allowing for improved text compression (less sequence positions) and performance in the languages it has been trained on, and potentially higher robustness to prompt changes, as well as improved adaptability to new languages & domains via fine-tuning.
|
| 51 |
+
|
| 52 |
+
The model was pre-trained in English & German on carefully curated data in compliance with applicable EU and national regulations, including copyright and data privacy laws. It shows strong proficiency in German, while also beating Llama 3.1 on many benchmarks in English.
|
| 53 |
+
|
| 54 |
+
You can find model weights and their corresponding safetensors conversions at the following links:
|
| 55 |
+
|
| 56 |
+
| Model Name | Description |
|
| 57 |
+
| --- | --- |
|
| 58 |
+
| `TFree-HAT-Pretrained-8B-Base` | [Link](https://huggingface.co/Aleph-Alpha/TFree-HAT-Pretrained-8B-Base) - pre-trained for English and German, adapted to a maximum context length of 32900 words |
|
| 59 |
+
|
| 60 |
+
# Model Access
|
| 61 |
+
|
| 62 |
+
We provide access to our models through the channels listed below.
|
| 63 |
+
|
| 64 |
+
- **HuggingFace**: The model’s weights as well as basic inference implementation are available on HuggingFace under the [Open Aleph License](https://github.com/Aleph-Alpha/.github/blob/main/oal.pdf), a license explicitly allowing for non-commercial research and educational use.
|
| 65 |
+
|
| 66 |
+
We do not collect PII (personally identifiable information) for any of these channels. We do not log user inputs to the models. We do not train on user data.
|
| 67 |
+
|
| 68 |
+
**Note**: The same models are made available to users regardless of their geographic location and their input language but subject to sanction regimes, technology export regulations, and other restrictions that may apply. The same offering is provided to all countries within and external to the European Union if no legal restrictions apply.
|
| 69 |
+
|
| 70 |
+
# How to use
|
| 71 |
+
|
| 72 |
+
## Inference
|
| 73 |
+
|
| 74 |
+
We provide an inference module compatible with HuggingFace Transformers for running model inference. We recommend pinning the transformers library to version 4.46.3. Before executing the inference example below, make sure the [hat-splitter package](https://pypi.org/project/hat-splitter/) is installed in your environment.
|
| 75 |
+
|
| 76 |
+
```shell
|
| 77 |
+
pip install 'hat-splitter>=0.1.9' 'transformers==4.46.3' torch
|
| 78 |
+
pip install flash_attn
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
Download model weights and run inference using the following example:
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
import torch
|
| 85 |
+
from transformers import AutoModelForCausalLM
|
| 86 |
+
INPUT ="When was Rome founded?"
|
| 87 |
+
MODEL_ID = "Aleph-Alpha/TFree-HAT-Pretrained-8B-Base"
|
| 88 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 89 |
+
trust_remote_code=True,
|
| 90 |
+
pretrained_model_name_or_path=MODEL_ID,
|
| 91 |
+
attn_implementation="flash_attention_2",
|
| 92 |
+
).to("cuda", torch.bfloat16)
|
| 93 |
+
input_ids, cumulative_word_lengths = model._prepare_input(INPUT)
|
| 94 |
+
model_output = model.generate(
|
| 95 |
+
input_ids,
|
| 96 |
+
cumulative_seq_lengths_per_word=cumulative_word_lengths,
|
| 97 |
+
max_new_tokens=300,
|
| 98 |
+
use_cache=False,
|
| 99 |
+
)
|
| 100 |
+
print("Prompt: ", INPUT)
|
| 101 |
+
print("Completion: ", model_output.completion_text)
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
Please note that the realized inference speed strongly depends on the maturity of the inference implementation beyond the intrinsic text compression of any model. Besides this huggingface transformers-based inference solution, we are also releasing a [vLLM-based inference solution](https://github.com/Aleph-Alpha/vllm) for our models that is optimized for batched inference. Please note that this vLLM inference for HAT is still under active development.
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# Evaluation
|
| 108 |
+
|
| 109 |
+
**Performance**: Our T-Free models deliver performance on par with strong tokenizer-based models such as [Llama 3.1 8B Base](https://huggingface.co/meta-llama/Llama-3.1-8B). Respective benchmarks and results can be found in the tables below.
|
| 110 |
+
|
| 111 |
+
**Efficiency**: Our tokenizer-free approach results in improved text compression, providing a foundation for improved efficiency in inference speed. We measure in terms of words processed across all languages and domains. We define the metric as **tokenizer fertility** or **bytes per sequence position**, where a higher value indicates better performance. Latency and throughput are currently out of scope for research-centric evaluations and will be addressed in the future. Currently, our evaluation framework automatically measures **bytes per sequence position** across datasets, allowing us to derive text compression scores and analyze variations across different dataset distributions. The end to end resulting efficiency is depends on the inference implementation beyond the scope of the here provided inference implementation and reported compression scores.
|
| 112 |
+
|
| 113 |
+
**Disclaimer**: The results presented below were generated using our internal inference implementation, not the inference module mentioned above. As a sanity check, we reproduced some of the benchmarks using our evaluation framework with the huggingface inference code, but other results might still deviate slightly. We will also make source-available both our evaluation framework and a [high-performance vLLM integration](https://github.com/Aleph-Alpha/vllm) for this model to ensure reproducibility.
|
| 114 |
+
|
| 115 |
+
**Metric Glossary**
|
| 116 |
+
|
| 117 |
+
`log_acc`: Average Accuracy Loglikelihood<br>
|
| 118 |
+
`norm_log_acc`: Average Normalized Loglikelihood Accuracy<br>
|
| 119 |
+
`comp_acc`: Average Completion Accuracy<br>
|
| 120 |
+
`norm_prob_mass`: Average Probability Mass Normalized<br>
|
| 121 |
+
`bleu`: Average BLEU Score<br>
|
| 122 |
+
`rouge_gm`: Average ROUGE-Geometric-Mean<br>
|
| 123 |
+
`F1`: Average F1<br>
|
| 124 |
+
`CS`: Chatbot Style<br>
|
| 125 |
+
`IF`: Instruction Following<br>
|
| 126 |
+
`LC`: Language Consistency<br>
|
| 127 |
+
`CI`: Concordance Index<br>
|
| 128 |
+
`ES`: Exponential Similarity
|
| 129 |
+
|
| 130 |
+
## Pre-training Benchmarks
|
| 131 |
+
|
| 132 |
+
| Group | Task | Metric Name | Num Fewshot | [TFree-HAT-Pretrained-8B-Base](https://huggingface.co/Aleph-Alpha/TFree-HAT-Pretrained-8B-Base) | [Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B) | [TFree-HAT-Pretrained-8B-Base](https://huggingface.co/Aleph-Alpha/TFree-HAT-Pretrained-8B-Base) Compression | [Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B) Compression |
|
| 133 |
+
| --- | --- | --- | --- | --- | --- | --- | --- |
|
| 134 |
+
| Knowledge | MMLU | `norm_log_acc` | 5 | **0.669** | 0.668 | **5.184** | 4.278 |
|
| 135 |
+
| Knowledge | MMLU Pro | `norm_log_acc` | 5 | **0.387** | 0.367 | **4.734** | 3.731 |
|
| 136 |
+
| Knowledge | OpenBookQA | `norm_log_acc` | 10 | 0.360 | **0.366** | **4.982** | 4.724 |
|
| 137 |
+
| Knowledge | TriviaQA | `comp_acc` | 10 | 0.657 | **0.695** | **5.317** | 4.221 |
|
| 138 |
+
| Knowledge | TruthfulQA | `norm_prob_mass` | 6 | **0.304** | 0.279 | **4.945** | 4.197 |
|
| 139 |
+
| Reasoning | ARC Challenge | `norm_log_acc` | 25 | **0.592** | 0.538 | **5.514** | 4.924 |
|
| 140 |
+
| Reasoning | Winogrande | `norm_log_acc` | 5 | **0.754** | 0.747 | **5.158** | 4.909 |
|
| 141 |
+
| German | MMMLU | `norm_log_acc` | 5 | **0.618** | 0.576 | **6.056** | 3.410 |
|
| 142 |
+
| German | WMT16 | `bleu` | 5 | 34.465 | **34.998** | **5.968** | 4.210 |
|
| 143 |
+
| German | WMT20 | `bleu` | 5 | **33.212** | 32.892 | **6.269** | 4.222 |
|
| 144 |
+
| Math | GSM8K | `comp_acc` | 8 | 0.508 | **0.528** | **3.840** | 3.332 |
|
| 145 |
+
| Long context | GSM8K | `comp_acc` | 16 | 0.520 | --- | 3.837 | --- |
|
| 146 |
+
| Long context | Long Bench v2 | `norm_log_acc` | 10 | 0.299 | --- | 5.125 | --- |
|
| 147 |
+
| Long context German | Long Bench v2 | `norm_log_acc` | 10 | 0.282 | --- | 5.872 | --- |
|
| 148 |
+
| Safety | Winogender | `norm_log_acc` | 5 | **0.662** | 0.636 | **5.232** | 4.799 |
|
| 149 |
+
|
| 150 |
+
# Training Details
|
| 151 |
+
|
| 152 |
+
## Model Architecture
|
| 153 |
+
|
| 154 |
+
The model uses a hierarchical autoregressive transformer (HAT) architecture consisting of three components: encoder, backbone, and decoder, together with connector layers between components. Encoder, backbone, and decoder are all instances of autoregressive transformers with pre-norm residual blocks in the style of Llama, using a SwiGLU unit as a feed-forward block, with all model parameters active during training and inference. The backbone model uses standard causal attention, while the encoder and decoder use local causal attention with a finite look-back window. The architecture of the backbone largely follows the design of LLama 3.1 8B (with embedding and language modeling head removed and weights randomly initialized). In addition, we added per-head QK-norm in the backbone, which we found important for training stability.
|
| 155 |
+
|
| 156 |
+
The encoder processes input text as a sequence of UTF-8 bytes and produces a sequence of activations of the same length. This sequence is then split into chunks corresponding to words or other semantic units in the text (this is further explained below). In the encoder-backbone connector layer, for each word, a learned latent vector cross-attends to its corresponding chunk of encoder activations. The resulting sequence of latent vectors then serves as input to the backbone. The backbone processes this latent sequence and produces a sequence of word-level representations. Finally, the decoder module is another transformer that acts on the byte-level activations and has an LM head that produces next-byte probabilities. To make use of the higher level information stored in the word-level embeddings during decoding, another cross-attention mechanism is used. In each transformer block of the decoder, every byte-level position cross-attends to the backbone’s word-level representations that correspond to the words preceding this byte.
|
| 157 |
+
|
| 158 |
+
## Encoder module
|
| 159 |
+
|
| 160 |
+
| | **8B** |
|
| 161 |
+
| --- | --- |
|
| 162 |
+
| Number of layers | 6 |
|
| 163 |
+
| Number of attention heads | 8 |
|
| 164 |
+
| Head size | 128 |
|
| 165 |
+
| Number of Key-Value heads | 8 |
|
| 166 |
+
| Hidden size | 1024 |
|
| 167 |
+
| Cross-attention hidden size | 4096 |
|
| 168 |
+
| MLP expansion factor | 2.75 |
|
| 169 |
+
| MLP type | SwiGLU |
|
| 170 |
+
| Sequence length | 262144 |
|
| 171 |
+
| Position embeddings | RoPE with base 1e5 |
|
| 172 |
+
| Attention type | causal, local with window size 768 |
|
| 173 |
+
| QK-norm | disabled |
|
| 174 |
+
|
| 175 |
+
## Backbone module
|
| 176 |
+
|
| 177 |
+
| | **8B** |
|
| 178 |
+
| --- | --- |
|
| 179 |
+
| Number of layers | 32 |
|
| 180 |
+
| Number of attention heads | 32 |
|
| 181 |
+
| Head size | 128 |
|
| 182 |
+
| Number of Key-Value heads | 8 |
|
| 183 |
+
| Hidden size | 4096 |
|
| 184 |
+
| MLP expansion factor | 3.5 |
|
| 185 |
+
| MLP type | SwiGLU |
|
| 186 |
+
| Sequence length | 32900 |
|
| 187 |
+
| Position embeddings | RoPE with base 5e5 |
|
| 188 |
+
| Attention type | causal |
|
| 189 |
+
| QK-norm | per head |
|
| 190 |
+
|
| 191 |
+
## Decoder module
|
| 192 |
+
|
| 193 |
+
| | **8B** |
|
| 194 |
+
| --- | --- |
|
| 195 |
+
| Number of layers | 4 |
|
| 196 |
+
| Number of attention heads | 8 |
|
| 197 |
+
| Head size | 128 |
|
| 198 |
+
| Number of Key-Value heads | 8 |
|
| 199 |
+
| Hidden size | 1024 |
|
| 200 |
+
| Cross-attention hidden size | 4096 |
|
| 201 |
+
| MLP expansion factor | 2.75 |
|
| 202 |
+
| MLP type | SwiGLU |
|
| 203 |
+
| Sequence length | 262144 |
|
| 204 |
+
| Position embeddings | RoPE with base 1e5 |
|
| 205 |
+
| Attention type | causal, local with window size 768 |
|
| 206 |
+
| QK-norm | disabled |
|
| 207 |
+
|
| 208 |
+
**Parameter count**
|
| 209 |
+
|
| 210 |
+
Total: `7,192,507,136`
|
| 211 |
+
Encoder: `119,293,696`
|
| 212 |
+
Backbone: `6,979,592,192`
|
| 213 |
+
Decoder: `93,621,248`
|
| 214 |
+
|
| 215 |
+
We note that one distinctive property of our tokenizer-free architectures is that encoder and decoder are substantially smaller than typical embedding and language model head layers of tokenizer-based models. Because of this, while our models share the architecture with Llama 3.1 8B (plus the added QK-norm), they are closer to 7B than 8B parameters in total.
|
| 216 |
+
|
| 217 |
+
**Word splitter**
|
| 218 |
+
|
| 219 |
+
To split arbitrary byte sequences, we adopted the guidelines from [UAX #29](https://unicode.org/reports/tr29/), which splits text into words for common Western languages but also produces meaningful semantic units for other types of languages (e.g. Chinese, Japanese, Korean). From now on, we refer to these splits as words.
|
| 220 |
+
|
| 221 |
+
We also merged leading whitespace and trailing punctuation into the words to reduce sequence length at the word level.
|
| 222 |
+
|
| 223 |
+
To improve the processing of code and math documents, we made additional adjustments to the Unicode splitter. First, we split instances of camel cases like FooBar into Foo and Bar. Second, we treated math symbols (again by Unicode standard) as separate words.
|
| 224 |
+
|
| 225 |
+
## Pre-Training
|
| 226 |
+
|
| 227 |
+
**Approach**
|
| 228 |
+
|
| 229 |
+
We randomly initialized all model parameters. The model was then trained on the next-byte-prediction objective on a large and diverse document corpus (see below). Initially, we trained on sequences up to 3500 words for a total amount of nearly 4T words. We used global batch-size of 1024 (2.5M words) and followed a warmup-stable-decay schedule with a warmup of 5000 steps, a phase of stable learning rate 2e-3 for 945000 steps and inverse-square-root cooldown to learning rate 0 over the last 50000 steps. We employed weight decay of 0.05 for all parameters except for the embedding and normalization parameters. We employed QK-norm per head and attention logit softcapping at 100, which we found to be important for training stability during pretraining.
|
| 230 |
+
|
| 231 |
+
We then continued training on sequences of up to 32900 words for another 2500 steps with global batch size 128, totaling to 10.5B words, upweighting longer documents to make use of the extended context. We used warmup-stable-decay learning rate schedule with 500 steps warmup, a phase of stable learning 2e-4, and a final decay to 0 over the last 500 steps. We disabled attention logit softcapping during this long-context adaptation such that it is not required during inference.
|
| 232 |
+
|
| 233 |
+
The training was conducted in our [Scaling framework](https://github.com/Aleph-Alpha/scaling).
|
| 234 |
+
|
| 235 |
+
**Data sources**
|
| 236 |
+
|
| 237 |
+
The model was trained on a filtered subset of diverse corpora of text data including proprietary curated datasets, high-quality web content, public domain sources, German texts, mathematical texts, and programming code. The proportions and sources of data we used in the pre-training were:
|
| 238 |
+
|
| 239 |
+
English Language Data (70%)
|
| 240 |
+
|
| 241 |
+
- curated web and synthetic data (63%)
|
| 242 |
+
|
| 243 |
+
- high quality curated sources such as Wikipedia and public domain books (7%)
|
| 244 |
+
|
| 245 |
+
German Language Data (7%)
|
| 246 |
+
|
| 247 |
+
- curated web and synthetic data (6.3%)
|
| 248 |
+
|
| 249 |
+
- high quality curated sources such as Wikipedia and public domain books (0.7%)
|
| 250 |
+
|
| 251 |
+
Mathematical Content (5%)
|
| 252 |
+
|
| 253 |
+
- mathematical code and proofs (2%)
|
| 254 |
+
|
| 255 |
+
- mathematical word problems and equations (3%)
|
| 256 |
+
|
| 257 |
+
Programming Code (18%)
|
| 258 |
+
|
| 259 |
+
- general programming code (11%)
|
| 260 |
+
|
| 261 |
+
- high-quality and synthetic Python code (7%)
|
| 262 |
+
|
| 263 |
+
## Data curation
|
| 264 |
+
|
| 265 |
+
We applied a range of curation techniques, e.g., for German as described in [Aleph-Alpha-GermanWeb](https://huggingface.co/datasets/Aleph-Alpha/Aleph-Alpha-GermanWeb). These include but are not limited to:
|
| 266 |
+
|
| 267 |
+
- URL filtering. We used a URL filter developed to filter out fraudulent, harmful, and illegal content from an explicit blocklist, e.g., adult websites, or URLs containing words associated with fraudulent, harmful, or adult content.
|
| 268 |
+
|
| 269 |
+
- Text extraction. Natural language texts which were embedded HTML and other web programming languages were extracted using the [Resiliparse](https://github.com/chatnoir-eu/chatnoir-resiliparse) text extractor.
|
| 270 |
+
|
| 271 |
+
- Language identification. We used a [fastText language classifier](https://fasttext.cc/docs/en/language-identification.html) trained on character n-grams from Wikipedia to identify, retain, and sort texts into English and German.
|
| 272 |
+
|
| 273 |
+
- Repetition removal. We applied heuristic methods for detection and removal of repetitions on the line, paragraph, and character level.
|
| 274 |
+
|
| 275 |
+
- Document- and line-level filtering. We utilized additional document-level heuristics to ensure documents had reasonable numbers and quality of words, naturalistic symbols-to-words and numbers-to-words ratios, not predominantly made up of bullet points, and a sufficient quantity of real words.
|
| 276 |
+
|
| 277 |
+
- Deduplication. Using exact and fuzzy deduplication to remove duplicate documents.
|
| 278 |
+
|
| 279 |
+
## Synthetic data
|
| 280 |
+
|
| 281 |
+
We also generated synthetic data by using permissively-licensed LLMs.
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
## Legal Compliance
|
| 285 |
+
|
| 286 |
+
We acknowledge and abide by applicable national and international regulations, including copyright, data privacy, and other related legislation. Any text and data mining by us is performed in compliance with Directive (EU) 2019/790 and its respective national transposition. During the training and fine-tuning of our models, we comply with applicable data privacy laws, including Regulation (EU) 2016/679 (GDPR) and national data privacy regulations. To the extent possible and foreseeable, we also took legislation with forthcoming obligations into account, such as the obligations for General Purpose AI Models under Regulation (EU) 2024/1689 (EU AI Act), and will constantly monitor such developments and adapt our products and this model card accordingly.
|
| 287 |
+
|
| 288 |
+
# Resource Usage
|
| 289 |
+
|
| 290 |
+
## Compute & Training Efficiency
|
| 291 |
+
|
| 292 |
+
The following table shows the compute resources used in the training stages for the 8B models.
|
| 293 |
+
|
| 294 |
+
| **Model** | **Training phase** | **GPUs** | **Approximate average power consumption per GPU** | **Approximate GPU hours** |
|
| 295 |
+
| --- | --- | --- | --- | --- |
|
| 296 |
+
| 8B | Pre-training (part 1) | 256 x H200 | 460W | 111,822 |
|
| 297 |
+
| 8B | Pre-training (part 2) | 256 x H100 | 460W | 151,289 |
|
| 298 |
+
| 8B | Long context adaptation | 256 x H100 | 190W | 5,328 |
|
| 299 |
+
|
| 300 |
+
## Environmental Impact
|
| 301 |
+
|
| 302 |
+
Our H200 and A100 infrastructure runs entirely on 100% renewable energy, ensuring that no CO₂ emissions are directly incurred from training. In addition to this, the H200 data center boasts a power usage effectiveness (PUE) of ≤1.2. Its operation also maintains a net-zero water footprint. Specific number on renewable energy usage for the H100 GPUs is not yet available to us.
|
| 303 |
+
|
| 304 |
+
To estimate the carbon footprint of inference, we base our calculations on publicly available data from the infrastructure provider and, where applicable, standard emissions accounting methodology. We report:
|
| 305 |
+
|
| 306 |
+
- **Carbon emitted**: GPU runtime emissions
|
| 307 |
+
|
| 308 |
+
- **Carbon emitted accounting for PUE**: GPU runtime emissions scaled by the data center's PUE
|
| 309 |
+
|
| 310 |
+
Because the data centers operate fully on renewable energy, both metrics for its operation (excluding infrastructure-related emissions, e.g., initial chip manufacturing) are effectively zero. For H100 GPU infrastructure no information has been made available to us.
|
| 311 |
+
|
| 312 |
+
| Metric | H200 GPU | H100 GPU | A100 GPU |
|
| 313 |
+
| --- | --- | --- | --- |
|
| 314 |
+
| Carbon emitted | 0 kg CO₂ | no information available | 0 kg CO₂ |
|
| 315 |
+
| Carbon emitted accounting for PUE | 0 kg CO₂ | no information available | 0 kg CO₂ |
|
| 316 |
+
|
| 317 |
+
## Power Consumption
|
| 318 |
+
|
| 319 |
+
| GPU Model | Max Power (W) |
|
| 320 |
+
| --- | --- |
|
| 321 |
+
| A100 | 400 W |
|
| 322 |
+
| H100 | 700 W |
|
| 323 |
+
| H200 | 700 W |
|
| 324 |
+
|
| 325 |
+
Numbers may be contextualized with reference to publicly available studies, such as the carbon footprint of language model training.
|
| 326 |
+
|
| 327 |
+
# Intended Use
|
| 328 |
+
|
| 329 |
+
These models are intended to be deployed as components of AI systems or applications. Use-cases and the model's capabilities include but are not limited to: text generation, classification, summarization, question answering, and labeling. Note that applications might require additional model adaptations or components for guarding against unwanted application behavior or model output.
|
| 330 |
+
|
| 331 |
+
## Non-Permitted Use
|
| 332 |
+
|
| 333 |
+
Our models shall not be used for illegal or unlawful actions of any kind and with any illegal or unlawful content. This includes in particular prohibited practices according to Article 5 of Regulation (EU) 2024/1689 (EU AI Act) and other activities such as engaging in terrorism, violence, human trafficking, illegal distribution of materials to minors, sexual solicitation, any other criminal activities, harassment, discrimination, creating or promoting malicious code or activities risking death or harm, including those related to military or nuclear applications, and activities not in compliance with sanction regimes, technology export regulations, and other restrictions that may apply. The models are to be used following ethical standards. The utilization of our technology is always governed by, and may be limited in accordance with, our Terms and Conditions, the Open Aleph License, or any specific agreement we might have established with you.
|
| 334 |
+
|
| 335 |
+
Although we do not inspect the requests sent to our API, we regularly review and monitor potential violations that may be related to our models and depending on the circumstances of the specific case take legal action against them. This includes but is not limited to, enforcement to remove published model content, requesting compensation for damages caused, and account termination or removal of credits.
|
| 336 |
+
|
| 337 |
+
For non-anonymous reports, we also provide an appeals mechanism for usage policy violations via our dedicated contact address [[email protected]](mailto:[email protected]) to communicate with us.
|
| 338 |
+
|
| 339 |
+
Customers and partners are enabled to use our [ticketing system](https://servicedesk.aleph-alpha.de/external) for appeals, claims, and feedback.
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# Risks and Limitations
|
| 343 |
+
|
| 344 |
+
**Note:** Language models are **not agents** and not optimized for prescriptive actions. The use of language models in high-stake environments, for critical decisions or to support a user's wellbeing should be performed with additional guardrails in place.
|
| 345 |
+
|
| 346 |
+
## Risk Categories
|
| 347 |
+
|
| 348 |
+
In the following sections, we describe risk categories and provide examples of completions we would consider inappropriate or harmful. We then describe steps to minimize these risks.
|
| 349 |
+
|
| 350 |
+
**Harmful Language**
|
| 351 |
+
|
| 352 |
+
Large language models can sometimes generate undesired outputs that are unsuitable for certain applications. This includes producing content with harmful language, discriminative content, inappropriate tone and style, systemic biases, or suggestions that might encourage illegal actions. Such outputs can also include incorrect, outdated information, or material that is not suitable for all ages. While we constantly take efforts to reduce the likelihood of such undesired outputs, this possibility can never be fully ruled out. To minimize these issues, the following strategies can be employed:
|
| 353 |
+
|
| 354 |
+
- Abide by the guidance on illegal use provided for in this Model Card.
|
| 355 |
+
|
| 356 |
+
- Crafting prompts carefully to guide the model's output more effectively.
|
| 357 |
+
|
| 358 |
+
- Utilizing a finetuned model (often referred to as a control or instruct model) that prioritizes using explicitly provided information.
|
| 359 |
+
|
| 360 |
+
- Employing a finetuned model designed to maintain an appropriate tone and style, including avoiding offensive language.
|
| 361 |
+
|
| 362 |
+
- Conducting additional validations at the application level to ensure output quality and appropriateness.
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
### Systemic Biases
|
| 366 |
+
|
| 367 |
+
Language models obtain world-knowledge from their pre-training data and may therefore exhibit the same systematic biases that are present in the data. Differing deployment scenarios (including differing cultural contexts) can expose systematic biases in different ways. We acknowledge the cultural diversity of communities and users inside and outside the EU. For larger deployments, we encourage users to track systematic biases relevant to their use-case, and we are happy to consult on bespoke fine-tunings to alleviate such biases.
|
| 368 |
+
|
| 369 |
+
### Outdated World Knowledge
|
| 370 |
+
|
| 371 |
+
| **Prompt** | **Completion** |
|
| 372 |
+
| --- | --- |
|
| 373 |
+
| What was the warmest year in human history? | The warmest year in human history, based on global average temperatures, is 2016. However, it's important to note that the ranking of the warmest years can vary slightly depending on the dataset used and the methodology applied. |
|
| 374 |
+
|
| 375 |
+
Pre-training was performed using a fixed dataset, created at a fixed date in the past. Accordingly, the world knowledge of foundation models is limited to the information contained in its training data. More recent information may not be known to the model or misunderstood when presented as input during live usage. In the above example, the model is convinced that 2016 was the warmest year in human history, however, 2023 ended up breaking that record. This information can not be known by the model due to its knowledge cutoff.
|
| 376 |
+
|
| 377 |
+
Risks include:
|
| 378 |
+
|
| 379 |
+
- Generation of personally identifiable information. Models are not explicitly trained to provide such information, but may seem to provide personally identifiable information. This does not necessarily imply the presence of such information in training data, as hallucination is possible.
|
| 380 |
+
|
| 381 |
+
- Generation of unintended, irrelevant, or repetitive outputs. This includes the production of incorrect or outdated information.
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
Risks may be mitigated by:
|
| 385 |
+
|
| 386 |
+
- Injecting context, where relevant.
|
| 387 |
+
|
| 388 |
+
- Crafting prompts carefully to guide the model's output more effectively.
|
| 389 |
+
|
| 390 |
+
- Performing validations on the application layer, e.g., classifying the output.
|
| 391 |
+
|
| 392 |
+
- Using the repetition penalty, especially in the case of repetition, or other parameters available in the API (see [documentation](https://docs.aleph-alpha.com/api/complete/)).
|
| 393 |
+
|
| 394 |
+
- Avoiding of use cases targeted at retrieval of personally identifiable information.
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
### Political Bias
|
| 398 |
+
|
| 399 |
+
Our models have not been optimized to represent a political opinion or take a specific point of view. They may generate outputs that contradict a user's opinion or expectation, e.g., produce hateful, violent or inappropriate, biased, or discriminatory content. Such behavior may be addressed by:
|
| 400 |
+
|
| 401 |
+
- Crafting prompts carefully to guide the model's output more effectively.
|
| 402 |
+
|
| 403 |
+
- Performing validations on the application layer, e.g., via Red-Teaming or classifying the output.
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
### Mistaken for a Human
|
| 407 |
+
|
| 408 |
+
| **Prompt** | **Completion** |
|
| 409 |
+
| --- | --- |
|
| 410 |
+
| Good morning, today is such a beautiful day! | Hello! It sounds like you're starting your day on a positive note. I'm glad to hear that the weather is beautiful. How are you feeling today? Is there anything specific you'd like to discuss or any tasks you'd like some help with? Whether it's planning your day, sharing some thoughts, or getting advice on something, I'm here to assist! Enjoy your day! |
|
| 411 |
+
|
| 412 |
+
Users may attribute human traits to AI models. This also includes the fact that content generated by the model is not explicitly detectable at this point. It is therefore required to:
|
| 413 |
+
|
| 414 |
+
- Inform end users that they are interacting with or reading output of an AI.
|
| 415 |
+
|
| 416 |
+
- Design the system in a way that mitigates the impact of unintended interpretation of the output.
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
### Other Errors
|
| 420 |
+
|
| 421 |
+
Any AI module can produce errors, even after implementing all the recommended measures. When integrating foundation language models into an application, users should:
|
| 422 |
+
|
| 423 |
+
- be aware of the risk of (harmful) failure cases and implement the use case in a way that mitigates such risks.
|
| 424 |
+
|
| 425 |
+
- be aware that foundation models do not contain application logic, e.g., content filters. Enforcement policies relevant to the use case need to be implemented in the application layer.
|
| 426 |
+
|
| 427 |
+
- avoid unsupervised use in high-stakes environments.
|
| 428 |
+
|
| 429 |
+
- validate output with adequate measures.
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
### Mitigation Approach
|
| 433 |
+
|
| 434 |
+
We specifically tailor model alignment and risk mitigation techniques to each user-facing application built on top of our models, working closely with our customers to refine them according to their unique requirements. Our intention is for these models to undergo further fine-tuning by us and our customers, utilizing their own datasets alongside our support and datasets to ensure suitability for end-user applications, including harm mitigation efforts. Our customers are responsible for adhering to the terms and conditions when aligning the models in their downstream applications.
|
| 435 |
+
|
| 436 |
+
### Reproducibility
|
| 437 |
+
|
| 438 |
+
Some inference parameters, e.g., temperature, lead to the random sampling of outputs, which precludes the reproducibility of outputs. Even when such parameters are not in use, outputs may diverge slightly on a numeric level for technical reasons. One may implement the following measures if needed:
|
| 439 |
+
|
| 440 |
+
- Logging of past model outputs on the application layer (Aleph Alpha Research is not storing any data and/or using any data provided in prompts for the training of its LLMs).
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
This list of risks, biases, and limitations may not be complete, as improving the understanding and behavior of language models is an ongoing research topic in the AI science community.
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
\*Aleph Alpha Research refers to Aleph Alpha Research GmbH
|
| 447 |
+
|
| 448 |
+
[hat-paper]: https://arxiv.org/abs/2501.10322
|
config.json
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"HATForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "config.HATArchitectureConfig",
|
| 7 |
+
"AutoModelForCausalLM": "model.HATForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"backbone_config": {
|
| 10 |
+
"hidden_size": 4096,
|
| 11 |
+
"intermediate_size": 14336,
|
| 12 |
+
"is_neox_style": true,
|
| 13 |
+
"key_query_norm": true,
|
| 14 |
+
"key_query_norm_per_head": true,
|
| 15 |
+
"max_position_embeddings": 3500,
|
| 16 |
+
"mlp_bias": false,
|
| 17 |
+
"num_attention_heads": 32,
|
| 18 |
+
"num_hidden_layers": 32,
|
| 19 |
+
"num_key_value_heads": 8,
|
| 20 |
+
"rms_norm_eps": 1e-05,
|
| 21 |
+
"rope_scaling": {
|
| 22 |
+
"rope_type": "default"
|
| 23 |
+
},
|
| 24 |
+
"rope_theta": 500000,
|
| 25 |
+
"sliding_window": null,
|
| 26 |
+
"transformers_version": null,
|
| 27 |
+
"use_cache": true,
|
| 28 |
+
"vocab_size": 0
|
| 29 |
+
},
|
| 30 |
+
"decoder_config": {
|
| 31 |
+
"cross_attention_config": {
|
| 32 |
+
"attention_num_kv_heads": 8,
|
| 33 |
+
"hidden_size": 1024,
|
| 34 |
+
"hidden_size_kv": 4096,
|
| 35 |
+
"hidden_size_q": 1024,
|
| 36 |
+
"key_query_norm": true,
|
| 37 |
+
"key_query_norm_per_head": true,
|
| 38 |
+
"num_attention_heads": 8,
|
| 39 |
+
"word_window_size": 1
|
| 40 |
+
},
|
| 41 |
+
"cross_attn_every_layer": true,
|
| 42 |
+
"hidden_size": 1024,
|
| 43 |
+
"intermediate_size": 2816,
|
| 44 |
+
"is_neox_style": true,
|
| 45 |
+
"key_query_norm": true,
|
| 46 |
+
"key_query_norm_per_head": true,
|
| 47 |
+
"max_position_embeddings": 28000,
|
| 48 |
+
"mlp_bias": false,
|
| 49 |
+
"num_attention_heads": 8,
|
| 50 |
+
"num_hidden_layers": 4,
|
| 51 |
+
"num_key_value_heads": 8,
|
| 52 |
+
"rms_norm_eps": 1e-05,
|
| 53 |
+
"rope_scaling": {
|
| 54 |
+
"rope_type": "default"
|
| 55 |
+
},
|
| 56 |
+
"rope_theta": 100000,
|
| 57 |
+
"sliding_window": 768,
|
| 58 |
+
"transformers_version": null,
|
| 59 |
+
"use_cache": true,
|
| 60 |
+
"vocab_size": 256
|
| 61 |
+
},
|
| 62 |
+
"encoder_config": {
|
| 63 |
+
"cross_attention_config": {
|
| 64 |
+
"attention_num_kv_heads": 32,
|
| 65 |
+
"hidden_size": 4096,
|
| 66 |
+
"hidden_size_kv": 1024,
|
| 67 |
+
"hidden_size_q": 4096,
|
| 68 |
+
"key_query_norm": true,
|
| 69 |
+
"key_query_norm_per_head": true,
|
| 70 |
+
"num_attention_heads": 32,
|
| 71 |
+
"word_window_size": 1
|
| 72 |
+
},
|
| 73 |
+
"hidden_size": 1024,
|
| 74 |
+
"intermediate_size": 2816,
|
| 75 |
+
"is_neox_style": true,
|
| 76 |
+
"key_query_norm": true,
|
| 77 |
+
"key_query_norm_per_head": true,
|
| 78 |
+
"max_position_embeddings": 28000,
|
| 79 |
+
"mlp_bias": false,
|
| 80 |
+
"num_attention_heads": 8,
|
| 81 |
+
"num_hidden_layers": 6,
|
| 82 |
+
"num_key_value_heads": 8,
|
| 83 |
+
"rms_norm_eps": 1e-05,
|
| 84 |
+
"rope_scaling": {
|
| 85 |
+
"rope_type": "default"
|
| 86 |
+
},
|
| 87 |
+
"rope_theta": 100000,
|
| 88 |
+
"sliding_window": 768,
|
| 89 |
+
"transformers_version": null,
|
| 90 |
+
"use_cache": true,
|
| 91 |
+
"vocab_size": 256
|
| 92 |
+
},
|
| 93 |
+
"max_position_embeddings": 28000,
|
| 94 |
+
"max_word_size": 100,
|
| 95 |
+
"model_type": "hierarchical_autoregressive_transformer",
|
| 96 |
+
"sliding_window": 768,
|
| 97 |
+
"special_token_dict": {},
|
| 98 |
+
"torch_dtype": "bfloat16",
|
| 99 |
+
"transformers_version": "4.46.3"
|
| 100 |
+
}
|
config.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 5 |
+
from transformers.models.llama.configuration_llama import LlamaConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class TransformerHATModelConfig(LlamaConfig):
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
hidden_size: int,
|
| 13 |
+
num_hidden_layers: int,
|
| 14 |
+
num_attention_heads: int,
|
| 15 |
+
num_key_value_heads: int,
|
| 16 |
+
rms_norm_eps: float,
|
| 17 |
+
intermediate_size: int,
|
| 18 |
+
max_position_embeddings: int,
|
| 19 |
+
rope_scaling: dict,
|
| 20 |
+
rope_theta: float,
|
| 21 |
+
mlp_bias: bool,
|
| 22 |
+
use_cache: bool = True,
|
| 23 |
+
sliding_window: int | None = None,
|
| 24 |
+
vocab_size: int = 0,
|
| 25 |
+
hidden_act: str = "silu",
|
| 26 |
+
key_query_norm: bool = False,
|
| 27 |
+
key_query_norm_per_head: bool = False,
|
| 28 |
+
is_neox_style: bool = True,
|
| 29 |
+
**kwargs,
|
| 30 |
+
):
|
| 31 |
+
super().__init__(
|
| 32 |
+
vocab_size=vocab_size,
|
| 33 |
+
hidden_size=hidden_size,
|
| 34 |
+
num_hidden_layers=num_hidden_layers,
|
| 35 |
+
num_attention_heads=num_attention_heads,
|
| 36 |
+
num_key_value_heads=num_key_value_heads,
|
| 37 |
+
hidden_act=hidden_act,
|
| 38 |
+
rms_norm_eps=rms_norm_eps,
|
| 39 |
+
intermediate_size=intermediate_size,
|
| 40 |
+
max_position_embeddings=max_position_embeddings,
|
| 41 |
+
rope_scaling=rope_scaling,
|
| 42 |
+
rope_theta=rope_theta,
|
| 43 |
+
mlp_bias=mlp_bias,
|
| 44 |
+
use_cache=use_cache,
|
| 45 |
+
**kwargs,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
self.sliding_window = sliding_window
|
| 49 |
+
self.key_query_norm = key_query_norm
|
| 50 |
+
self.key_query_norm_per_head = key_query_norm_per_head
|
| 51 |
+
self.is_neox_style = is_neox_style
|
| 52 |
+
|
| 53 |
+
def to_dict(self):
|
| 54 |
+
config_dict = {
|
| 55 |
+
"vocab_size": self.vocab_size,
|
| 56 |
+
"hidden_size": self.hidden_size,
|
| 57 |
+
"num_hidden_layers": self.num_hidden_layers,
|
| 58 |
+
"num_attention_heads": self.num_attention_heads,
|
| 59 |
+
"num_key_value_heads": self.num_key_value_heads,
|
| 60 |
+
"rms_norm_eps": self.rms_norm_eps,
|
| 61 |
+
"intermediate_size": self.intermediate_size,
|
| 62 |
+
"max_position_embeddings": self.max_position_embeddings,
|
| 63 |
+
"rope_scaling": self.rope_scaling,
|
| 64 |
+
"rope_theta": self.rope_theta,
|
| 65 |
+
"mlp_bias": self.mlp_bias,
|
| 66 |
+
"use_cache": self.use_cache,
|
| 67 |
+
"sliding_window": self.sliding_window,
|
| 68 |
+
"transformers_version": self.transformers_version,
|
| 69 |
+
"key_query_norm": self.key_query_norm,
|
| 70 |
+
"key_query_norm_per_head": self.key_query_norm_per_head,
|
| 71 |
+
"is_neox_style": self.is_neox_style,
|
| 72 |
+
}
|
| 73 |
+
return config_dict
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class CrossAttentionConfig:
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
hidden_size: int,
|
| 81 |
+
hidden_size_q: int,
|
| 82 |
+
hidden_size_kv: int,
|
| 83 |
+
num_attention_heads: int,
|
| 84 |
+
attention_num_kv_heads: int,
|
| 85 |
+
word_window_size: int,
|
| 86 |
+
key_query_norm: bool,
|
| 87 |
+
key_query_norm_per_head: bool,
|
| 88 |
+
):
|
| 89 |
+
self.hidden_size = hidden_size
|
| 90 |
+
self.hidden_size_q = hidden_size_q
|
| 91 |
+
self.hidden_size_kv = hidden_size_kv
|
| 92 |
+
self.num_attention_heads = num_attention_heads
|
| 93 |
+
self.attention_num_kv_heads = attention_num_kv_heads
|
| 94 |
+
self.word_window_size = word_window_size
|
| 95 |
+
self.key_query_norm = key_query_norm
|
| 96 |
+
self.key_query_norm_per_head = key_query_norm_per_head
|
| 97 |
+
|
| 98 |
+
def to_dict(self):
|
| 99 |
+
return {
|
| 100 |
+
"hidden_size_q": self.hidden_size_q,
|
| 101 |
+
"hidden_size_kv": self.hidden_size_kv,
|
| 102 |
+
"hidden_size": self.hidden_size,
|
| 103 |
+
"num_attention_heads": self.num_attention_heads,
|
| 104 |
+
"attention_num_kv_heads": self.attention_num_kv_heads,
|
| 105 |
+
"word_window_size": self.word_window_size,
|
| 106 |
+
"key_query_norm": self.key_query_norm,
|
| 107 |
+
"key_query_norm_per_head": self.key_query_norm_per_head,
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@dataclass
|
| 112 |
+
class DecoderHATModelConfig(TransformerHATModelConfig):
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
num_attention_heads: int,
|
| 116 |
+
num_key_value_heads: int,
|
| 117 |
+
sliding_window: int,
|
| 118 |
+
cross_attention_config: CrossAttentionConfig,
|
| 119 |
+
cross_attn_every_layer: bool,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
super().__init__(
|
| 123 |
+
num_attention_heads=num_attention_heads,
|
| 124 |
+
num_key_value_heads=num_key_value_heads,
|
| 125 |
+
sliding_window=sliding_window,
|
| 126 |
+
**kwargs,
|
| 127 |
+
)
|
| 128 |
+
self.cross_attn_every_layer = cross_attn_every_layer
|
| 129 |
+
self.cross_attention_config = cross_attention_config
|
| 130 |
+
|
| 131 |
+
def to_dict(self):
|
| 132 |
+
config_dict = super().to_dict()
|
| 133 |
+
config_dict["cross_attn_every_layer"] = self.cross_attn_every_layer
|
| 134 |
+
config_dict["cross_attention_config"] = self.cross_attention_config.to_dict()
|
| 135 |
+
return config_dict
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def from_dict(cls, config_dict, **kwargs):
|
| 139 |
+
config_dict = config_dict.copy() # Avoid modifying the original dict
|
| 140 |
+
config_dict.update(kwargs) # Apply overrides
|
| 141 |
+
dict_config = config_dict.pop("cross_attention_config", {})
|
| 142 |
+
cross_attention_config = CrossAttentionConfig(**dict_config)
|
| 143 |
+
config_dict["cross_attention_config"] = cross_attention_config
|
| 144 |
+
return cls(**config_dict)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@dataclass
|
| 148 |
+
class EncoderHATModelConfig(TransformerHATModelConfig):
|
| 149 |
+
def __init__(
|
| 150 |
+
self,
|
| 151 |
+
cross_attention_config: CrossAttentionConfig,
|
| 152 |
+
**kwargs,
|
| 153 |
+
):
|
| 154 |
+
super().__init__(**kwargs)
|
| 155 |
+
self.cross_attention_config = cross_attention_config
|
| 156 |
+
|
| 157 |
+
@classmethod
|
| 158 |
+
def from_dict(cls, config_dict, **kwargs):
|
| 159 |
+
config_dict = config_dict.copy() # Avoid modifying the original dict
|
| 160 |
+
config_dict.update(kwargs) # Apply overrides
|
| 161 |
+
dict_config = config_dict.pop("cross_attention_config", {})
|
| 162 |
+
cross_attention_config = CrossAttentionConfig(**dict_config)
|
| 163 |
+
config_dict["cross_attention_config"] = cross_attention_config
|
| 164 |
+
|
| 165 |
+
return cls(**config_dict)
|
| 166 |
+
|
| 167 |
+
def to_dict(self):
|
| 168 |
+
config_dict = super().to_dict()
|
| 169 |
+
if self.cross_attention_config:
|
| 170 |
+
config_dict["cross_attention_config"] = self.cross_attention_config.to_dict()
|
| 171 |
+
return config_dict
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@dataclass
|
| 175 |
+
class HATArchitectureConfig(PretrainedConfig):
|
| 176 |
+
model_type: str = "hierarchical_autoregressive_transformer"
|
| 177 |
+
|
| 178 |
+
def __init__(
|
| 179 |
+
self,
|
| 180 |
+
special_token_dict: dict | None = None,
|
| 181 |
+
encoder_config: EncoderHATModelConfig | None = None,
|
| 182 |
+
backbone_config: TransformerHATModelConfig | None = None,
|
| 183 |
+
decoder_config: DecoderHATModelConfig | None = None,
|
| 184 |
+
model_type: str = "hierarchical_autoregressive_transformer",
|
| 185 |
+
eos_token_id: int = 192,
|
| 186 |
+
max_word_size: int = 100,
|
| 187 |
+
sliding_window: int = 768,
|
| 188 |
+
max_position_embeddings: int = 262144,
|
| 189 |
+
**kwargs,
|
| 190 |
+
):
|
| 191 |
+
super().__init__(**kwargs)
|
| 192 |
+
self.encoder_config = encoder_config
|
| 193 |
+
self.backbone_config = backbone_config
|
| 194 |
+
self.decoder_config = decoder_config
|
| 195 |
+
self.model_type = model_type
|
| 196 |
+
self.eos_token_id = eos_token_id
|
| 197 |
+
self.max_word_size = max_word_size
|
| 198 |
+
self.special_token_dict = special_token_dict
|
| 199 |
+
self.transformers_version = "4.46.3"
|
| 200 |
+
|
| 201 |
+
# set these for out of the box vllm inference
|
| 202 |
+
self.architectures = ["HATDecoderForCausalLM"]
|
| 203 |
+
self.sliding_window = sliding_window
|
| 204 |
+
self.max_position_embeddings = max_position_embeddings
|
| 205 |
+
self.torch_dtype = "bfloat16"
|
| 206 |
+
|
| 207 |
+
@classmethod
|
| 208 |
+
def from_dict(cls, config_dict, **kwargs):
|
| 209 |
+
"""
|
| 210 |
+
Instantiates a HATArchitectureConfig from a Python dictionary of parameters.
|
| 211 |
+
|
| 212 |
+
Overrides the base `from_dict` to correctly handle nested config objects.
|
| 213 |
+
"""
|
| 214 |
+
config_dict = config_dict.copy() # Avoid modifying the original dict
|
| 215 |
+
config_dict.update(kwargs) # Apply overrides
|
| 216 |
+
|
| 217 |
+
# Pop and instantiate nested config dictionaries
|
| 218 |
+
encoder_dict = config_dict.pop("encoder_config", {})
|
| 219 |
+
backbone_dict = config_dict.pop("backbone_config", {})
|
| 220 |
+
decoder_dict = config_dict.pop("decoder_config", {})
|
| 221 |
+
|
| 222 |
+
# Instantiate nested configs
|
| 223 |
+
encoder_config = EncoderHATModelConfig.from_dict(encoder_dict) if encoder_dict else None
|
| 224 |
+
backbone_config = TransformerHATModelConfig.from_dict(backbone_dict) if backbone_dict else None
|
| 225 |
+
decoder_config = DecoderHATModelConfig.from_dict(decoder_dict) if decoder_dict else None
|
| 226 |
+
special_token_dict = config_dict.pop("special_token_dict", {"<|eot_id|>": 192})
|
| 227 |
+
max_word_size = config_dict.pop("max_word_size", 100)
|
| 228 |
+
return cls(
|
| 229 |
+
encoder_config=encoder_config,
|
| 230 |
+
backbone_config=backbone_config,
|
| 231 |
+
decoder_config=decoder_config,
|
| 232 |
+
special_token_dict=special_token_dict,
|
| 233 |
+
max_word_size=max_word_size,
|
| 234 |
+
**config_dict,
|
| 235 |
+
), {}
|
| 236 |
+
|
| 237 |
+
def to_dict(self):
|
| 238 |
+
config_dict = {}
|
| 239 |
+
if self.encoder_config:
|
| 240 |
+
config_dict["encoder_config"] = self.encoder_config.to_dict()
|
| 241 |
+
if self.backbone_config:
|
| 242 |
+
config_dict["backbone_config"] = self.backbone_config.to_dict()
|
| 243 |
+
if self.decoder_config:
|
| 244 |
+
config_dict["decoder_config"] = self.decoder_config.to_dict()
|
| 245 |
+
config_dict["model_type"] = self.model_type
|
| 246 |
+
config_dict["transformers_version"] = self.transformers_version
|
| 247 |
+
config_dict["auto_map"] = {"AutoConfig": "config.HATArchitectureConfig", "AutoModelForCausalLM": "model.HATForCausalLM"}
|
| 248 |
+
config_dict["special_token_dict"] = self.special_token_dict
|
| 249 |
+
|
| 250 |
+
# print these out to the config for vllm
|
| 251 |
+
config_dict["max_word_size"] = self.max_word_size
|
| 252 |
+
config_dict["sliding_window"] = self.sliding_window
|
| 253 |
+
config_dict["max_position_embeddings"] = self.max_position_embeddings
|
| 254 |
+
config_dict["torch_dtype"] = self.torch_dtype
|
| 255 |
+
config_dict["architectures"] = self.architectures
|
| 256 |
+
return config_dict
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class EncoderHATModel(nn.Module):
|
| 260 |
+
def __init__(self, config: HATArchitectureConfig, *args, **kwargs):
|
| 261 |
+
super().__init__(*args, **kwargs)
|
| 262 |
+
self.config = config
|
config.yaml
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
encoder_config:
|
| 2 |
+
vocab_size: 256
|
| 3 |
+
hidden_size: 1024
|
| 4 |
+
num_hidden_layers: 6
|
| 5 |
+
num_attention_heads: 8
|
| 6 |
+
num_key_value_heads: 8
|
| 7 |
+
rms_norm_eps: 1.0e-05
|
| 8 |
+
intermediate_size: 2816
|
| 9 |
+
max_position_embeddings: 28000
|
| 10 |
+
rope_scaling:
|
| 11 |
+
rope_type: default
|
| 12 |
+
rope_theta: 100000
|
| 13 |
+
mlp_bias: false
|
| 14 |
+
use_cache: true
|
| 15 |
+
sliding_window: 768
|
| 16 |
+
transformers_version: null
|
| 17 |
+
key_query_norm: true
|
| 18 |
+
key_query_norm_per_head: true
|
| 19 |
+
is_neox_style: true
|
| 20 |
+
cross_attention_config:
|
| 21 |
+
hidden_size_q: 4096
|
| 22 |
+
hidden_size_kv: 1024
|
| 23 |
+
hidden_size: 4096
|
| 24 |
+
num_attention_heads: 32
|
| 25 |
+
attention_num_kv_heads: 32
|
| 26 |
+
word_window_size: 1
|
| 27 |
+
key_query_norm: true
|
| 28 |
+
key_query_norm_per_head: true
|
| 29 |
+
backbone_config:
|
| 30 |
+
vocab_size: 0
|
| 31 |
+
hidden_size: 4096
|
| 32 |
+
num_hidden_layers: 32
|
| 33 |
+
num_attention_heads: 32
|
| 34 |
+
num_key_value_heads: 8
|
| 35 |
+
rms_norm_eps: 1.0e-05
|
| 36 |
+
intermediate_size: 14336
|
| 37 |
+
max_position_embeddings: 3500
|
| 38 |
+
rope_scaling:
|
| 39 |
+
rope_type: default
|
| 40 |
+
rope_theta: 500000
|
| 41 |
+
mlp_bias: false
|
| 42 |
+
use_cache: true
|
| 43 |
+
sliding_window: null
|
| 44 |
+
transformers_version: null
|
| 45 |
+
key_query_norm: true
|
| 46 |
+
key_query_norm_per_head: true
|
| 47 |
+
is_neox_style: true
|
| 48 |
+
decoder_config:
|
| 49 |
+
vocab_size: 256
|
| 50 |
+
hidden_size: 1024
|
| 51 |
+
num_hidden_layers: 4
|
| 52 |
+
num_attention_heads: 8
|
| 53 |
+
num_key_value_heads: 8
|
| 54 |
+
rms_norm_eps: 1.0e-05
|
| 55 |
+
intermediate_size: 2816
|
| 56 |
+
max_position_embeddings: 28000
|
| 57 |
+
rope_scaling:
|
| 58 |
+
rope_type: default
|
| 59 |
+
rope_theta: 100000
|
| 60 |
+
mlp_bias: false
|
| 61 |
+
use_cache: true
|
| 62 |
+
sliding_window: 768
|
| 63 |
+
transformers_version: null
|
| 64 |
+
key_query_norm: true
|
| 65 |
+
key_query_norm_per_head: true
|
| 66 |
+
is_neox_style: true
|
| 67 |
+
cross_attn_every_layer: true
|
| 68 |
+
cross_attention_config:
|
| 69 |
+
hidden_size_q: 1024
|
| 70 |
+
hidden_size_kv: 4096
|
| 71 |
+
hidden_size: 1024
|
| 72 |
+
num_attention_heads: 8
|
| 73 |
+
attention_num_kv_heads: 8
|
| 74 |
+
word_window_size: 1
|
| 75 |
+
key_query_norm: true
|
| 76 |
+
key_query_norm_per_head: true
|
| 77 |
+
model_type: hierarchical_autoregressive_transformer
|
| 78 |
+
transformers_version: 4.46.3
|
| 79 |
+
auto_map:
|
| 80 |
+
AutoConfig: config.HATArchitectureConfig
|
| 81 |
+
AutoModelForCausalLM: model.HATForCausalLM
|
| 82 |
+
special_token_dict: {}
|
| 83 |
+
max_word_size: 100
|
| 84 |
+
sliding_window: 768
|
| 85 |
+
max_position_embeddings: 28000
|
| 86 |
+
torch_dtype: bfloat16
|
| 87 |
+
architectures:
|
| 88 |
+
- HATDecoderForCausalLM
|
generation_config.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"transformers_version": "4.46.3"
|
| 4 |
+
}
|
model-00001-of-00006.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b63eea8783a24fd114863084cb643599940cb7a53324b980f6f111ab264e2280
|
| 3 |
+
size 4922789928
|
model-00002-of-00006.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:02e25bef21a7ba415e7e2c35c7c1f1f7e9813f6ad477bf41e4bbf6e34dab8b2c
|
| 3 |
+
size 4832013880
|
model-00003-of-00006.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4437c2f7f5145df1c4ba34c0652c3a8d84a42b31fff03edbf475d05b60b4cbec
|
| 3 |
+
size 4999820824
|
model-00004-of-00006.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c2b92e4eaba076d7d18f6776983d4f2b89c2232a60136ec820a35374a0eb3777
|
| 3 |
+
size 4999820832
|
model-00005-of-00006.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1e49586a2b7a12f36a76567739a430498ade7cb61be567df4047e73e1bc48e51
|
| 3 |
+
size 4832013928
|
model-00006-of-00006.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2582415526c586f8815750c56f5bec08198ab142c31dd7c175d5868b180a8245
|
| 3 |
+
size 4014747208
|
model.py
ADDED
|
@@ -0,0 +1,951 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
from collections.abc import Sequence
|
| 3 |
+
from importlib.metadata import PackageNotFoundError, version
|
| 4 |
+
from typing import Callable
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from einops import rearrange
|
| 9 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_func
|
| 10 |
+
from transformers import PreTrainedModel
|
| 11 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 12 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 13 |
+
from transformers.utils import ModelOutput
|
| 14 |
+
|
| 15 |
+
from .config import (
|
| 16 |
+
CrossAttentionConfig,
|
| 17 |
+
DecoderHATModelConfig,
|
| 18 |
+
EncoderHATModelConfig,
|
| 19 |
+
HATArchitectureConfig,
|
| 20 |
+
TransformerHATModelConfig,
|
| 21 |
+
)
|
| 22 |
+
from .splitter import HATSplitter
|
| 23 |
+
from .norm import RMSNorm
|
| 24 |
+
from .transformer_backbone import (
|
| 25 |
+
LlamaDecoderLayer,
|
| 26 |
+
LlamaRotaryEmbedding,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
transformers_version = version("transformers")
|
| 31 |
+
if transformers_version != "4.46.3":
|
| 32 |
+
print(f"Warning: Expecected transformers version 4.46.3, but found {transformers_version}. Outputs might be different.")
|
| 33 |
+
except PackageNotFoundError:
|
| 34 |
+
print("transformers is not installed")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sample_argmax(logits: torch.Tensor) -> torch.Tensor:
|
| 38 |
+
return torch.argmax(logits, dim=-1)[:, -1]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
LLAMA_TEMPLATE = """<|begin_of_text|><|start_header_id|>system<|end_header_id|>
|
| 42 |
+
You are a helpful assistant. You give engaging, well-structured answers to user inquiries.<|eot_id|><|start_header_id|>user<|end_header_id|>
|
| 43 |
+
{input}<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class HATCache(Cache):
|
| 47 |
+
encoder_cache: DynamicCache
|
| 48 |
+
backbone_cache: DynamicCache
|
| 49 |
+
decoder_cache: DynamicCache
|
| 50 |
+
|
| 51 |
+
def __init__(self, *args, **kwargs):
|
| 52 |
+
super().__init__(*args, **kwargs)
|
| 53 |
+
self.encoder_cache = DynamicCache()
|
| 54 |
+
self.backbone_cache = DynamicCache()
|
| 55 |
+
self.decoder_cache = DynamicCache()
|
| 56 |
+
|
| 57 |
+
def get_backbone_cache(self) -> DynamicCache:
|
| 58 |
+
return self.backbone_cache
|
| 59 |
+
|
| 60 |
+
def get_decoder_cache(self) -> DynamicCache:
|
| 61 |
+
return self.decoder_cache
|
| 62 |
+
|
| 63 |
+
def get_encoder_cache(self) -> DynamicCache:
|
| 64 |
+
return self.encoder_cache
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def rotate_half(x):
|
| 68 |
+
"""Rotates half the hidden dims of the input."""
|
| 69 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 70 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 71 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def apply_rotary_pos_emb(q, k, q_cos=None, q_sin=None, k_cos=None, k_sin=None, unsqueeze_dim=1):
|
| 75 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 76 |
+
and allows for different sequence lengths.
|
| 77 |
+
Args:
|
| 78 |
+
q (`torch.Tensor`): The query tensor.
|
| 79 |
+
k (`torch.Tensor`): The key tensor.
|
| 80 |
+
q_cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 81 |
+
q_sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 82 |
+
k_cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 83 |
+
k_sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 84 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 85 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze
|
| 86 |
+
cos[position_ids] and sin[position_ids] so that they can be properly
|
| 87 |
+
broadcasted to the dimensions of q and k. For example, note
|
| 88 |
+
that cos[position_ids] and sin[position_ids] have the shape
|
| 89 |
+
[batch_size, seq_len, head_dim]. Then, if q and
|
| 90 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting
|
| 91 |
+
unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids]
|
| 92 |
+
broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 93 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 94 |
+
Returns:
|
| 95 |
+
`tuple(torch.Tensor)` comprising of the query and key
|
| 96 |
+
tensors rotated using the Rotary Position Embedding.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
q_cos = q_cos.unsqueeze(unsqueeze_dim)
|
| 100 |
+
q_sin = q_sin.unsqueeze(unsqueeze_dim)
|
| 101 |
+
k_cos = k_cos.unsqueeze(unsqueeze_dim)
|
| 102 |
+
k_sin = k_sin.unsqueeze(unsqueeze_dim)
|
| 103 |
+
q_embed = (q * q_cos) + (rotate_half(q) * q_sin)
|
| 104 |
+
k_embed = (k * k_cos) + (rotate_half(k) * k_sin)
|
| 105 |
+
|
| 106 |
+
return q_embed, k_embed
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class HATBackbone(nn.Module):
|
| 110 |
+
def __init__(self, config: TransformerHATModelConfig, *args, **kwargs):
|
| 111 |
+
super().__init__(*args, **kwargs)
|
| 112 |
+
|
| 113 |
+
self.layers = nn.ModuleList([LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 114 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
| 115 |
+
|
| 116 |
+
def forward(
|
| 117 |
+
self,
|
| 118 |
+
hidden_states: torch.Tensor,
|
| 119 |
+
position_ids: torch.Tensor | None = None,
|
| 120 |
+
past_key_values: DynamicCache | None = None,
|
| 121 |
+
use_cache: bool | None = False,
|
| 122 |
+
) -> BaseModelOutputWithPast:
|
| 123 |
+
if use_cache and past_key_values is None:
|
| 124 |
+
past_key_values = DynamicCache()
|
| 125 |
+
|
| 126 |
+
if position_ids is None:
|
| 127 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 128 |
+
position_ids = torch.arange(
|
| 129 |
+
past_seen_tokens,
|
| 130 |
+
past_seen_tokens + hidden_states.shape[1],
|
| 131 |
+
device=hidden_states.device,
|
| 132 |
+
).unsqueeze(0)
|
| 133 |
+
|
| 134 |
+
# create position embeddings to be shared across the decoder layers
|
| 135 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 136 |
+
|
| 137 |
+
for backbone_layer in self.layers:
|
| 138 |
+
layer_outputs = backbone_layer(
|
| 139 |
+
hidden_states,
|
| 140 |
+
position_ids=position_ids,
|
| 141 |
+
past_key_value=past_key_values,
|
| 142 |
+
use_cache=use_cache,
|
| 143 |
+
position_embeddings=position_embeddings,
|
| 144 |
+
)
|
| 145 |
+
hidden_states = layer_outputs[0]
|
| 146 |
+
|
| 147 |
+
return CausalLMOutputWithPast(
|
| 148 |
+
hidden_states=hidden_states,
|
| 149 |
+
past_key_values=past_key_values if use_cache else None,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class HATDecoderConnector(nn.Module):
|
| 154 |
+
def __init__(self, backbone_hiden_dim: int, *args, **kwargs):
|
| 155 |
+
super().__init__(*args, **kwargs)
|
| 156 |
+
self.first_word_embedding = torch.nn.Parameter(
|
| 157 |
+
torch.empty(
|
| 158 |
+
1,
|
| 159 |
+
1,
|
| 160 |
+
backbone_hiden_dim,
|
| 161 |
+
device="cuda",
|
| 162 |
+
dtype=torch.bfloat16,
|
| 163 |
+
)
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
def forward(
|
| 167 |
+
self,
|
| 168 |
+
backbone_activations: torch.Tensor,
|
| 169 |
+
):
|
| 170 |
+
activations = backbone_activations.clone()
|
| 171 |
+
activations[:, -1:, :] = self.first_word_embedding
|
| 172 |
+
activations = torch.roll(activations, shifts=1, dims=1)
|
| 173 |
+
return activations
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class HATDecoderBlock(nn.Module):
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
add_cross_attention: bool,
|
| 180 |
+
config: DecoderHATModelConfig,
|
| 181 |
+
layer_idx: int,
|
| 182 |
+
*args,
|
| 183 |
+
**kwargs,
|
| 184 |
+
):
|
| 185 |
+
super().__init__(*args, **kwargs)
|
| 186 |
+
self.add_cross_attention = add_cross_attention
|
| 187 |
+
self.config = config
|
| 188 |
+
self.llama_layer = LlamaDecoderLayer(config, layer_idx)
|
| 189 |
+
self.llama_layer.self_attn.sliding_window = config.sliding_window
|
| 190 |
+
if add_cross_attention:
|
| 191 |
+
self.cross_attention = HATCrossAttention(
|
| 192 |
+
hidden_size=config.cross_attention_config.hidden_size,
|
| 193 |
+
hidden_size_kv=config.cross_attention_config.hidden_size_kv,
|
| 194 |
+
hidden_size_q=config.cross_attention_config.hidden_size_q,
|
| 195 |
+
config=config,
|
| 196 |
+
cross_attention_config=config.cross_attention_config,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
self.query_norm = RMSNorm(
|
| 200 |
+
config.cross_attention_config.hidden_size_q,
|
| 201 |
+
eps=config.rms_norm_eps,
|
| 202 |
+
device=torch.device("cuda"),
|
| 203 |
+
dtype=torch.bfloat16,
|
| 204 |
+
norm_in_fp32=False,
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
self.kv_norm = RMSNorm(
|
| 208 |
+
config.cross_attention_config.hidden_size_kv,
|
| 209 |
+
eps=config.rms_norm_eps,
|
| 210 |
+
device=torch.device("cuda"),
|
| 211 |
+
dtype=torch.bfloat16,
|
| 212 |
+
norm_in_fp32=False,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
def apply_norm(self, activations):
|
| 216 |
+
return self.query_norm(activations), self.kv_norm(activations)
|
| 217 |
+
|
| 218 |
+
def forward(
|
| 219 |
+
self,
|
| 220 |
+
encoder_activations,
|
| 221 |
+
backbone_activations,
|
| 222 |
+
byte_position_ids,
|
| 223 |
+
word_position_ids,
|
| 224 |
+
cumulative_seq_lengths_per_word,
|
| 225 |
+
position_embeddings,
|
| 226 |
+
past_key_values,
|
| 227 |
+
use_cache,
|
| 228 |
+
):
|
| 229 |
+
if self.add_cross_attention:
|
| 230 |
+
kv_activations = self.kv_norm(backbone_activations)
|
| 231 |
+
q_activations = self.query_norm(encoder_activations)
|
| 232 |
+
|
| 233 |
+
activations = self.cross_attention.forward(
|
| 234 |
+
q_activations=q_activations,
|
| 235 |
+
kv_activations=kv_activations,
|
| 236 |
+
position_ids_q=byte_position_ids,
|
| 237 |
+
position_ids_kv=word_position_ids,
|
| 238 |
+
cumulative_seq_q=cumulative_seq_lengths_per_word,
|
| 239 |
+
cumulative_seq_kv=torch.arange(0, kv_activations.size(1) + 1, device=encoder_activations.device, dtype=torch.int32),
|
| 240 |
+
causal=False,
|
| 241 |
+
)
|
| 242 |
+
encoder_activations = encoder_activations + activations
|
| 243 |
+
|
| 244 |
+
return self.llama_layer.forward(
|
| 245 |
+
hidden_states=encoder_activations,
|
| 246 |
+
position_ids=byte_position_ids,
|
| 247 |
+
position_embeddings=position_embeddings,
|
| 248 |
+
past_key_value=past_key_values,
|
| 249 |
+
use_cache=use_cache,
|
| 250 |
+
)[0]
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class HATDecoder(nn.Module):
|
| 254 |
+
def __init__(self, config: DecoderHATModelConfig, *args, **kwargs):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
self.decoder_layers = nn.Sequential()
|
| 258 |
+
for layer_idx in range(config.num_hidden_layers):
|
| 259 |
+
add_cross_attention = config.cross_attn_every_layer or layer_idx == 0
|
| 260 |
+
self.decoder_layers.add_module(
|
| 261 |
+
str(layer_idx),
|
| 262 |
+
HATDecoderBlock(
|
| 263 |
+
add_cross_attention,
|
| 264 |
+
config,
|
| 265 |
+
layer_idx,
|
| 266 |
+
),
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
| 270 |
+
|
| 271 |
+
def forward(
|
| 272 |
+
self,
|
| 273 |
+
backbone_activations: torch.Tensor,
|
| 274 |
+
activations: torch.Tensor,
|
| 275 |
+
cumulative_seq_lengths_per_word: torch.Tensor | None = None,
|
| 276 |
+
byte_position_ids: torch.Tensor | None = None,
|
| 277 |
+
word_position_ids: torch.Tensor | None = None,
|
| 278 |
+
past_key_values: DynamicCache | None = None,
|
| 279 |
+
use_cache: bool | None = False,
|
| 280 |
+
) -> BaseModelOutputWithPast:
|
| 281 |
+
if use_cache and past_key_values is None:
|
| 282 |
+
past_key_values = DynamicCache()
|
| 283 |
+
|
| 284 |
+
if byte_position_ids is None:
|
| 285 |
+
past_seen_bytes = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 286 |
+
byte_position_ids = torch.arange(
|
| 287 |
+
past_seen_bytes,
|
| 288 |
+
past_seen_bytes + activations.size(1),
|
| 289 |
+
device=activations.device,
|
| 290 |
+
dtype=torch.int32,
|
| 291 |
+
).unsqueeze(0)
|
| 292 |
+
|
| 293 |
+
if cumulative_seq_lengths_per_word is None:
|
| 294 |
+
cumulative_seq_lengths_per_word = torch.tensor([0, byte_position_ids.size(1)], dtype=byte_position_ids.dtype, device=byte_position_ids.device)
|
| 295 |
+
|
| 296 |
+
if word_position_ids is None:
|
| 297 |
+
raise ValueError() # TODO
|
| 298 |
+
|
| 299 |
+
position_embeddings = self.rotary_emb(activations, byte_position_ids)
|
| 300 |
+
|
| 301 |
+
for _, layer in enumerate(self.decoder_layers):
|
| 302 |
+
activations = layer(
|
| 303 |
+
encoder_activations=activations,
|
| 304 |
+
backbone_activations=backbone_activations,
|
| 305 |
+
position_embeddings=position_embeddings,
|
| 306 |
+
cumulative_seq_lengths_per_word=cumulative_seq_lengths_per_word,
|
| 307 |
+
byte_position_ids=byte_position_ids,
|
| 308 |
+
word_position_ids=word_position_ids,
|
| 309 |
+
past_key_values=past_key_values,
|
| 310 |
+
use_cache=use_cache,
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
return BaseModelOutputWithPast(
|
| 314 |
+
last_hidden_state=activations,
|
| 315 |
+
past_key_values=past_key_values if use_cache else None,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class HATCrossAttention(nn.Module):
|
| 320 |
+
def __init__(
|
| 321 |
+
self,
|
| 322 |
+
hidden_size: int,
|
| 323 |
+
hidden_size_q: int,
|
| 324 |
+
hidden_size_kv: int,
|
| 325 |
+
config: EncoderHATModelConfig | DecoderHATModelConfig,
|
| 326 |
+
cross_attention_config: CrossAttentionConfig,
|
| 327 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 328 |
+
):
|
| 329 |
+
super().__init__()
|
| 330 |
+
self.hidden_size = hidden_size
|
| 331 |
+
self.hidden_size_q = hidden_size_q
|
| 332 |
+
self.hidden_size_kv = hidden_size_kv
|
| 333 |
+
self.num_heads = cross_attention_config.num_attention_heads
|
| 334 |
+
self.num_key_value_heads = cross_attention_config.attention_num_kv_heads
|
| 335 |
+
self.num_repeat_kv = cross_attention_config.num_attention_heads // cross_attention_config.attention_num_kv_heads
|
| 336 |
+
self.head_dim = hidden_size // self.num_heads
|
| 337 |
+
self.key_query_norm = cross_attention_config.key_query_norm
|
| 338 |
+
self.key_query_norm_per_head = cross_attention_config.key_query_norm_per_head
|
| 339 |
+
|
| 340 |
+
self.q_proj = nn.Linear(
|
| 341 |
+
in_features=hidden_size_q,
|
| 342 |
+
out_features=hidden_size,
|
| 343 |
+
dtype=dtype,
|
| 344 |
+
bias=False,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
self.k_proj = nn.Linear(
|
| 348 |
+
in_features=hidden_size_kv,
|
| 349 |
+
out_features=hidden_size // self.num_repeat_kv,
|
| 350 |
+
dtype=dtype,
|
| 351 |
+
bias=False,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
self.v_proj = nn.Linear(
|
| 355 |
+
in_features=hidden_size_kv,
|
| 356 |
+
out_features=hidden_size // self.num_repeat_kv,
|
| 357 |
+
dtype=dtype,
|
| 358 |
+
bias=False,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
if self.key_query_norm:
|
| 362 |
+
if self.key_query_norm_per_head:
|
| 363 |
+
# Both query and key have head dim equal to self.hidden_size_per_attention_head
|
| 364 |
+
query_norm_dimensions = self.head_dim
|
| 365 |
+
key_norm_dimensions = self.head_dim
|
| 366 |
+
else:
|
| 367 |
+
# Query dimensions across head is equal to hidden_size but key dimensions are divided
|
| 368 |
+
# by self.num_repeat_kv
|
| 369 |
+
query_norm_dimensions = self.hidden_size
|
| 370 |
+
key_norm_dimensions = self.hidden_size // self.num_repeat_kv
|
| 371 |
+
|
| 372 |
+
self.norm_query = RMSNorm(
|
| 373 |
+
dimensions=query_norm_dimensions,
|
| 374 |
+
eps=config.rms_norm_eps,
|
| 375 |
+
device=self.q_proj.weight.device,
|
| 376 |
+
dtype=dtype,
|
| 377 |
+
)
|
| 378 |
+
self.norm_key = RMSNorm(
|
| 379 |
+
dimensions=key_norm_dimensions,
|
| 380 |
+
eps=config.rms_norm_eps,
|
| 381 |
+
device=self.q_proj.weight.device,
|
| 382 |
+
dtype=dtype,
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
self.o_proj = nn.Linear(in_features=hidden_size, out_features=hidden_size_q, dtype=dtype, bias=False)
|
| 386 |
+
|
| 387 |
+
rope_theta = config.rope_theta
|
| 388 |
+
rope_type = config.rope_scaling["rope_type"]
|
| 389 |
+
|
| 390 |
+
self.rotary_emb = LlamaRotaryEmbedding(dim=self.head_dim, base=rope_theta, rope_type=rope_type)
|
| 391 |
+
|
| 392 |
+
def forward(
|
| 393 |
+
self,
|
| 394 |
+
q_activations: torch.Tensor,
|
| 395 |
+
kv_activations: torch.Tensor,
|
| 396 |
+
position_ids_q: torch.Tensor,
|
| 397 |
+
position_ids_kv: torch.Tensor,
|
| 398 |
+
cumulative_seq_kv: torch.Tensor,
|
| 399 |
+
cumulative_seq_q: torch.Tensor,
|
| 400 |
+
causal: bool = True,
|
| 401 |
+
use_cache: bool = False,
|
| 402 |
+
past_key_value: DynamicCache | None = None,
|
| 403 |
+
):
|
| 404 |
+
q_len = cumulative_seq_q[-1]
|
| 405 |
+
|
| 406 |
+
bsz, _, _ = kv_activations.size()
|
| 407 |
+
query_states = self.q_proj(q_activations)
|
| 408 |
+
key_states = self.k_proj(kv_activations)
|
| 409 |
+
value_states = self.v_proj(kv_activations)
|
| 410 |
+
|
| 411 |
+
if self.key_query_norm:
|
| 412 |
+
assert self.norm_query is not None
|
| 413 |
+
assert self.norm_key is not None
|
| 414 |
+
# query_states and key_states are bsz seq_len (h d)
|
| 415 |
+
if self.key_query_norm_per_head:
|
| 416 |
+
# for per head qk norm we need head dim to be the last dim
|
| 417 |
+
query_states = rearrange(
|
| 418 |
+
query_states,
|
| 419 |
+
"bsz seq_len (h d) -> bsz seq_len h d",
|
| 420 |
+
h=self.num_heads,
|
| 421 |
+
)
|
| 422 |
+
key_states = rearrange(
|
| 423 |
+
key_states,
|
| 424 |
+
"bsz seq_len (h d) -> bsz seq_len h d",
|
| 425 |
+
h=self.num_key_value_heads,
|
| 426 |
+
)
|
| 427 |
+
query_states = self.norm_query(query_states)
|
| 428 |
+
key_states = self.norm_key(key_states)
|
| 429 |
+
if self.key_query_norm_per_head:
|
| 430 |
+
query_states = rearrange(
|
| 431 |
+
query_states,
|
| 432 |
+
"bsz seq_len h d -> bsz seq_len (h d)",
|
| 433 |
+
)
|
| 434 |
+
key_states = rearrange(
|
| 435 |
+
key_states,
|
| 436 |
+
"bsz seq_len h d -> bsz seq_len (h d)",
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
# TODO get rid of the double rearrange, this is just for compatibility with scaling
|
| 440 |
+
query_states = rearrange(query_states, "bsz seq_len (h d) -> bsz h seq_len d", h=self.num_heads)
|
| 441 |
+
key_states = rearrange(
|
| 442 |
+
key_states,
|
| 443 |
+
"bsz seq_len (h d) -> bsz h seq_len d",
|
| 444 |
+
h=self.num_key_value_heads,
|
| 445 |
+
)
|
| 446 |
+
value_states = rearrange(
|
| 447 |
+
value_states,
|
| 448 |
+
"bsz seq_len (h d) -> bsz h seq_len d",
|
| 449 |
+
h=self.num_key_value_heads,
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
# WIP: Should word_positions_id respect document boundaries?
|
| 453 |
+
q_cos, q_sin = self.rotary_emb(query_states, position_ids_q)
|
| 454 |
+
k_cos, k_sin = self.rotary_emb(key_states, position_ids_kv)
|
| 455 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, q_cos=q_cos, q_sin=q_sin, k_cos=k_cos, k_sin=k_sin)
|
| 456 |
+
|
| 457 |
+
query_states = rearrange(query_states, "bsz h seq_len d -> (bsz seq_len) h d")
|
| 458 |
+
key_states = rearrange(key_states, "bsz h seq_len d -> (bsz seq_len) h d")
|
| 459 |
+
value_states = rearrange(value_states, "bsz h seq_len d -> (bsz seq_len) h d")
|
| 460 |
+
|
| 461 |
+
attn_output = flash_attn_varlen_func(
|
| 462 |
+
query_states,
|
| 463 |
+
key_states,
|
| 464 |
+
value_states,
|
| 465 |
+
cu_seqlens_q=cumulative_seq_q,
|
| 466 |
+
cu_seqlens_k=cumulative_seq_kv,
|
| 467 |
+
max_seqlen_q=self._get_max_seqlen(cumulative_seq_q),
|
| 468 |
+
max_seqlen_k=self._get_max_seqlen(cumulative_seq_kv),
|
| 469 |
+
causal=False,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 473 |
+
|
| 474 |
+
attn_output = self.o_proj(attn_output)
|
| 475 |
+
return attn_output
|
| 476 |
+
|
| 477 |
+
def _get_max_seqlen(self, cumulative_word_lengths: torch.Tensor):
|
| 478 |
+
diffs = cumulative_word_lengths[1:] - cumulative_word_lengths[:-1]
|
| 479 |
+
return int(diffs.max().item())
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class HATEncoderConnector(nn.Module):
|
| 483 |
+
def __init__(
|
| 484 |
+
self,
|
| 485 |
+
config: EncoderHATModelConfig,
|
| 486 |
+
backbone_hidden_size: int,
|
| 487 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 488 |
+
*args,
|
| 489 |
+
**kwargs,
|
| 490 |
+
):
|
| 491 |
+
super().__init__(*args, **kwargs)
|
| 492 |
+
self.latent_query = torch.nn.Parameter(
|
| 493 |
+
torch.empty(
|
| 494 |
+
1,
|
| 495 |
+
1,
|
| 496 |
+
backbone_hidden_size,
|
| 497 |
+
device="cuda",
|
| 498 |
+
dtype=dtype,
|
| 499 |
+
)
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
self.cross_attention_encoder_connector = HATCrossAttention(
|
| 503 |
+
hidden_size=config.cross_attention_config.hidden_size,
|
| 504 |
+
hidden_size_q=backbone_hidden_size,
|
| 505 |
+
hidden_size_kv=config.hidden_size,
|
| 506 |
+
config=config,
|
| 507 |
+
cross_attention_config=config.cross_attention_config,
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
def forward(
|
| 511 |
+
self,
|
| 512 |
+
hidden_states: torch.Tensor,
|
| 513 |
+
cumulative_seq_lengths_per_word: torch.Tensor,
|
| 514 |
+
word_position_ids: torch.Tensor,
|
| 515 |
+
byte_position_ids: torch.Tensor,
|
| 516 |
+
):
|
| 517 |
+
q_len = cumulative_seq_lengths_per_word.shape[0] - 1
|
| 518 |
+
latent_query_repeated = self.latent_query.expand(-1, q_len, -1)
|
| 519 |
+
cumulative_seq_lengths_q = torch.arange(
|
| 520 |
+
start=0,
|
| 521 |
+
end=latent_query_repeated.shape[1] + 1,
|
| 522 |
+
step=1,
|
| 523 |
+
device=self.latent_query.device,
|
| 524 |
+
dtype=torch.int32,
|
| 525 |
+
)
|
| 526 |
+
word_embeddings = self.cross_attention_encoder_connector.forward(
|
| 527 |
+
q_activations=latent_query_repeated,
|
| 528 |
+
kv_activations=hidden_states,
|
| 529 |
+
position_ids_q=word_position_ids,
|
| 530 |
+
position_ids_kv=byte_position_ids,
|
| 531 |
+
cumulative_seq_q=cumulative_seq_lengths_q,
|
| 532 |
+
cumulative_seq_kv=cumulative_seq_lengths_per_word,
|
| 533 |
+
)
|
| 534 |
+
return word_embeddings
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class HATEncoder(nn.Module):
|
| 538 |
+
def __init__(
|
| 539 |
+
self,
|
| 540 |
+
config: EncoderHATModelConfig,
|
| 541 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 542 |
+
*args,
|
| 543 |
+
**kwargs,
|
| 544 |
+
):
|
| 545 |
+
super().__init__(*args, **kwargs)
|
| 546 |
+
self.embedding_layer = nn.Embedding(config.vocab_size, config.hidden_size, dtype=dtype)
|
| 547 |
+
self.layers = nn.ModuleList([LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 548 |
+
for layer in self.layers:
|
| 549 |
+
layer.self_attn.sliding_window = config.sliding_window
|
| 550 |
+
|
| 551 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
| 552 |
+
|
| 553 |
+
self.word_window_size = config.cross_attention_config.word_window_size
|
| 554 |
+
|
| 555 |
+
def forward(
|
| 556 |
+
self,
|
| 557 |
+
input_ids: torch.Tensor,
|
| 558 |
+
cumulative_seq_lengths_per_word: torch.Tensor | None = None,
|
| 559 |
+
byte_position_ids: torch.Tensor | None = None,
|
| 560 |
+
word_position_ids: torch.Tensor | None = None, # TODO: Remove
|
| 561 |
+
past_key_values: DynamicCache | None = None,
|
| 562 |
+
use_cache: bool | None = False,
|
| 563 |
+
):
|
| 564 |
+
input_embeds = self.embedding_layer(input_ids)
|
| 565 |
+
|
| 566 |
+
if cumulative_seq_lengths_per_word is None:
|
| 567 |
+
cumulative_seq_lengths_per_word = torch.tensor([0, input_embeds.shape[1]], dtype=torch.int32, device=input_ids.device)
|
| 568 |
+
|
| 569 |
+
if use_cache and past_key_values is None:
|
| 570 |
+
past_key_values = DynamicCache()
|
| 571 |
+
|
| 572 |
+
if byte_position_ids is None:
|
| 573 |
+
past_seen_bytes = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 574 |
+
byte_position_ids = torch.arange(
|
| 575 |
+
past_seen_bytes,
|
| 576 |
+
past_seen_bytes + input_embeds.shape[1],
|
| 577 |
+
device=input_embeds.device,
|
| 578 |
+
).unsqueeze(0)
|
| 579 |
+
|
| 580 |
+
if word_position_ids is None:
|
| 581 |
+
raise ValueError() # TODO
|
| 582 |
+
|
| 583 |
+
hidden_states = input_embeds
|
| 584 |
+
|
| 585 |
+
# create position embeddings to be shared across the decoder layers
|
| 586 |
+
position_embeddings = self.rotary_emb(hidden_states, byte_position_ids)
|
| 587 |
+
|
| 588 |
+
for layer in self.layers:
|
| 589 |
+
layer_outputs = layer(
|
| 590 |
+
hidden_states,
|
| 591 |
+
position_ids=byte_position_ids,
|
| 592 |
+
past_key_value=past_key_values,
|
| 593 |
+
use_cache=use_cache,
|
| 594 |
+
position_embeddings=position_embeddings,
|
| 595 |
+
)
|
| 596 |
+
hidden_states = layer_outputs[0]
|
| 597 |
+
|
| 598 |
+
return CausalLMOutputWithPast(
|
| 599 |
+
hidden_states=hidden_states,
|
| 600 |
+
past_key_values=past_key_values if use_cache else None,
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
class HATForCausalLM(PreTrainedModel):
|
| 605 |
+
config_class = HATArchitectureConfig
|
| 606 |
+
_supports_flash_attn_2 = True
|
| 607 |
+
_supports_cache_class = True
|
| 608 |
+
|
| 609 |
+
def __init__(self, config: HATArchitectureConfig, *args, **kwargs):
|
| 610 |
+
super().__init__(config, *args, **kwargs)
|
| 611 |
+
self.config = config
|
| 612 |
+
self.eos_token_id = config.eos_token_id
|
| 613 |
+
self.encoder = HATEncoder(config.encoder_config)
|
| 614 |
+
self.encoder_connector = HATEncoderConnector(config.encoder_config, config.backbone_config.hidden_size)
|
| 615 |
+
self.backbone = HATBackbone(config.backbone_config)
|
| 616 |
+
self.decoder_connector = HATDecoderConnector(config.backbone_config.hidden_size)
|
| 617 |
+
self.decoder = HATDecoder(config.decoder_config)
|
| 618 |
+
self.splitter = HATSplitter(special_token_dict=config.special_token_dict, max_word_size=config.max_word_size)
|
| 619 |
+
self.layer_norm = RMSNorm(config.decoder_config.hidden_size, eps=config.decoder_config.rms_norm_eps, device=torch.device("cuda"), dtype=torch.bfloat16, norm_in_fp32=False)
|
| 620 |
+
self.lm_head = nn.Linear(
|
| 621 |
+
in_features=config.decoder_config.hidden_size,
|
| 622 |
+
out_features=config.decoder_config.vocab_size,
|
| 623 |
+
dtype=torch.bfloat16,
|
| 624 |
+
bias=False,
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
def forward(
|
| 628 |
+
self,
|
| 629 |
+
input_ids: torch.Tensor,
|
| 630 |
+
byte_position_ids: torch.Tensor,
|
| 631 |
+
cumulative_seq_lengths_per_word: torch.Tensor | None = None,
|
| 632 |
+
word_position_ids: torch.Tensor | None = None,
|
| 633 |
+
past_key_values: HATCache | None = None,
|
| 634 |
+
use_cache: bool = False,
|
| 635 |
+
):
|
| 636 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 637 |
+
|
| 638 |
+
if past_key_values is None and use_cache:
|
| 639 |
+
past_key_values = HATCache()
|
| 640 |
+
|
| 641 |
+
encoder_past_key_values = past_key_values.get_encoder_cache() if past_key_values is not None else None
|
| 642 |
+
backbone_past_key_values = past_key_values.get_backbone_cache() if past_key_values is not None else None
|
| 643 |
+
decoder_past_key_values = past_key_values.get_decoder_cache() if past_key_values is not None else None
|
| 644 |
+
|
| 645 |
+
encoder_output: BaseModelOutputWithPast = self.encoder(
|
| 646 |
+
input_ids=input_ids,
|
| 647 |
+
cumulative_seq_lengths_per_word=cumulative_seq_lengths_per_word,
|
| 648 |
+
byte_position_ids=byte_position_ids,
|
| 649 |
+
word_position_ids=word_position_ids,
|
| 650 |
+
past_key_values=encoder_past_key_values,
|
| 651 |
+
use_cache=use_cache,
|
| 652 |
+
)
|
| 653 |
+
byte_level_activations = encoder_output.hidden_states
|
| 654 |
+
|
| 655 |
+
encoder_connector_output = self.encoder_connector(
|
| 656 |
+
byte_level_activations,
|
| 657 |
+
cumulative_seq_lengths_per_word,
|
| 658 |
+
word_position_ids,
|
| 659 |
+
byte_position_ids,
|
| 660 |
+
)
|
| 661 |
+
backbone_output: CausalLMOutputWithPast = self.backbone(
|
| 662 |
+
hidden_states=encoder_connector_output,
|
| 663 |
+
position_ids=word_position_ids,
|
| 664 |
+
past_key_values=backbone_past_key_values,
|
| 665 |
+
use_cache=use_cache,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
predictive_word_embeddings = self.decoder_connector.forward(backbone_activations=backbone_output.hidden_states)
|
| 669 |
+
|
| 670 |
+
decoder_output = self.decoder.forward(
|
| 671 |
+
activations=byte_level_activations,
|
| 672 |
+
backbone_activations=predictive_word_embeddings,
|
| 673 |
+
cumulative_seq_lengths_per_word=cumulative_seq_lengths_per_word,
|
| 674 |
+
byte_position_ids=byte_position_ids,
|
| 675 |
+
word_position_ids=word_position_ids,
|
| 676 |
+
past_key_values=decoder_past_key_values,
|
| 677 |
+
use_cache=use_cache,
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
decoder_output = self.layer_norm(decoder_output.last_hidden_state)
|
| 681 |
+
logits = self.lm_head(decoder_output)
|
| 682 |
+
|
| 683 |
+
loss = None
|
| 684 |
+
|
| 685 |
+
return CausalLMOutputWithPast(
|
| 686 |
+
loss=loss,
|
| 687 |
+
logits=logits,
|
| 688 |
+
past_key_values=past_key_values if use_cache else None,
|
| 689 |
+
hidden_states=backbone_output.hidden_states,
|
| 690 |
+
attentions=None,
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
def _append_byte(self, words: list[list[int]], token: int) -> list[list[int]]:
|
| 694 |
+
extended_last_word = words.pop() + [token]
|
| 695 |
+
try:
|
| 696 |
+
text = self.splitter.decode(extended_last_word, errors='strict', skip_special_tokens=False)
|
| 697 |
+
list_of_bytes = self.splitter.encode(text)
|
| 698 |
+
words.extend([list(word_in_bytes) for word_in_bytes in list_of_bytes])
|
| 699 |
+
except UnicodeDecodeError:
|
| 700 |
+
# if decoding fails, the token cannot be part of a new word since it is not a valid
|
| 701 |
+
# utf-8 end byte and we append it to the current word
|
| 702 |
+
words.append(extended_last_word)
|
| 703 |
+
return words
|
| 704 |
+
|
| 705 |
+
def _complete_word(
|
| 706 |
+
self,
|
| 707 |
+
input_ids: torch.Tensor,
|
| 708 |
+
byte_position_ids: torch.Tensor,
|
| 709 |
+
backbone_word_prediction: torch.Tensor,
|
| 710 |
+
word_position_id: torch.Tensor,
|
| 711 |
+
encoder_cache: DynamicCache,
|
| 712 |
+
decoder_cache: DynamicCache,
|
| 713 |
+
sample_fn: Callable[[torch.Tensor], torch.Tensor] = sample_argmax,
|
| 714 |
+
):
|
| 715 |
+
"""Generate byte tokens until we hit the first byte of a new word."""
|
| 716 |
+
words = [input_ids.squeeze(0).tolist()]
|
| 717 |
+
byte_encoder_activations = []
|
| 718 |
+
completion_logits = []
|
| 719 |
+
|
| 720 |
+
while True:
|
| 721 |
+
encoder_output = self.encoder.forward(
|
| 722 |
+
input_ids,
|
| 723 |
+
byte_position_ids=None,
|
| 724 |
+
word_position_ids=word_position_id,
|
| 725 |
+
past_key_values=encoder_cache,
|
| 726 |
+
use_cache=True,
|
| 727 |
+
)
|
| 728 |
+
byte_encoder_activations.append(encoder_output.hidden_states)
|
| 729 |
+
decoder_output = self.decoder.forward(
|
| 730 |
+
backbone_word_prediction,
|
| 731 |
+
encoder_output.hidden_states,
|
| 732 |
+
byte_position_ids=None,
|
| 733 |
+
word_position_ids=word_position_id,
|
| 734 |
+
past_key_values=decoder_cache,
|
| 735 |
+
use_cache=True,
|
| 736 |
+
)
|
| 737 |
+
decoder_output = self.layer_norm(decoder_output.last_hidden_state)
|
| 738 |
+
logits = self.lm_head(decoder_output)
|
| 739 |
+
completion_logits.append(logits[0, -1:, :])
|
| 740 |
+
next_byte = int(sample_fn(logits).item())
|
| 741 |
+
words = self._append_byte(words, next_byte)
|
| 742 |
+
if len(words) > 1 or next_byte == self.eos_token_id:
|
| 743 |
+
break
|
| 744 |
+
input_ids = torch.tensor([[next_byte]], dtype=input_ids.dtype, device=input_ids.device)
|
| 745 |
+
|
| 746 |
+
byte_encoder_activations = torch.cat(byte_encoder_activations, dim=1)
|
| 747 |
+
num_kv = encoder_cache.get_seq_length()
|
| 748 |
+
byte_position_ids = torch.arange(num_kv + 1 - byte_encoder_activations.shape[1], num_kv + 1, device=input_ids.device, dtype=torch.long).unsqueeze(0)
|
| 749 |
+
completed_word_embedding = self.encoder_connector.forward(
|
| 750 |
+
byte_encoder_activations,
|
| 751 |
+
cumulative_seq_lengths_per_word=torch.tensor([0, byte_encoder_activations.size(1)], dtype=torch.int32, device=input_ids.device),
|
| 752 |
+
word_position_ids=word_position_id,
|
| 753 |
+
byte_position_ids=byte_position_ids,
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
completion = sum(words, [])[-len(completion_logits) :]
|
| 757 |
+
first_byte_of_next_word = words[1]
|
| 758 |
+
return completion, completed_word_embedding, first_byte_of_next_word, byte_position_ids[:, -1].item() + 1, completion_logits
|
| 759 |
+
|
| 760 |
+
def generate(
|
| 761 |
+
self,
|
| 762 |
+
input_ids: torch.Tensor,
|
| 763 |
+
max_new_tokens: int,
|
| 764 |
+
cumulative_seq_lengths_per_word: torch.Tensor,
|
| 765 |
+
byte_position_ids: torch.Tensor | None = None,
|
| 766 |
+
word_position_ids: torch.Tensor | None = None,
|
| 767 |
+
sample_fn: Callable[[torch.Tensor], torch.Tensor] = sample_argmax,
|
| 768 |
+
use_cache: bool = True,
|
| 769 |
+
stop_sequences: Sequence[str] | None = None,
|
| 770 |
+
):
|
| 771 |
+
if use_cache:
|
| 772 |
+
completion_text, completion_logits = self._generate_cached(input_ids, max_new_tokens, cumulative_seq_lengths_per_word, byte_position_ids, word_position_ids, sample_fn, stop_sequences=stop_sequences)
|
| 773 |
+
else:
|
| 774 |
+
completion_text, completion_logits = self._generate_uncached(input_ids, max_new_tokens, cumulative_seq_lengths_per_word, byte_position_ids, word_position_ids, sample_fn, stop_sequences=stop_sequences)
|
| 775 |
+
|
| 776 |
+
# remove stop sequence if exists
|
| 777 |
+
if stop_sequences is not None:
|
| 778 |
+
stop_sequences = sorted(stop_sequences, key=lambda i: len(i), reverse=True)
|
| 779 |
+
for stop_sequence in stop_sequences:
|
| 780 |
+
if stop_sequence in completion_text:
|
| 781 |
+
completion_text_left = completion_text.split(stop_sequence)[0]
|
| 782 |
+
completion_text_removed = completion_text[len(completion_text_left) :]
|
| 783 |
+
|
| 784 |
+
completion_logits = completion_logits[: -len(list(bytes(completion_text_removed.encode("UTF-8"))))]
|
| 785 |
+
completion_text = completion_text_left
|
| 786 |
+
break
|
| 787 |
+
|
| 788 |
+
return ModelOutput(
|
| 789 |
+
completion_text=completion_text,
|
| 790 |
+
input_ids=input_ids,
|
| 791 |
+
completion_logits=completion_logits,
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
@torch.no_grad()
|
| 795 |
+
def _generate_cached(
|
| 796 |
+
self,
|
| 797 |
+
input_ids: torch.Tensor,
|
| 798 |
+
max_new_tokens: int,
|
| 799 |
+
cumulative_seq_lengths_per_word: torch.Tensor,
|
| 800 |
+
byte_position_ids: torch.Tensor | None = None,
|
| 801 |
+
word_position_ids: torch.Tensor | None = None,
|
| 802 |
+
sample_fn: Callable[[torch.Tensor], torch.Tensor] = sample_argmax,
|
| 803 |
+
stop_sequences: Sequence[str] | None = None,
|
| 804 |
+
):
|
| 805 |
+
max_total_bytes = max_new_tokens + input_ids.shape[1]
|
| 806 |
+
if byte_position_ids is None:
|
| 807 |
+
byte_position_ids = torch.arange(0, cumulative_seq_lengths_per_word[-1].item(), device=input_ids.device, dtype=torch.int32).unsqueeze(0)
|
| 808 |
+
|
| 809 |
+
if word_position_ids is None:
|
| 810 |
+
word_position_ids = torch.arange(0, cumulative_seq_lengths_per_word.shape[0] - 1, device=input_ids.device, dtype=torch.int32).unsqueeze(0)
|
| 811 |
+
|
| 812 |
+
last_word_start, last_word_end = (
|
| 813 |
+
cumulative_seq_lengths_per_word[-2],
|
| 814 |
+
cumulative_seq_lengths_per_word[-1],
|
| 815 |
+
)
|
| 816 |
+
# Populate cache with everything except last word
|
| 817 |
+
initial_forward_output = self.forward(
|
| 818 |
+
input_ids=input_ids[:, :last_word_start],
|
| 819 |
+
cumulative_seq_lengths_per_word=cumulative_seq_lengths_per_word[:-1],
|
| 820 |
+
byte_position_ids=byte_position_ids[:, :last_word_start],
|
| 821 |
+
word_position_ids=word_position_ids[:, :-1],
|
| 822 |
+
past_key_values=None,
|
| 823 |
+
use_cache=True,
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
completion_bytes = []
|
| 827 |
+
completion_logits = []
|
| 828 |
+
input_ids = input_ids[:, last_word_start:last_word_end]
|
| 829 |
+
next_byte_id = last_word_end
|
| 830 |
+
byte_position_ids = byte_position_ids[:, last_word_start:last_word_end]
|
| 831 |
+
word_position_id = word_position_ids[:, -1].unsqueeze(-1)
|
| 832 |
+
backbone_last_hidden_state = initial_forward_output.hidden_states[:, -1:, :]
|
| 833 |
+
while next_byte_id < max_total_bytes:
|
| 834 |
+
completion, completed_word_embedding, first_byte_of_next_word, next_byte_id, next_completion_logits = self._complete_word(
|
| 835 |
+
input_ids=input_ids,
|
| 836 |
+
byte_position_ids=byte_position_ids,
|
| 837 |
+
backbone_word_prediction=backbone_last_hidden_state,
|
| 838 |
+
word_position_id=word_position_id,
|
| 839 |
+
encoder_cache=initial_forward_output.past_key_values.get_encoder_cache(),
|
| 840 |
+
decoder_cache=initial_forward_output.past_key_values.get_decoder_cache(),
|
| 841 |
+
sample_fn=sample_fn,
|
| 842 |
+
)
|
| 843 |
+
completion_logits.extend(next_completion_logits)
|
| 844 |
+
completion_bytes.extend(completion)
|
| 845 |
+
|
| 846 |
+
if self.eos_token_id in completion_bytes:
|
| 847 |
+
completion_bytes = completion_bytes[: completion_bytes.index(self.eos_token_id)]
|
| 848 |
+
break
|
| 849 |
+
|
| 850 |
+
if stop_sequences is not None:
|
| 851 |
+
try:
|
| 852 |
+
completion_text_tmp = self.splitter.decode(completion_bytes)
|
| 853 |
+
if any(stop_sequence in completion_text_tmp for stop_sequence in stop_sequences):
|
| 854 |
+
break
|
| 855 |
+
except Exception as e:
|
| 856 |
+
print("Cannot compare stop sequence", e)
|
| 857 |
+
|
| 858 |
+
backbone_output = self.backbone.forward(
|
| 859 |
+
hidden_states=completed_word_embedding,
|
| 860 |
+
position_ids=None,
|
| 861 |
+
past_key_values=initial_forward_output.past_key_values.get_backbone_cache(),
|
| 862 |
+
use_cache=True,
|
| 863 |
+
)
|
| 864 |
+
backbone_last_hidden_state = backbone_output.hidden_states[:, -1, :].unsqueeze(1)
|
| 865 |
+
|
| 866 |
+
input_ids = torch.tensor([first_byte_of_next_word], dtype=input_ids.dtype, device=input_ids.device)
|
| 867 |
+
byte_position_ids = torch.tensor([[next_byte_id]], dtype=input_ids.dtype, device=input_ids.device)
|
| 868 |
+
word_position_id = word_position_id + 1
|
| 869 |
+
|
| 870 |
+
completion_bytes.extend(first_byte_of_next_word)
|
| 871 |
+
completion_bytes = completion_bytes[:max_new_tokens]
|
| 872 |
+
completion_logits = torch.cat(completion_logits[:max_new_tokens], dim=0)
|
| 873 |
+
completion_text = self.splitter.decode(completion_bytes)
|
| 874 |
+
|
| 875 |
+
return completion_text, completion_logits
|
| 876 |
+
|
| 877 |
+
@torch.no_grad()
|
| 878 |
+
def _generate_uncached(
|
| 879 |
+
self,
|
| 880 |
+
input_ids: torch.Tensor,
|
| 881 |
+
max_new_tokens: int,
|
| 882 |
+
cumulative_seq_lengths_per_word: torch.Tensor,
|
| 883 |
+
byte_position_ids: torch.Tensor | None = None,
|
| 884 |
+
word_position_ids: torch.Tensor | None = None,
|
| 885 |
+
sample_fn=sample_argmax,
|
| 886 |
+
stop_sequences: Sequence[str] | None = None,
|
| 887 |
+
):
|
| 888 |
+
if byte_position_ids is None:
|
| 889 |
+
byte_position_ids = torch.arange(0, cumulative_seq_lengths_per_word[-1].item(), device=input_ids.device, dtype=torch.int32).unsqueeze(0)
|
| 890 |
+
|
| 891 |
+
if word_position_ids is None:
|
| 892 |
+
word_position_ids = torch.arange(0, cumulative_seq_lengths_per_word.shape[0] - 1, device=input_ids.device, dtype=torch.int32).unsqueeze(0)
|
| 893 |
+
|
| 894 |
+
word_list = []
|
| 895 |
+
for i in range(1, cumulative_seq_lengths_per_word.shape[0]):
|
| 896 |
+
start_idx = cumulative_seq_lengths_per_word[i - 1]
|
| 897 |
+
end_idx = cumulative_seq_lengths_per_word[i]
|
| 898 |
+
word_list.append(input_ids[:, start_idx:end_idx].squeeze(0).tolist())
|
| 899 |
+
|
| 900 |
+
completion_bytes = []
|
| 901 |
+
for _ in range(max_new_tokens):
|
| 902 |
+
output = self.forward(
|
| 903 |
+
input_ids=input_ids,
|
| 904 |
+
cumulative_seq_lengths_per_word=cumulative_seq_lengths_per_word,
|
| 905 |
+
byte_position_ids=byte_position_ids,
|
| 906 |
+
word_position_ids=word_position_ids,
|
| 907 |
+
past_key_values=None,
|
| 908 |
+
)
|
| 909 |
+
|
| 910 |
+
next_byte = int(sample_fn(output.logits).item())
|
| 911 |
+
completion_bytes.append(next_byte)
|
| 912 |
+
if next_byte == self.eos_token_id:
|
| 913 |
+
break
|
| 914 |
+
word_list = self._append_byte(word_list, next_byte)
|
| 915 |
+
|
| 916 |
+
input_ids = torch.tensor(sum(word_list, []), dtype=torch.long, device=input_ids.device).unsqueeze(0)
|
| 917 |
+
cumulative_seq_lengths_per_word = torch.tensor([0] + list(itertools.accumulate(len(word) for word in word_list if len(word) > 0)), dtype=torch.int32, device=input_ids.device)
|
| 918 |
+
byte_position_ids = torch.arange(0, input_ids.shape[1], device=input_ids.device, dtype=torch.int32).unsqueeze(0)
|
| 919 |
+
word_position_ids = torch.arange(0, cumulative_seq_lengths_per_word.shape[0] - 1, device=input_ids.device, dtype=torch.int32).unsqueeze(0)
|
| 920 |
+
|
| 921 |
+
if stop_sequences is not None:
|
| 922 |
+
try:
|
| 923 |
+
completion_text_tmp = self.splitter.decode(completion_bytes)
|
| 924 |
+
if any(completion_text_tmp.endswith(stop_sequence) for stop_sequence in stop_sequences):
|
| 925 |
+
break
|
| 926 |
+
except Exception as e:
|
| 927 |
+
print("Cannot compare stop sequence", e)
|
| 928 |
+
|
| 929 |
+
completion_text = self.splitter.decode(completion_bytes)
|
| 930 |
+
completion_logits = output.logits[0, -len(completion_bytes) :, :]
|
| 931 |
+
|
| 932 |
+
return completion_text, completion_logits
|
| 933 |
+
|
| 934 |
+
def _prepare_input(self, input_str: str, add_llama_template: bool = True, device: torch.device | None = None) -> tuple[torch.Tensor, torch.Tensor]:
|
| 935 |
+
if add_llama_template:
|
| 936 |
+
input_str = LLAMA_TEMPLATE.format(input=input_str)
|
| 937 |
+
|
| 938 |
+
if device is None:
|
| 939 |
+
assert torch.cuda.is_available(), "CUDA is not available"
|
| 940 |
+
device = torch.device("cuda")
|
| 941 |
+
input_ids_list = []
|
| 942 |
+
cumulative_per_word_lengths_list = [0]
|
| 943 |
+
|
| 944 |
+
words = self.splitter.encode(input_str)
|
| 945 |
+
for word in words:
|
| 946 |
+
input_ids_list.extend(word)
|
| 947 |
+
word_length = len(word)
|
| 948 |
+
cumulative_per_word_lengths_list.append(cumulative_per_word_lengths_list[-1] + word_length)
|
| 949 |
+
input_ids = torch.tensor(input_ids_list, device=device, dtype=torch.int32).unsqueeze(0)
|
| 950 |
+
cumulative_per_word_lengths = torch.tensor(cumulative_per_word_lengths_list, device=device, dtype=torch.int32)
|
| 951 |
+
return input_ids, cumulative_per_word_lengths
|
model.safetensors.index.json
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"metadata": {
|
| 3 |
+
"total_size": 28601145856
|
| 4 |
+
},
|
| 5 |
+
"weight_map": {
|
| 6 |
+
"backbone.layers.0.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 7 |
+
"backbone.layers.0.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 8 |
+
"backbone.layers.0.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 9 |
+
"backbone.layers.0.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 10 |
+
"backbone.layers.0.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 11 |
+
"backbone.layers.0.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 12 |
+
"backbone.layers.0.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 13 |
+
"backbone.layers.0.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 14 |
+
"backbone.layers.0.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 15 |
+
"backbone.layers.0.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 16 |
+
"backbone.layers.0.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 17 |
+
"backbone.layers.1.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 18 |
+
"backbone.layers.1.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 19 |
+
"backbone.layers.1.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 20 |
+
"backbone.layers.1.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 21 |
+
"backbone.layers.1.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 22 |
+
"backbone.layers.1.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 23 |
+
"backbone.layers.1.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 24 |
+
"backbone.layers.1.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 25 |
+
"backbone.layers.1.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 26 |
+
"backbone.layers.1.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 27 |
+
"backbone.layers.1.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 28 |
+
"backbone.layers.10.input_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 29 |
+
"backbone.layers.10.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
|
| 30 |
+
"backbone.layers.10.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
|
| 31 |
+
"backbone.layers.10.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
|
| 32 |
+
"backbone.layers.10.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 33 |
+
"backbone.layers.10.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
|
| 34 |
+
"backbone.layers.10.self_attn.norm_key.weight": "model-00002-of-00006.safetensors",
|
| 35 |
+
"backbone.layers.10.self_attn.norm_query.weight": "model-00002-of-00006.safetensors",
|
| 36 |
+
"backbone.layers.10.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
|
| 37 |
+
"backbone.layers.10.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
|
| 38 |
+
"backbone.layers.10.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
|
| 39 |
+
"backbone.layers.11.input_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 40 |
+
"backbone.layers.11.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
|
| 41 |
+
"backbone.layers.11.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
|
| 42 |
+
"backbone.layers.11.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
|
| 43 |
+
"backbone.layers.11.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 44 |
+
"backbone.layers.11.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
|
| 45 |
+
"backbone.layers.11.self_attn.norm_key.weight": "model-00003-of-00006.safetensors",
|
| 46 |
+
"backbone.layers.11.self_attn.norm_query.weight": "model-00003-of-00006.safetensors",
|
| 47 |
+
"backbone.layers.11.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
|
| 48 |
+
"backbone.layers.11.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
|
| 49 |
+
"backbone.layers.11.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
|
| 50 |
+
"backbone.layers.12.input_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 51 |
+
"backbone.layers.12.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
|
| 52 |
+
"backbone.layers.12.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
|
| 53 |
+
"backbone.layers.12.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
|
| 54 |
+
"backbone.layers.12.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 55 |
+
"backbone.layers.12.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
|
| 56 |
+
"backbone.layers.12.self_attn.norm_key.weight": "model-00003-of-00006.safetensors",
|
| 57 |
+
"backbone.layers.12.self_attn.norm_query.weight": "model-00003-of-00006.safetensors",
|
| 58 |
+
"backbone.layers.12.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
|
| 59 |
+
"backbone.layers.12.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
|
| 60 |
+
"backbone.layers.12.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
|
| 61 |
+
"backbone.layers.13.input_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 62 |
+
"backbone.layers.13.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
|
| 63 |
+
"backbone.layers.13.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
|
| 64 |
+
"backbone.layers.13.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
|
| 65 |
+
"backbone.layers.13.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 66 |
+
"backbone.layers.13.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
|
| 67 |
+
"backbone.layers.13.self_attn.norm_key.weight": "model-00003-of-00006.safetensors",
|
| 68 |
+
"backbone.layers.13.self_attn.norm_query.weight": "model-00003-of-00006.safetensors",
|
| 69 |
+
"backbone.layers.13.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
|
| 70 |
+
"backbone.layers.13.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
|
| 71 |
+
"backbone.layers.13.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
|
| 72 |
+
"backbone.layers.14.input_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 73 |
+
"backbone.layers.14.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
|
| 74 |
+
"backbone.layers.14.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
|
| 75 |
+
"backbone.layers.14.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
|
| 76 |
+
"backbone.layers.14.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 77 |
+
"backbone.layers.14.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
|
| 78 |
+
"backbone.layers.14.self_attn.norm_key.weight": "model-00003-of-00006.safetensors",
|
| 79 |
+
"backbone.layers.14.self_attn.norm_query.weight": "model-00003-of-00006.safetensors",
|
| 80 |
+
"backbone.layers.14.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
|
| 81 |
+
"backbone.layers.14.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
|
| 82 |
+
"backbone.layers.14.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
|
| 83 |
+
"backbone.layers.15.input_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 84 |
+
"backbone.layers.15.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
|
| 85 |
+
"backbone.layers.15.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
|
| 86 |
+
"backbone.layers.15.mlp.up_proj.weight": "model-00003-of-00006.safetensors",
|
| 87 |
+
"backbone.layers.15.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
|
| 88 |
+
"backbone.layers.15.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
|
| 89 |
+
"backbone.layers.15.self_attn.norm_key.weight": "model-00003-of-00006.safetensors",
|
| 90 |
+
"backbone.layers.15.self_attn.norm_query.weight": "model-00003-of-00006.safetensors",
|
| 91 |
+
"backbone.layers.15.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
|
| 92 |
+
"backbone.layers.15.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
|
| 93 |
+
"backbone.layers.15.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
|
| 94 |
+
"backbone.layers.16.input_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 95 |
+
"backbone.layers.16.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
|
| 96 |
+
"backbone.layers.16.mlp.gate_proj.weight": "model-00003-of-00006.safetensors",
|
| 97 |
+
"backbone.layers.16.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
|
| 98 |
+
"backbone.layers.16.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 99 |
+
"backbone.layers.16.self_attn.k_proj.weight": "model-00003-of-00006.safetensors",
|
| 100 |
+
"backbone.layers.16.self_attn.norm_key.weight": "model-00003-of-00006.safetensors",
|
| 101 |
+
"backbone.layers.16.self_attn.norm_query.weight": "model-00003-of-00006.safetensors",
|
| 102 |
+
"backbone.layers.16.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
|
| 103 |
+
"backbone.layers.16.self_attn.q_proj.weight": "model-00003-of-00006.safetensors",
|
| 104 |
+
"backbone.layers.16.self_attn.v_proj.weight": "model-00003-of-00006.safetensors",
|
| 105 |
+
"backbone.layers.17.input_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 106 |
+
"backbone.layers.17.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
|
| 107 |
+
"backbone.layers.17.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
|
| 108 |
+
"backbone.layers.17.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
|
| 109 |
+
"backbone.layers.17.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 110 |
+
"backbone.layers.17.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
|
| 111 |
+
"backbone.layers.17.self_attn.norm_key.weight": "model-00004-of-00006.safetensors",
|
| 112 |
+
"backbone.layers.17.self_attn.norm_query.weight": "model-00004-of-00006.safetensors",
|
| 113 |
+
"backbone.layers.17.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
|
| 114 |
+
"backbone.layers.17.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
|
| 115 |
+
"backbone.layers.17.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
|
| 116 |
+
"backbone.layers.18.input_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 117 |
+
"backbone.layers.18.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
|
| 118 |
+
"backbone.layers.18.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
|
| 119 |
+
"backbone.layers.18.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
|
| 120 |
+
"backbone.layers.18.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 121 |
+
"backbone.layers.18.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
|
| 122 |
+
"backbone.layers.18.self_attn.norm_key.weight": "model-00004-of-00006.safetensors",
|
| 123 |
+
"backbone.layers.18.self_attn.norm_query.weight": "model-00004-of-00006.safetensors",
|
| 124 |
+
"backbone.layers.18.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
|
| 125 |
+
"backbone.layers.18.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
|
| 126 |
+
"backbone.layers.18.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
|
| 127 |
+
"backbone.layers.19.input_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 128 |
+
"backbone.layers.19.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
|
| 129 |
+
"backbone.layers.19.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
|
| 130 |
+
"backbone.layers.19.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
|
| 131 |
+
"backbone.layers.19.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 132 |
+
"backbone.layers.19.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
|
| 133 |
+
"backbone.layers.19.self_attn.norm_key.weight": "model-00004-of-00006.safetensors",
|
| 134 |
+
"backbone.layers.19.self_attn.norm_query.weight": "model-00004-of-00006.safetensors",
|
| 135 |
+
"backbone.layers.19.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
|
| 136 |
+
"backbone.layers.19.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
|
| 137 |
+
"backbone.layers.19.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
|
| 138 |
+
"backbone.layers.2.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 139 |
+
"backbone.layers.2.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 140 |
+
"backbone.layers.2.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 141 |
+
"backbone.layers.2.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 142 |
+
"backbone.layers.2.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 143 |
+
"backbone.layers.2.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 144 |
+
"backbone.layers.2.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 145 |
+
"backbone.layers.2.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 146 |
+
"backbone.layers.2.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 147 |
+
"backbone.layers.2.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 148 |
+
"backbone.layers.2.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 149 |
+
"backbone.layers.20.input_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 150 |
+
"backbone.layers.20.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
|
| 151 |
+
"backbone.layers.20.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
|
| 152 |
+
"backbone.layers.20.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
|
| 153 |
+
"backbone.layers.20.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 154 |
+
"backbone.layers.20.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
|
| 155 |
+
"backbone.layers.20.self_attn.norm_key.weight": "model-00004-of-00006.safetensors",
|
| 156 |
+
"backbone.layers.20.self_attn.norm_query.weight": "model-00004-of-00006.safetensors",
|
| 157 |
+
"backbone.layers.20.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
|
| 158 |
+
"backbone.layers.20.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
|
| 159 |
+
"backbone.layers.20.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
|
| 160 |
+
"backbone.layers.21.input_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 161 |
+
"backbone.layers.21.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
|
| 162 |
+
"backbone.layers.21.mlp.gate_proj.weight": "model-00004-of-00006.safetensors",
|
| 163 |
+
"backbone.layers.21.mlp.up_proj.weight": "model-00004-of-00006.safetensors",
|
| 164 |
+
"backbone.layers.21.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
|
| 165 |
+
"backbone.layers.21.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
|
| 166 |
+
"backbone.layers.21.self_attn.norm_key.weight": "model-00004-of-00006.safetensors",
|
| 167 |
+
"backbone.layers.21.self_attn.norm_query.weight": "model-00004-of-00006.safetensors",
|
| 168 |
+
"backbone.layers.21.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
|
| 169 |
+
"backbone.layers.21.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
|
| 170 |
+
"backbone.layers.21.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
|
| 171 |
+
"backbone.layers.22.input_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 172 |
+
"backbone.layers.22.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
|
| 173 |
+
"backbone.layers.22.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
|
| 174 |
+
"backbone.layers.22.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
|
| 175 |
+
"backbone.layers.22.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 176 |
+
"backbone.layers.22.self_attn.k_proj.weight": "model-00004-of-00006.safetensors",
|
| 177 |
+
"backbone.layers.22.self_attn.norm_key.weight": "model-00004-of-00006.safetensors",
|
| 178 |
+
"backbone.layers.22.self_attn.norm_query.weight": "model-00004-of-00006.safetensors",
|
| 179 |
+
"backbone.layers.22.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
|
| 180 |
+
"backbone.layers.22.self_attn.q_proj.weight": "model-00004-of-00006.safetensors",
|
| 181 |
+
"backbone.layers.22.self_attn.v_proj.weight": "model-00004-of-00006.safetensors",
|
| 182 |
+
"backbone.layers.23.input_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 183 |
+
"backbone.layers.23.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
|
| 184 |
+
"backbone.layers.23.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
|
| 185 |
+
"backbone.layers.23.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
|
| 186 |
+
"backbone.layers.23.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 187 |
+
"backbone.layers.23.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
|
| 188 |
+
"backbone.layers.23.self_attn.norm_key.weight": "model-00005-of-00006.safetensors",
|
| 189 |
+
"backbone.layers.23.self_attn.norm_query.weight": "model-00005-of-00006.safetensors",
|
| 190 |
+
"backbone.layers.23.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
|
| 191 |
+
"backbone.layers.23.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
|
| 192 |
+
"backbone.layers.23.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
|
| 193 |
+
"backbone.layers.24.input_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 194 |
+
"backbone.layers.24.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
|
| 195 |
+
"backbone.layers.24.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
|
| 196 |
+
"backbone.layers.24.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
|
| 197 |
+
"backbone.layers.24.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 198 |
+
"backbone.layers.24.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
|
| 199 |
+
"backbone.layers.24.self_attn.norm_key.weight": "model-00005-of-00006.safetensors",
|
| 200 |
+
"backbone.layers.24.self_attn.norm_query.weight": "model-00005-of-00006.safetensors",
|
| 201 |
+
"backbone.layers.24.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
|
| 202 |
+
"backbone.layers.24.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
|
| 203 |
+
"backbone.layers.24.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
|
| 204 |
+
"backbone.layers.25.input_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 205 |
+
"backbone.layers.25.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
|
| 206 |
+
"backbone.layers.25.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
|
| 207 |
+
"backbone.layers.25.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
|
| 208 |
+
"backbone.layers.25.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 209 |
+
"backbone.layers.25.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
|
| 210 |
+
"backbone.layers.25.self_attn.norm_key.weight": "model-00005-of-00006.safetensors",
|
| 211 |
+
"backbone.layers.25.self_attn.norm_query.weight": "model-00005-of-00006.safetensors",
|
| 212 |
+
"backbone.layers.25.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
|
| 213 |
+
"backbone.layers.25.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
|
| 214 |
+
"backbone.layers.25.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
|
| 215 |
+
"backbone.layers.26.input_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 216 |
+
"backbone.layers.26.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
|
| 217 |
+
"backbone.layers.26.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
|
| 218 |
+
"backbone.layers.26.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
|
| 219 |
+
"backbone.layers.26.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
|
| 220 |
+
"backbone.layers.26.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
|
| 221 |
+
"backbone.layers.26.self_attn.norm_key.weight": "model-00005-of-00006.safetensors",
|
| 222 |
+
"backbone.layers.26.self_attn.norm_query.weight": "model-00005-of-00006.safetensors",
|
| 223 |
+
"backbone.layers.26.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
|
| 224 |
+
"backbone.layers.26.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
|
| 225 |
+
"backbone.layers.26.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
|
| 226 |
+
"backbone.layers.27.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 227 |
+
"backbone.layers.27.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 228 |
+
"backbone.layers.27.mlp.gate_proj.weight": "model-00005-of-00006.safetensors",
|
| 229 |
+
"backbone.layers.27.mlp.up_proj.weight": "model-00005-of-00006.safetensors",
|
| 230 |
+
"backbone.layers.27.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 231 |
+
"backbone.layers.27.self_attn.k_proj.weight": "model-00005-of-00006.safetensors",
|
| 232 |
+
"backbone.layers.27.self_attn.norm_key.weight": "model-00005-of-00006.safetensors",
|
| 233 |
+
"backbone.layers.27.self_attn.norm_query.weight": "model-00005-of-00006.safetensors",
|
| 234 |
+
"backbone.layers.27.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
|
| 235 |
+
"backbone.layers.27.self_attn.q_proj.weight": "model-00005-of-00006.safetensors",
|
| 236 |
+
"backbone.layers.27.self_attn.v_proj.weight": "model-00005-of-00006.safetensors",
|
| 237 |
+
"backbone.layers.28.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 238 |
+
"backbone.layers.28.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 239 |
+
"backbone.layers.28.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 240 |
+
"backbone.layers.28.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 241 |
+
"backbone.layers.28.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 242 |
+
"backbone.layers.28.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 243 |
+
"backbone.layers.28.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 244 |
+
"backbone.layers.28.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 245 |
+
"backbone.layers.28.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 246 |
+
"backbone.layers.28.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 247 |
+
"backbone.layers.28.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 248 |
+
"backbone.layers.29.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 249 |
+
"backbone.layers.29.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 250 |
+
"backbone.layers.29.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 251 |
+
"backbone.layers.29.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 252 |
+
"backbone.layers.29.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 253 |
+
"backbone.layers.29.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 254 |
+
"backbone.layers.29.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 255 |
+
"backbone.layers.29.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 256 |
+
"backbone.layers.29.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 257 |
+
"backbone.layers.29.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 258 |
+
"backbone.layers.29.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 259 |
+
"backbone.layers.3.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 260 |
+
"backbone.layers.3.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 261 |
+
"backbone.layers.3.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 262 |
+
"backbone.layers.3.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 263 |
+
"backbone.layers.3.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 264 |
+
"backbone.layers.3.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 265 |
+
"backbone.layers.3.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 266 |
+
"backbone.layers.3.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 267 |
+
"backbone.layers.3.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 268 |
+
"backbone.layers.3.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 269 |
+
"backbone.layers.3.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 270 |
+
"backbone.layers.30.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 271 |
+
"backbone.layers.30.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 272 |
+
"backbone.layers.30.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 273 |
+
"backbone.layers.30.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 274 |
+
"backbone.layers.30.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 275 |
+
"backbone.layers.30.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 276 |
+
"backbone.layers.30.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 277 |
+
"backbone.layers.30.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 278 |
+
"backbone.layers.30.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 279 |
+
"backbone.layers.30.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 280 |
+
"backbone.layers.30.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 281 |
+
"backbone.layers.31.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 282 |
+
"backbone.layers.31.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 283 |
+
"backbone.layers.31.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 284 |
+
"backbone.layers.31.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 285 |
+
"backbone.layers.31.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 286 |
+
"backbone.layers.31.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 287 |
+
"backbone.layers.31.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 288 |
+
"backbone.layers.31.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 289 |
+
"backbone.layers.31.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 290 |
+
"backbone.layers.31.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 291 |
+
"backbone.layers.31.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 292 |
+
"backbone.layers.4.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 293 |
+
"backbone.layers.4.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 294 |
+
"backbone.layers.4.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 295 |
+
"backbone.layers.4.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 296 |
+
"backbone.layers.4.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 297 |
+
"backbone.layers.4.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 298 |
+
"backbone.layers.4.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 299 |
+
"backbone.layers.4.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 300 |
+
"backbone.layers.4.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 301 |
+
"backbone.layers.4.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 302 |
+
"backbone.layers.4.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 303 |
+
"backbone.layers.5.input_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 304 |
+
"backbone.layers.5.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
|
| 305 |
+
"backbone.layers.5.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
|
| 306 |
+
"backbone.layers.5.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
|
| 307 |
+
"backbone.layers.5.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 308 |
+
"backbone.layers.5.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 309 |
+
"backbone.layers.5.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 310 |
+
"backbone.layers.5.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 311 |
+
"backbone.layers.5.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 312 |
+
"backbone.layers.5.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 313 |
+
"backbone.layers.5.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 314 |
+
"backbone.layers.6.input_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 315 |
+
"backbone.layers.6.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
|
| 316 |
+
"backbone.layers.6.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
|
| 317 |
+
"backbone.layers.6.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
|
| 318 |
+
"backbone.layers.6.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 319 |
+
"backbone.layers.6.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
|
| 320 |
+
"backbone.layers.6.self_attn.norm_key.weight": "model-00002-of-00006.safetensors",
|
| 321 |
+
"backbone.layers.6.self_attn.norm_query.weight": "model-00002-of-00006.safetensors",
|
| 322 |
+
"backbone.layers.6.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
|
| 323 |
+
"backbone.layers.6.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
|
| 324 |
+
"backbone.layers.6.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
|
| 325 |
+
"backbone.layers.7.input_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 326 |
+
"backbone.layers.7.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
|
| 327 |
+
"backbone.layers.7.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
|
| 328 |
+
"backbone.layers.7.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
|
| 329 |
+
"backbone.layers.7.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 330 |
+
"backbone.layers.7.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
|
| 331 |
+
"backbone.layers.7.self_attn.norm_key.weight": "model-00002-of-00006.safetensors",
|
| 332 |
+
"backbone.layers.7.self_attn.norm_query.weight": "model-00002-of-00006.safetensors",
|
| 333 |
+
"backbone.layers.7.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
|
| 334 |
+
"backbone.layers.7.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
|
| 335 |
+
"backbone.layers.7.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
|
| 336 |
+
"backbone.layers.8.input_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 337 |
+
"backbone.layers.8.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
|
| 338 |
+
"backbone.layers.8.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
|
| 339 |
+
"backbone.layers.8.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
|
| 340 |
+
"backbone.layers.8.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 341 |
+
"backbone.layers.8.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
|
| 342 |
+
"backbone.layers.8.self_attn.norm_key.weight": "model-00002-of-00006.safetensors",
|
| 343 |
+
"backbone.layers.8.self_attn.norm_query.weight": "model-00002-of-00006.safetensors",
|
| 344 |
+
"backbone.layers.8.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
|
| 345 |
+
"backbone.layers.8.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
|
| 346 |
+
"backbone.layers.8.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
|
| 347 |
+
"backbone.layers.9.input_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 348 |
+
"backbone.layers.9.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
|
| 349 |
+
"backbone.layers.9.mlp.gate_proj.weight": "model-00002-of-00006.safetensors",
|
| 350 |
+
"backbone.layers.9.mlp.up_proj.weight": "model-00002-of-00006.safetensors",
|
| 351 |
+
"backbone.layers.9.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
|
| 352 |
+
"backbone.layers.9.self_attn.k_proj.weight": "model-00002-of-00006.safetensors",
|
| 353 |
+
"backbone.layers.9.self_attn.norm_key.weight": "model-00002-of-00006.safetensors",
|
| 354 |
+
"backbone.layers.9.self_attn.norm_query.weight": "model-00002-of-00006.safetensors",
|
| 355 |
+
"backbone.layers.9.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
|
| 356 |
+
"backbone.layers.9.self_attn.q_proj.weight": "model-00002-of-00006.safetensors",
|
| 357 |
+
"backbone.layers.9.self_attn.v_proj.weight": "model-00002-of-00006.safetensors",
|
| 358 |
+
"decoder.decoder_layers.0.cross_attention.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 359 |
+
"decoder.decoder_layers.0.cross_attention.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 360 |
+
"decoder.decoder_layers.0.cross_attention.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 361 |
+
"decoder.decoder_layers.0.cross_attention.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 362 |
+
"decoder.decoder_layers.0.cross_attention.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 363 |
+
"decoder.decoder_layers.0.cross_attention.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 364 |
+
"decoder.decoder_layers.0.kv_norm.weight": "model-00006-of-00006.safetensors",
|
| 365 |
+
"decoder.decoder_layers.0.llama_layer.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 366 |
+
"decoder.decoder_layers.0.llama_layer.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 367 |
+
"decoder.decoder_layers.0.llama_layer.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 368 |
+
"decoder.decoder_layers.0.llama_layer.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 369 |
+
"decoder.decoder_layers.0.llama_layer.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 370 |
+
"decoder.decoder_layers.0.llama_layer.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 371 |
+
"decoder.decoder_layers.0.llama_layer.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 372 |
+
"decoder.decoder_layers.0.llama_layer.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 373 |
+
"decoder.decoder_layers.0.llama_layer.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 374 |
+
"decoder.decoder_layers.0.llama_layer.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 375 |
+
"decoder.decoder_layers.0.llama_layer.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 376 |
+
"decoder.decoder_layers.0.query_norm.weight": "model-00006-of-00006.safetensors",
|
| 377 |
+
"decoder.decoder_layers.1.cross_attention.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 378 |
+
"decoder.decoder_layers.1.cross_attention.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 379 |
+
"decoder.decoder_layers.1.cross_attention.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 380 |
+
"decoder.decoder_layers.1.cross_attention.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 381 |
+
"decoder.decoder_layers.1.cross_attention.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 382 |
+
"decoder.decoder_layers.1.cross_attention.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 383 |
+
"decoder.decoder_layers.1.kv_norm.weight": "model-00006-of-00006.safetensors",
|
| 384 |
+
"decoder.decoder_layers.1.llama_layer.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 385 |
+
"decoder.decoder_layers.1.llama_layer.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 386 |
+
"decoder.decoder_layers.1.llama_layer.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 387 |
+
"decoder.decoder_layers.1.llama_layer.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 388 |
+
"decoder.decoder_layers.1.llama_layer.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 389 |
+
"decoder.decoder_layers.1.llama_layer.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 390 |
+
"decoder.decoder_layers.1.llama_layer.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 391 |
+
"decoder.decoder_layers.1.llama_layer.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 392 |
+
"decoder.decoder_layers.1.llama_layer.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 393 |
+
"decoder.decoder_layers.1.llama_layer.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 394 |
+
"decoder.decoder_layers.1.llama_layer.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 395 |
+
"decoder.decoder_layers.1.query_norm.weight": "model-00006-of-00006.safetensors",
|
| 396 |
+
"decoder.decoder_layers.2.cross_attention.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 397 |
+
"decoder.decoder_layers.2.cross_attention.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 398 |
+
"decoder.decoder_layers.2.cross_attention.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 399 |
+
"decoder.decoder_layers.2.cross_attention.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 400 |
+
"decoder.decoder_layers.2.cross_attention.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 401 |
+
"decoder.decoder_layers.2.cross_attention.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 402 |
+
"decoder.decoder_layers.2.kv_norm.weight": "model-00006-of-00006.safetensors",
|
| 403 |
+
"decoder.decoder_layers.2.llama_layer.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 404 |
+
"decoder.decoder_layers.2.llama_layer.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 405 |
+
"decoder.decoder_layers.2.llama_layer.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 406 |
+
"decoder.decoder_layers.2.llama_layer.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 407 |
+
"decoder.decoder_layers.2.llama_layer.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 408 |
+
"decoder.decoder_layers.2.llama_layer.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 409 |
+
"decoder.decoder_layers.2.llama_layer.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 410 |
+
"decoder.decoder_layers.2.llama_layer.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 411 |
+
"decoder.decoder_layers.2.llama_layer.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 412 |
+
"decoder.decoder_layers.2.llama_layer.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 413 |
+
"decoder.decoder_layers.2.llama_layer.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 414 |
+
"decoder.decoder_layers.2.query_norm.weight": "model-00006-of-00006.safetensors",
|
| 415 |
+
"decoder.decoder_layers.3.cross_attention.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 416 |
+
"decoder.decoder_layers.3.cross_attention.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 417 |
+
"decoder.decoder_layers.3.cross_attention.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 418 |
+
"decoder.decoder_layers.3.cross_attention.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 419 |
+
"decoder.decoder_layers.3.cross_attention.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 420 |
+
"decoder.decoder_layers.3.cross_attention.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 421 |
+
"decoder.decoder_layers.3.kv_norm.weight": "model-00006-of-00006.safetensors",
|
| 422 |
+
"decoder.decoder_layers.3.llama_layer.input_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 423 |
+
"decoder.decoder_layers.3.llama_layer.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
|
| 424 |
+
"decoder.decoder_layers.3.llama_layer.mlp.gate_proj.weight": "model-00006-of-00006.safetensors",
|
| 425 |
+
"decoder.decoder_layers.3.llama_layer.mlp.up_proj.weight": "model-00006-of-00006.safetensors",
|
| 426 |
+
"decoder.decoder_layers.3.llama_layer.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
|
| 427 |
+
"decoder.decoder_layers.3.llama_layer.self_attn.k_proj.weight": "model-00006-of-00006.safetensors",
|
| 428 |
+
"decoder.decoder_layers.3.llama_layer.self_attn.norm_key.weight": "model-00006-of-00006.safetensors",
|
| 429 |
+
"decoder.decoder_layers.3.llama_layer.self_attn.norm_query.weight": "model-00006-of-00006.safetensors",
|
| 430 |
+
"decoder.decoder_layers.3.llama_layer.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
|
| 431 |
+
"decoder.decoder_layers.3.llama_layer.self_attn.q_proj.weight": "model-00006-of-00006.safetensors",
|
| 432 |
+
"decoder.decoder_layers.3.llama_layer.self_attn.v_proj.weight": "model-00006-of-00006.safetensors",
|
| 433 |
+
"decoder.decoder_layers.3.query_norm.weight": "model-00006-of-00006.safetensors",
|
| 434 |
+
"decoder_connector.first_word_embedding": "model-00006-of-00006.safetensors",
|
| 435 |
+
"encoder.embedding_layer.weight": "model-00001-of-00006.safetensors",
|
| 436 |
+
"encoder.layers.0.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 437 |
+
"encoder.layers.0.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 438 |
+
"encoder.layers.0.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 439 |
+
"encoder.layers.0.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 440 |
+
"encoder.layers.0.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 441 |
+
"encoder.layers.0.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 442 |
+
"encoder.layers.0.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 443 |
+
"encoder.layers.0.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 444 |
+
"encoder.layers.0.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 445 |
+
"encoder.layers.0.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 446 |
+
"encoder.layers.0.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 447 |
+
"encoder.layers.1.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 448 |
+
"encoder.layers.1.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 449 |
+
"encoder.layers.1.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 450 |
+
"encoder.layers.1.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 451 |
+
"encoder.layers.1.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 452 |
+
"encoder.layers.1.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 453 |
+
"encoder.layers.1.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 454 |
+
"encoder.layers.1.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 455 |
+
"encoder.layers.1.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 456 |
+
"encoder.layers.1.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 457 |
+
"encoder.layers.1.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 458 |
+
"encoder.layers.2.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 459 |
+
"encoder.layers.2.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 460 |
+
"encoder.layers.2.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 461 |
+
"encoder.layers.2.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 462 |
+
"encoder.layers.2.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 463 |
+
"encoder.layers.2.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 464 |
+
"encoder.layers.2.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 465 |
+
"encoder.layers.2.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 466 |
+
"encoder.layers.2.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 467 |
+
"encoder.layers.2.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 468 |
+
"encoder.layers.2.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 469 |
+
"encoder.layers.3.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 470 |
+
"encoder.layers.3.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 471 |
+
"encoder.layers.3.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 472 |
+
"encoder.layers.3.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 473 |
+
"encoder.layers.3.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 474 |
+
"encoder.layers.3.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 475 |
+
"encoder.layers.3.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 476 |
+
"encoder.layers.3.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 477 |
+
"encoder.layers.3.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 478 |
+
"encoder.layers.3.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 479 |
+
"encoder.layers.3.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 480 |
+
"encoder.layers.4.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 481 |
+
"encoder.layers.4.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 482 |
+
"encoder.layers.4.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 483 |
+
"encoder.layers.4.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 484 |
+
"encoder.layers.4.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 485 |
+
"encoder.layers.4.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 486 |
+
"encoder.layers.4.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 487 |
+
"encoder.layers.4.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 488 |
+
"encoder.layers.4.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 489 |
+
"encoder.layers.4.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 490 |
+
"encoder.layers.4.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 491 |
+
"encoder.layers.5.input_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 492 |
+
"encoder.layers.5.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
|
| 493 |
+
"encoder.layers.5.mlp.gate_proj.weight": "model-00001-of-00006.safetensors",
|
| 494 |
+
"encoder.layers.5.mlp.up_proj.weight": "model-00001-of-00006.safetensors",
|
| 495 |
+
"encoder.layers.5.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
|
| 496 |
+
"encoder.layers.5.self_attn.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 497 |
+
"encoder.layers.5.self_attn.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 498 |
+
"encoder.layers.5.self_attn.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 499 |
+
"encoder.layers.5.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 500 |
+
"encoder.layers.5.self_attn.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 501 |
+
"encoder.layers.5.self_attn.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 502 |
+
"encoder_connector.cross_attention_encoder_connector.k_proj.weight": "model-00001-of-00006.safetensors",
|
| 503 |
+
"encoder_connector.cross_attention_encoder_connector.norm_key.weight": "model-00001-of-00006.safetensors",
|
| 504 |
+
"encoder_connector.cross_attention_encoder_connector.norm_query.weight": "model-00001-of-00006.safetensors",
|
| 505 |
+
"encoder_connector.cross_attention_encoder_connector.o_proj.weight": "model-00001-of-00006.safetensors",
|
| 506 |
+
"encoder_connector.cross_attention_encoder_connector.q_proj.weight": "model-00001-of-00006.safetensors",
|
| 507 |
+
"encoder_connector.cross_attention_encoder_connector.v_proj.weight": "model-00001-of-00006.safetensors",
|
| 508 |
+
"encoder_connector.latent_query": "model-00001-of-00006.safetensors",
|
| 509 |
+
"layer_norm.weight": "model-00006-of-00006.safetensors",
|
| 510 |
+
"lm_head.weight": "model-00006-of-00006.safetensors"
|
| 511 |
+
}
|
| 512 |
+
}
|
norm.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
class RMSNorm(nn.Module):
|
| 5 |
+
def __init__(self, dimensions: int, eps: float, device: torch.device, dtype: torch.dtype = torch.bfloat16, norm_in_fp32: bool = False):
|
| 6 |
+
super().__init__()
|
| 7 |
+
self.eps = eps
|
| 8 |
+
self.weight = torch.nn.Parameter(torch.ones(dimensions, dtype=dtype).to(device))
|
| 9 |
+
self.norm_in_fp32 = norm_in_fp32
|
| 10 |
+
|
| 11 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 12 |
+
original_dtype = x.dtype
|
| 13 |
+
if self.norm_in_fp32:
|
| 14 |
+
x = x.float()
|
| 15 |
+
|
| 16 |
+
out = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 17 |
+
|
| 18 |
+
if out.dtype != original_dtype:
|
| 19 |
+
out = out.to(original_dtype)
|
| 20 |
+
|
| 21 |
+
return out * self.weight
|
source/aleph_alpha_homepage_badge.svg
ADDED
|
|
source/aleph_alpha_logo.svg
ADDED
|
|
source/aleph_alpha_logo_thumbnail.png
ADDED
|
|
splitter.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
from hat_splitter import HATSplitter as RustHATSplitter
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class HATSplitter:
|
| 7 |
+
def __init__(self, special_token_dict: dict | None = None, max_word_size: int = 128):
|
| 8 |
+
self.hat_splitter = RustHATSplitter()
|
| 9 |
+
self.max_word_size = max_word_size
|
| 10 |
+
self.special_token_dict = special_token_dict
|
| 11 |
+
self.special_token_replace: dict[int, list[int]] = {token: list(text.encode("utf-8")) for text, token in self.special_token_dict.items()}
|
| 12 |
+
self.special_token_pattern = re.compile(rf"({'|'.join(map(re.escape, special_token_dict.keys()))})") if special_token_dict else re.compile(r"(?!)")
|
| 13 |
+
|
| 14 |
+
def encode(self, text: str) -> list[list[int]]:
|
| 15 |
+
chunks = []
|
| 16 |
+
for str_chunk in self.special_token_pattern.split(text):
|
| 17 |
+
if str_chunk:
|
| 18 |
+
if str_chunk in self.special_token_dict:
|
| 19 |
+
chunks.append([self.special_token_dict[str_chunk]])
|
| 20 |
+
else:
|
| 21 |
+
chunks.extend(list(chunk) for chunk in self.hat_splitter.split_with_limit(str_chunk, self.max_word_size))
|
| 22 |
+
return chunks
|
| 23 |
+
|
| 24 |
+
def decode(self, token_ids: list[int], errors: str = "replace", skip_special_tokens: bool = False) -> str:
|
| 25 |
+
assert isinstance(token_ids, list), "token_ids must be a list"
|
| 26 |
+
assert all(isinstance(token_id, int) for token_id in token_ids), "token_ids must be a list of integers"
|
| 27 |
+
|
| 28 |
+
new_token_ids: list[int]
|
| 29 |
+
if skip_special_tokens:
|
| 30 |
+
new_token_ids = [token_id for token_id in token_ids if token_id not in self.special_token_replace]
|
| 31 |
+
else:
|
| 32 |
+
new_token_ids = []
|
| 33 |
+
for token in token_ids:
|
| 34 |
+
if token in self.special_token_replace:
|
| 35 |
+
new_token_ids.extend(self.special_token_replace[token])
|
| 36 |
+
else:
|
| 37 |
+
new_token_ids.append(token)
|
| 38 |
+
|
| 39 |
+
return bytes(new_token_ids).decode("utf-8", errors=errors)
|
transformer_backbone.py
ADDED
|
@@ -0,0 +1,1553 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hacked in QK norm in LlamaDecoderLayer in transformers; keeping the version from
|
| 2 |
+
# transformers==4.46.3 since this keeps rotary within the decoder layer
|
| 3 |
+
# Source: https://github.com/huggingface/transformers/blob/v4.46.3/src/transformers/models/llama/modeling_llama.py#L400
|
| 4 |
+
|
| 5 |
+
# coding=utf-8
|
| 6 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 7 |
+
#
|
| 8 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 9 |
+
# and OPT implementations in this library. It has been modified from its
|
| 10 |
+
# original forms to accommodate minor architectural differences compared
|
| 11 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 12 |
+
#
|
| 13 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 14 |
+
# you may not use this file except in compliance with the License.
|
| 15 |
+
# You may obtain a copy of the License at
|
| 16 |
+
#
|
| 17 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 18 |
+
#
|
| 19 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 20 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 21 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 22 |
+
# See the License for the specific language governing permissions and
|
| 23 |
+
# limitations under the License.
|
| 24 |
+
import math
|
| 25 |
+
from typing import List, Optional, Tuple, Union
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
import torch.utils.checkpoint
|
| 30 |
+
from torch import nn
|
| 31 |
+
|
| 32 |
+
from transformers.activations import ACT2FN
|
| 33 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
| 34 |
+
from transformers.generation import GenerationMixin
|
| 35 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
| 36 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
| 37 |
+
from transformers.modeling_outputs import (
|
| 38 |
+
BaseModelOutputWithPast,
|
| 39 |
+
CausalLMOutputWithPast,
|
| 40 |
+
QuestionAnsweringModelOutput,
|
| 41 |
+
SequenceClassifierOutputWithPast,
|
| 42 |
+
TokenClassifierOutput,
|
| 43 |
+
)
|
| 44 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 45 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 46 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
| 47 |
+
from transformers.utils import (
|
| 48 |
+
add_code_sample_docstrings,
|
| 49 |
+
add_start_docstrings,
|
| 50 |
+
add_start_docstrings_to_model_forward,
|
| 51 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 52 |
+
logging,
|
| 53 |
+
replace_return_docstrings,
|
| 54 |
+
)
|
| 55 |
+
from transformers.models.llama.configuration_llama import LlamaConfig
|
| 56 |
+
|
| 57 |
+
from .norm import RMSNorm
|
| 58 |
+
|
| 59 |
+
logger = logging.get_logger(__name__)
|
| 60 |
+
|
| 61 |
+
_CHECKPOINT_FOR_DOC = "meta-llama/Llama-2-7b-hf"
|
| 62 |
+
_CONFIG_FOR_DOC = "LlamaConfig"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class LlamaRMSNorm(nn.Module):
|
| 66 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 67 |
+
"""
|
| 68 |
+
LlamaRMSNorm is equivalent to T5LayerNorm
|
| 69 |
+
"""
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 72 |
+
self.variance_epsilon = eps
|
| 73 |
+
|
| 74 |
+
def forward(self, hidden_states):
|
| 75 |
+
input_dtype = hidden_states.dtype
|
| 76 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 77 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 78 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 79 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 80 |
+
|
| 81 |
+
def extra_repr(self):
|
| 82 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class LlamaRotaryEmbedding(nn.Module):
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
dim=None,
|
| 92 |
+
max_position_embeddings=2048,
|
| 93 |
+
base=10000,
|
| 94 |
+
device=None,
|
| 95 |
+
scaling_factor=1.0,
|
| 96 |
+
rope_type="default",
|
| 97 |
+
config: Optional[LlamaConfig] = None,
|
| 98 |
+
):
|
| 99 |
+
super().__init__()
|
| 100 |
+
# TODO (joao): remove the `if` below, only used for BC
|
| 101 |
+
self.rope_kwargs = {}
|
| 102 |
+
if config is None:
|
| 103 |
+
logger.warning_once(
|
| 104 |
+
"`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
|
| 105 |
+
"`config` argument. All other arguments will be removed in v4.46"
|
| 106 |
+
)
|
| 107 |
+
self.rope_kwargs = {
|
| 108 |
+
"rope_type": rope_type,
|
| 109 |
+
"factor": scaling_factor,
|
| 110 |
+
"dim": dim,
|
| 111 |
+
"base": base,
|
| 112 |
+
"max_position_embeddings": max_position_embeddings,
|
| 113 |
+
}
|
| 114 |
+
self.rope_type = rope_type
|
| 115 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 116 |
+
self.original_max_seq_len = max_position_embeddings
|
| 117 |
+
else:
|
| 118 |
+
# BC: "rope_type" was originally "type"
|
| 119 |
+
if config.rope_scaling is not None:
|
| 120 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 121 |
+
else:
|
| 122 |
+
self.rope_type = "default"
|
| 123 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 124 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 125 |
+
|
| 126 |
+
self.config = config
|
| 127 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 128 |
+
|
| 129 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
|
| 130 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 131 |
+
self.original_inv_freq = self.inv_freq
|
| 132 |
+
|
| 133 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
| 134 |
+
"""
|
| 135 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
| 136 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
| 137 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
| 138 |
+
"""
|
| 139 |
+
seq_len = torch.max(position_ids) + 1
|
| 140 |
+
if seq_len > self.max_seq_len_cached: # growth
|
| 141 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(
|
| 142 |
+
self.config, device, seq_len=seq_len, **self.rope_kwargs
|
| 143 |
+
)
|
| 144 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
| 145 |
+
self.max_seq_len_cached = seq_len
|
| 146 |
+
|
| 147 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
| 148 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 149 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
| 150 |
+
|
| 151 |
+
@torch.no_grad()
|
| 152 |
+
def forward(self, x, position_ids):
|
| 153 |
+
if "dynamic" in self.rope_type:
|
| 154 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 155 |
+
|
| 156 |
+
# Core RoPE block
|
| 157 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 158 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 159 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
| 160 |
+
device_type = x.device.type
|
| 161 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 162 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 163 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 164 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 165 |
+
cos = emb.cos()
|
| 166 |
+
sin = emb.sin()
|
| 167 |
+
|
| 168 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
| 169 |
+
cos = cos * self.attention_scaling
|
| 170 |
+
sin = sin * self.attention_scaling
|
| 171 |
+
|
| 172 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
| 176 |
+
"""LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 177 |
+
|
| 178 |
+
def __init__(self, *args, **kwargs):
|
| 179 |
+
logger.warning_once(
|
| 180 |
+
"`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
|
| 181 |
+
"`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
|
| 182 |
+
)
|
| 183 |
+
kwargs["rope_type"] = "linear"
|
| 184 |
+
super().__init__(*args, **kwargs)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
| 188 |
+
"""LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 189 |
+
|
| 190 |
+
def __init__(self, *args, **kwargs):
|
| 191 |
+
logger.warning_once(
|
| 192 |
+
"`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
|
| 193 |
+
"`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
|
| 194 |
+
"__init__)."
|
| 195 |
+
)
|
| 196 |
+
kwargs["rope_type"] = "dynamic"
|
| 197 |
+
super().__init__(*args, **kwargs)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def rotate_half(x):
|
| 201 |
+
"""Rotates half the hidden dims of the input."""
|
| 202 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 203 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 204 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 208 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
q (`torch.Tensor`): The query tensor.
|
| 212 |
+
k (`torch.Tensor`): The key tensor.
|
| 213 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 214 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 215 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 216 |
+
Deprecated and unused.
|
| 217 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 218 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 219 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 220 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 221 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 222 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 223 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 224 |
+
Returns:
|
| 225 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 226 |
+
"""
|
| 227 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 228 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 229 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 230 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 231 |
+
return q_embed, k_embed
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class LlamaMLP(nn.Module):
|
| 235 |
+
def __init__(self, config):
|
| 236 |
+
super().__init__()
|
| 237 |
+
self.config = config
|
| 238 |
+
self.hidden_size = config.hidden_size
|
| 239 |
+
self.intermediate_size = config.intermediate_size
|
| 240 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 241 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 242 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 243 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 244 |
+
|
| 245 |
+
def forward(self, x):
|
| 246 |
+
if self.config.pretraining_tp > 1:
|
| 247 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
| 248 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
| 249 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
| 250 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
| 251 |
+
|
| 252 |
+
gate_proj = torch.cat(
|
| 253 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
| 254 |
+
)
|
| 255 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
| 256 |
+
|
| 257 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
| 258 |
+
down_proj = [
|
| 259 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
| 260 |
+
]
|
| 261 |
+
down_proj = sum(down_proj)
|
| 262 |
+
else:
|
| 263 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 264 |
+
|
| 265 |
+
return down_proj
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 269 |
+
"""
|
| 270 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 271 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 272 |
+
"""
|
| 273 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 274 |
+
if n_rep == 1:
|
| 275 |
+
return hidden_states
|
| 276 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 277 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class LlamaAttention(nn.Module):
|
| 281 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 282 |
+
|
| 283 |
+
def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
|
| 284 |
+
super().__init__()
|
| 285 |
+
self.config = config
|
| 286 |
+
self.layer_idx = layer_idx
|
| 287 |
+
if layer_idx is None:
|
| 288 |
+
logger.warning_once(
|
| 289 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 290 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 291 |
+
"when creating this class."
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
self.attention_dropout = config.attention_dropout
|
| 295 |
+
self.hidden_size = config.hidden_size
|
| 296 |
+
self.num_heads = config.num_attention_heads
|
| 297 |
+
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
|
| 298 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 299 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 300 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 301 |
+
self.rope_theta = config.rope_theta
|
| 302 |
+
self.is_causal = True
|
| 303 |
+
self.key_query_norm = config.key_query_norm
|
| 304 |
+
self.key_query_norm_per_head = config.key_query_norm_per_head
|
| 305 |
+
|
| 306 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
| 307 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 308 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 309 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
| 310 |
+
|
| 311 |
+
if self.key_query_norm:
|
| 312 |
+
if self.key_query_norm_per_head:
|
| 313 |
+
# Both query and key have head dim equal to self.hidden_size_per_attention_head
|
| 314 |
+
query_norm_dimensions = self.head_dim
|
| 315 |
+
key_norm_dimensions = self.head_dim
|
| 316 |
+
else:
|
| 317 |
+
# Query dimensions across head is equal to hidden_size but key dimensions are divided
|
| 318 |
+
# by self.num_repeat_kv
|
| 319 |
+
query_norm_dimensions = self.hidden_size
|
| 320 |
+
key_norm_dimensions = self.hidden_size // self.num_repeat_kv
|
| 321 |
+
|
| 322 |
+
# For numerical compatibility we use RMSNorm as it was used during training
|
| 323 |
+
self.norm_query = RMSNorm(
|
| 324 |
+
dimensions=query_norm_dimensions,
|
| 325 |
+
eps=config.rms_norm_eps,
|
| 326 |
+
device=self.q_proj.weight.device,
|
| 327 |
+
dtype=self.q_proj.weight.dtype,
|
| 328 |
+
)
|
| 329 |
+
self.norm_key = RMSNorm(
|
| 330 |
+
dimensions=key_norm_dimensions,
|
| 331 |
+
eps=config.rms_norm_eps,
|
| 332 |
+
device=self.q_proj.weight.device,
|
| 333 |
+
dtype=self.q_proj.weight.dtype,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
|
| 337 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
|
| 338 |
+
|
| 339 |
+
def forward(
|
| 340 |
+
self,
|
| 341 |
+
hidden_states: torch.Tensor,
|
| 342 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 343 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 344 |
+
past_key_value: Optional[Cache] = None,
|
| 345 |
+
output_attentions: bool = False,
|
| 346 |
+
use_cache: bool = False,
|
| 347 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 348 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 349 |
+
**kwargs,
|
| 350 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 351 |
+
bsz, q_len, _ = hidden_states.size()
|
| 352 |
+
|
| 353 |
+
if self.key_query_norm:
|
| 354 |
+
raise ValueError("QK norm not supported for eager attention, use flash_attention_2!")
|
| 355 |
+
|
| 356 |
+
if self.config.pretraining_tp > 1:
|
| 357 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
| 358 |
+
query_slices = self.q_proj.weight.split(
|
| 359 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
| 360 |
+
)
|
| 361 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
| 362 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
| 363 |
+
|
| 364 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 365 |
+
query_states = torch.cat(query_states, dim=-1)
|
| 366 |
+
|
| 367 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 368 |
+
key_states = torch.cat(key_states, dim=-1)
|
| 369 |
+
|
| 370 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 371 |
+
value_states = torch.cat(value_states, dim=-1)
|
| 372 |
+
|
| 373 |
+
else:
|
| 374 |
+
query_states = self.q_proj(hidden_states)
|
| 375 |
+
key_states = self.k_proj(hidden_states)
|
| 376 |
+
value_states = self.v_proj(hidden_states)
|
| 377 |
+
|
| 378 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 379 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 380 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 381 |
+
|
| 382 |
+
if position_embeddings is None:
|
| 383 |
+
logger.warning_once(
|
| 384 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 385 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 386 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 387 |
+
"removed and `position_embeddings` will be mandatory."
|
| 388 |
+
)
|
| 389 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 390 |
+
else:
|
| 391 |
+
cos, sin = position_embeddings
|
| 392 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 393 |
+
|
| 394 |
+
if past_key_value is not None:
|
| 395 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 396 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 397 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 398 |
+
|
| 399 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 400 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 401 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 402 |
+
|
| 403 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 404 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 405 |
+
attn_weights = attn_weights + causal_mask
|
| 406 |
+
|
| 407 |
+
# upcast attention to fp32
|
| 408 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 409 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 410 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 411 |
+
|
| 412 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 413 |
+
raise ValueError(
|
| 414 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 415 |
+
f" {attn_output.size()}"
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 419 |
+
|
| 420 |
+
attn_output = attn_output.reshape(bsz, q_len, -1)
|
| 421 |
+
|
| 422 |
+
if self.config.pretraining_tp > 1:
|
| 423 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
| 424 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
| 425 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
| 426 |
+
else:
|
| 427 |
+
attn_output = self.o_proj(attn_output)
|
| 428 |
+
|
| 429 |
+
if not output_attentions:
|
| 430 |
+
attn_weights = None
|
| 431 |
+
|
| 432 |
+
return attn_output, attn_weights, past_key_value
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class LlamaFlashAttention2(LlamaAttention):
|
| 436 |
+
"""
|
| 437 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
| 438 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 439 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
def __init__(self, *args, **kwargs):
|
| 443 |
+
super().__init__(*args, **kwargs)
|
| 444 |
+
|
| 445 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 446 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
| 447 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
| 448 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 449 |
+
|
| 450 |
+
def forward(
|
| 451 |
+
self,
|
| 452 |
+
hidden_states: torch.Tensor,
|
| 453 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 454 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 455 |
+
past_key_value: Optional[Cache] = None,
|
| 456 |
+
output_attentions: bool = False,
|
| 457 |
+
use_cache: bool = False,
|
| 458 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 459 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 460 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 461 |
+
if isinstance(past_key_value, StaticCache):
|
| 462 |
+
raise ValueError(
|
| 463 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
| 464 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
output_attentions = False
|
| 468 |
+
|
| 469 |
+
bsz, q_len, _ = hidden_states.size()
|
| 470 |
+
|
| 471 |
+
query_states = self.q_proj(hidden_states)
|
| 472 |
+
key_states = self.k_proj(hidden_states)
|
| 473 |
+
value_states = self.v_proj(hidden_states)
|
| 474 |
+
|
| 475 |
+
if self.key_query_norm:
|
| 476 |
+
if not self.key_query_norm_per_head:
|
| 477 |
+
# norm the full hidden fdim
|
| 478 |
+
query_states = self.norm_query(query_states)
|
| 479 |
+
key_states = self.norm_key(key_states)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# Flash attention requires the input to have the shape
|
| 483 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 484 |
+
# therefore we just need to keep the original shape
|
| 485 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 486 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 487 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 488 |
+
|
| 489 |
+
if self.key_query_norm:
|
| 490 |
+
if self.key_query_norm_per_head:
|
| 491 |
+
# norm each head (with shared weights)
|
| 492 |
+
query_states = self.norm_query(query_states)
|
| 493 |
+
key_states = self.norm_key(key_states)
|
| 494 |
+
|
| 495 |
+
if position_embeddings is None:
|
| 496 |
+
logger.warning_once(
|
| 497 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 498 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 499 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 500 |
+
"removed and `position_embeddings` will be mandatory."
|
| 501 |
+
)
|
| 502 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 503 |
+
else:
|
| 504 |
+
cos, sin = position_embeddings
|
| 505 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 506 |
+
|
| 507 |
+
if past_key_value is not None:
|
| 508 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 509 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 510 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 511 |
+
|
| 512 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
| 513 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 514 |
+
query_states = query_states.transpose(1, 2)
|
| 515 |
+
key_states = key_states.transpose(1, 2)
|
| 516 |
+
value_states = value_states.transpose(1, 2)
|
| 517 |
+
|
| 518 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
| 519 |
+
|
| 520 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 521 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 522 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 523 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 524 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
| 525 |
+
|
| 526 |
+
input_dtype = query_states.dtype
|
| 527 |
+
if input_dtype == torch.float32:
|
| 528 |
+
if torch.is_autocast_enabled():
|
| 529 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 530 |
+
# Handle the case where the model is quantized
|
| 531 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 532 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 533 |
+
else:
|
| 534 |
+
target_dtype = self.q_proj.weight.dtype
|
| 535 |
+
|
| 536 |
+
logger.warning_once(
|
| 537 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 538 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 539 |
+
f" {target_dtype}."
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
query_states = query_states.to(target_dtype)
|
| 543 |
+
key_states = key_states.to(target_dtype)
|
| 544 |
+
value_states = value_states.to(target_dtype)
|
| 545 |
+
|
| 546 |
+
attn_output = _flash_attention_forward(
|
| 547 |
+
query_states,
|
| 548 |
+
key_states,
|
| 549 |
+
value_states,
|
| 550 |
+
attention_mask,
|
| 551 |
+
q_len,
|
| 552 |
+
position_ids=position_ids,
|
| 553 |
+
dropout=dropout_rate,
|
| 554 |
+
sliding_window=getattr(self, "sliding_window", None),
|
| 555 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
| 556 |
+
is_causal=self.is_causal,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 560 |
+
attn_output = self.o_proj(attn_output)
|
| 561 |
+
|
| 562 |
+
if not output_attentions:
|
| 563 |
+
attn_weights = None
|
| 564 |
+
|
| 565 |
+
return attn_output, attn_weights, past_key_value
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class LlamaSdpaAttention(LlamaAttention):
|
| 569 |
+
"""
|
| 570 |
+
Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 571 |
+
`LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 572 |
+
SDPA API.
|
| 573 |
+
"""
|
| 574 |
+
|
| 575 |
+
# Adapted from LlamaAttention.forward
|
| 576 |
+
def forward(
|
| 577 |
+
self,
|
| 578 |
+
hidden_states: torch.Tensor,
|
| 579 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 580 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 581 |
+
past_key_value: Optional[Cache] = None,
|
| 582 |
+
output_attentions: bool = False,
|
| 583 |
+
use_cache: bool = False,
|
| 584 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 585 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 586 |
+
**kwargs,
|
| 587 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 588 |
+
if output_attentions:
|
| 589 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 590 |
+
logger.warning_once(
|
| 591 |
+
"LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 592 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 593 |
+
)
|
| 594 |
+
return super().forward(
|
| 595 |
+
hidden_states=hidden_states,
|
| 596 |
+
attention_mask=attention_mask,
|
| 597 |
+
position_ids=position_ids,
|
| 598 |
+
past_key_value=past_key_value,
|
| 599 |
+
output_attentions=output_attentions,
|
| 600 |
+
use_cache=use_cache,
|
| 601 |
+
cache_position=cache_position,
|
| 602 |
+
position_embeddings=position_embeddings,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
bsz, q_len, _ = hidden_states.size()
|
| 606 |
+
|
| 607 |
+
query_states = self.q_proj(hidden_states)
|
| 608 |
+
key_states = self.k_proj(hidden_states)
|
| 609 |
+
value_states = self.v_proj(hidden_states)
|
| 610 |
+
|
| 611 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 612 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 613 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 614 |
+
|
| 615 |
+
if position_embeddings is None:
|
| 616 |
+
logger.warning_once(
|
| 617 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 618 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 619 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 620 |
+
"removed and `position_embeddings` will be mandatory."
|
| 621 |
+
)
|
| 622 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 623 |
+
else:
|
| 624 |
+
cos, sin = position_embeddings
|
| 625 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 626 |
+
|
| 627 |
+
if past_key_value is not None:
|
| 628 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 629 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 630 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 631 |
+
|
| 632 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 633 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 634 |
+
|
| 635 |
+
causal_mask = attention_mask
|
| 636 |
+
if attention_mask is not None:
|
| 637 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
| 638 |
+
|
| 639 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 640 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 641 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
| 642 |
+
query_states = query_states.contiguous()
|
| 643 |
+
key_states = key_states.contiguous()
|
| 644 |
+
value_states = value_states.contiguous()
|
| 645 |
+
|
| 646 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 647 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 648 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
| 649 |
+
|
| 650 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 651 |
+
query_states,
|
| 652 |
+
key_states,
|
| 653 |
+
value_states,
|
| 654 |
+
attn_mask=causal_mask,
|
| 655 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 656 |
+
is_causal=is_causal,
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 660 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
| 661 |
+
|
| 662 |
+
attn_output = self.o_proj(attn_output)
|
| 663 |
+
|
| 664 |
+
return attn_output, None, past_key_value
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
LLAMA_ATTENTION_CLASSES = {
|
| 668 |
+
"eager": LlamaAttention,
|
| 669 |
+
"flash_attention_2": LlamaFlashAttention2,
|
| 670 |
+
"sdpa": LlamaSdpaAttention,
|
| 671 |
+
}
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
class LlamaDecoderLayer(nn.Module):
|
| 675 |
+
def __init__(self, config: LlamaConfig, layer_idx: int):
|
| 676 |
+
super().__init__()
|
| 677 |
+
self.hidden_size = config.hidden_size
|
| 678 |
+
|
| 679 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
| 680 |
+
|
| 681 |
+
self.mlp = LlamaMLP(config)
|
| 682 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 683 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 684 |
+
|
| 685 |
+
def forward(
|
| 686 |
+
self,
|
| 687 |
+
hidden_states: torch.Tensor,
|
| 688 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 689 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 690 |
+
past_key_value: Optional[Cache] = None,
|
| 691 |
+
output_attentions: Optional[bool] = False,
|
| 692 |
+
use_cache: Optional[bool] = False,
|
| 693 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 694 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 695 |
+
**kwargs,
|
| 696 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 697 |
+
"""
|
| 698 |
+
Args:
|
| 699 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 700 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 701 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
| 702 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
| 703 |
+
output_attentions (`bool`, *optional*):
|
| 704 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 705 |
+
returned tensors for more detail.
|
| 706 |
+
use_cache (`bool`, *optional*):
|
| 707 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 708 |
+
(see `past_key_values`).
|
| 709 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 710 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 711 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
| 712 |
+
position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
| 713 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
| 714 |
+
with `head_dim` being the embedding dimension of each attention head.
|
| 715 |
+
kwargs (`dict`, *optional*):
|
| 716 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 717 |
+
into the model
|
| 718 |
+
"""
|
| 719 |
+
residual = hidden_states
|
| 720 |
+
|
| 721 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 722 |
+
|
| 723 |
+
# Self Attention
|
| 724 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 725 |
+
hidden_states=hidden_states,
|
| 726 |
+
attention_mask=attention_mask,
|
| 727 |
+
position_ids=position_ids,
|
| 728 |
+
past_key_value=past_key_value,
|
| 729 |
+
output_attentions=output_attentions,
|
| 730 |
+
use_cache=use_cache,
|
| 731 |
+
cache_position=cache_position,
|
| 732 |
+
position_embeddings=position_embeddings,
|
| 733 |
+
**kwargs,
|
| 734 |
+
)
|
| 735 |
+
hidden_states = residual + hidden_states
|
| 736 |
+
|
| 737 |
+
# Fully Connected
|
| 738 |
+
residual = hidden_states
|
| 739 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 740 |
+
hidden_states = self.mlp(hidden_states)
|
| 741 |
+
hidden_states = residual + hidden_states
|
| 742 |
+
|
| 743 |
+
outputs = (hidden_states,)
|
| 744 |
+
|
| 745 |
+
if output_attentions:
|
| 746 |
+
outputs += (self_attn_weights,)
|
| 747 |
+
|
| 748 |
+
if use_cache:
|
| 749 |
+
outputs += (present_key_value,)
|
| 750 |
+
|
| 751 |
+
return outputs
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
LLAMA_START_DOCSTRING = r"""
|
| 755 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 756 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 757 |
+
etc.)
|
| 758 |
+
|
| 759 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 760 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 761 |
+
and behavior.
|
| 762 |
+
|
| 763 |
+
Parameters:
|
| 764 |
+
config ([`LlamaConfig`]):
|
| 765 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 766 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 767 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 768 |
+
"""
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
@add_start_docstrings(
|
| 772 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
| 773 |
+
LLAMA_START_DOCSTRING,
|
| 774 |
+
)
|
| 775 |
+
class LlamaPreTrainedModel(PreTrainedModel):
|
| 776 |
+
config_class = LlamaConfig
|
| 777 |
+
base_model_prefix = "model"
|
| 778 |
+
supports_gradient_checkpointing = True
|
| 779 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
| 780 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 781 |
+
_supports_flash_attn_2 = True
|
| 782 |
+
_supports_sdpa = True
|
| 783 |
+
_supports_cache_class = True
|
| 784 |
+
_supports_quantized_cache = True
|
| 785 |
+
_supports_static_cache = True
|
| 786 |
+
|
| 787 |
+
def _init_weights(self, module):
|
| 788 |
+
std = self.config.initializer_range
|
| 789 |
+
if isinstance(module, nn.Linear):
|
| 790 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 791 |
+
if module.bias is not None:
|
| 792 |
+
module.bias.data.zero_()
|
| 793 |
+
elif isinstance(module, nn.Embedding):
|
| 794 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 795 |
+
if module.padding_idx is not None:
|
| 796 |
+
module.weight.data[module.padding_idx].zero_()
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
| 800 |
+
Args:
|
| 801 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 802 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 803 |
+
it.
|
| 804 |
+
|
| 805 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 806 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 807 |
+
|
| 808 |
+
[What are input IDs?](../glossary#input-ids)
|
| 809 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 810 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 811 |
+
|
| 812 |
+
- 1 for tokens that are **not masked**,
|
| 813 |
+
- 0 for tokens that are **masked**.
|
| 814 |
+
|
| 815 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 816 |
+
|
| 817 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 818 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 819 |
+
|
| 820 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 821 |
+
`past_key_values`).
|
| 822 |
+
|
| 823 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 824 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 825 |
+
information on the default strategy.
|
| 826 |
+
|
| 827 |
+
- 1 indicates the head is **not masked**,
|
| 828 |
+
- 0 indicates the head is **masked**.
|
| 829 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 830 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 831 |
+
config.n_positions - 1]`.
|
| 832 |
+
|
| 833 |
+
[What are position IDs?](../glossary#position-ids)
|
| 834 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 835 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 836 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 837 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 838 |
+
|
| 839 |
+
Two formats are allowed:
|
| 840 |
+
- a [`~cache_utils.Cache`] instance, see our
|
| 841 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
| 842 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 843 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 844 |
+
cache format.
|
| 845 |
+
|
| 846 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 847 |
+
legacy cache format will be returned.
|
| 848 |
+
|
| 849 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 850 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 851 |
+
of shape `(batch_size, sequence_length)`.
|
| 852 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 853 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 854 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 855 |
+
model's internal embedding lookup matrix.
|
| 856 |
+
use_cache (`bool`, *optional*):
|
| 857 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 858 |
+
`past_key_values`).
|
| 859 |
+
output_attentions (`bool`, *optional*):
|
| 860 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 861 |
+
tensors for more detail.
|
| 862 |
+
output_hidden_states (`bool`, *optional*):
|
| 863 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 864 |
+
more detail.
|
| 865 |
+
return_dict (`bool`, *optional*):
|
| 866 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 867 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 868 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
| 869 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
| 870 |
+
the complete sequence length.
|
| 871 |
+
"""
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
@add_start_docstrings(
|
| 875 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
| 876 |
+
LLAMA_START_DOCSTRING,
|
| 877 |
+
)
|
| 878 |
+
class LlamaModel(LlamaPreTrainedModel):
|
| 879 |
+
"""
|
| 880 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
| 881 |
+
|
| 882 |
+
Args:
|
| 883 |
+
config: LlamaConfig
|
| 884 |
+
"""
|
| 885 |
+
|
| 886 |
+
def __init__(self, config: LlamaConfig):
|
| 887 |
+
super().__init__(config)
|
| 888 |
+
self.padding_idx = config.pad_token_id
|
| 889 |
+
self.vocab_size = config.vocab_size
|
| 890 |
+
|
| 891 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 892 |
+
self.layers = nn.ModuleList(
|
| 893 |
+
[LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 894 |
+
)
|
| 895 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 896 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
| 897 |
+
self.gradient_checkpointing = False
|
| 898 |
+
|
| 899 |
+
# Initialize weights and apply final processing
|
| 900 |
+
self.post_init()
|
| 901 |
+
|
| 902 |
+
def get_input_embeddings(self):
|
| 903 |
+
return self.embed_tokens
|
| 904 |
+
|
| 905 |
+
def set_input_embeddings(self, value):
|
| 906 |
+
self.embed_tokens = value
|
| 907 |
+
|
| 908 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 909 |
+
def forward(
|
| 910 |
+
self,
|
| 911 |
+
input_ids: torch.LongTensor = None,
|
| 912 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 913 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 914 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 915 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 916 |
+
use_cache: Optional[bool] = None,
|
| 917 |
+
output_attentions: Optional[bool] = None,
|
| 918 |
+
output_hidden_states: Optional[bool] = None,
|
| 919 |
+
return_dict: Optional[bool] = None,
|
| 920 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 921 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 922 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 923 |
+
output_hidden_states = (
|
| 924 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 925 |
+
)
|
| 926 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 927 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 928 |
+
|
| 929 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 930 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 931 |
+
|
| 932 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 933 |
+
logger.warning_once(
|
| 934 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 935 |
+
)
|
| 936 |
+
use_cache = False
|
| 937 |
+
|
| 938 |
+
if inputs_embeds is None:
|
| 939 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 940 |
+
|
| 941 |
+
# kept for BC (non `Cache` `past_key_values` inputs)
|
| 942 |
+
return_legacy_cache = False
|
| 943 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
| 944 |
+
return_legacy_cache = True
|
| 945 |
+
if past_key_values is None:
|
| 946 |
+
past_key_values = DynamicCache()
|
| 947 |
+
else:
|
| 948 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
| 949 |
+
logger.warning_once(
|
| 950 |
+
"We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
|
| 951 |
+
"will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
|
| 952 |
+
"(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
if cache_position is None:
|
| 956 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 957 |
+
cache_position = torch.arange(
|
| 958 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 959 |
+
)
|
| 960 |
+
if position_ids is None:
|
| 961 |
+
position_ids = cache_position.unsqueeze(0)
|
| 962 |
+
|
| 963 |
+
causal_mask = self._update_causal_mask(
|
| 964 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
| 965 |
+
)
|
| 966 |
+
hidden_states = inputs_embeds
|
| 967 |
+
|
| 968 |
+
# create position embeddings to be shared across the decoder layers
|
| 969 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 970 |
+
|
| 971 |
+
# decoder layers
|
| 972 |
+
all_hidden_states = () if output_hidden_states else None
|
| 973 |
+
all_self_attns = () if output_attentions else None
|
| 974 |
+
next_decoder_cache = None
|
| 975 |
+
|
| 976 |
+
for decoder_layer in self.layers:
|
| 977 |
+
if output_hidden_states:
|
| 978 |
+
all_hidden_states += (hidden_states,)
|
| 979 |
+
|
| 980 |
+
if self.gradient_checkpointing and self.training:
|
| 981 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 982 |
+
decoder_layer.__call__,
|
| 983 |
+
hidden_states,
|
| 984 |
+
causal_mask,
|
| 985 |
+
position_ids,
|
| 986 |
+
past_key_values,
|
| 987 |
+
output_attentions,
|
| 988 |
+
use_cache,
|
| 989 |
+
cache_position,
|
| 990 |
+
position_embeddings,
|
| 991 |
+
)
|
| 992 |
+
else:
|
| 993 |
+
layer_outputs = decoder_layer(
|
| 994 |
+
hidden_states,
|
| 995 |
+
attention_mask=causal_mask,
|
| 996 |
+
position_ids=position_ids,
|
| 997 |
+
past_key_value=past_key_values,
|
| 998 |
+
output_attentions=output_attentions,
|
| 999 |
+
use_cache=use_cache,
|
| 1000 |
+
cache_position=cache_position,
|
| 1001 |
+
position_embeddings=position_embeddings,
|
| 1002 |
+
)
|
| 1003 |
+
|
| 1004 |
+
hidden_states = layer_outputs[0]
|
| 1005 |
+
|
| 1006 |
+
if use_cache:
|
| 1007 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
| 1008 |
+
|
| 1009 |
+
if output_attentions:
|
| 1010 |
+
all_self_attns += (layer_outputs[1],)
|
| 1011 |
+
|
| 1012 |
+
hidden_states = self.norm(hidden_states)
|
| 1013 |
+
|
| 1014 |
+
# add hidden states from the last decoder layer
|
| 1015 |
+
if output_hidden_states:
|
| 1016 |
+
all_hidden_states += (hidden_states,)
|
| 1017 |
+
|
| 1018 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 1019 |
+
if return_legacy_cache:
|
| 1020 |
+
next_cache = next_cache.to_legacy_cache()
|
| 1021 |
+
|
| 1022 |
+
if not return_dict:
|
| 1023 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 1024 |
+
return BaseModelOutputWithPast(
|
| 1025 |
+
last_hidden_state=hidden_states,
|
| 1026 |
+
past_key_values=next_cache,
|
| 1027 |
+
hidden_states=all_hidden_states,
|
| 1028 |
+
attentions=all_self_attns,
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
def _update_causal_mask(
|
| 1032 |
+
self,
|
| 1033 |
+
attention_mask: torch.Tensor,
|
| 1034 |
+
input_tensor: torch.Tensor,
|
| 1035 |
+
cache_position: torch.Tensor,
|
| 1036 |
+
past_key_values: Cache,
|
| 1037 |
+
output_attentions: bool,
|
| 1038 |
+
):
|
| 1039 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 1040 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
| 1041 |
+
return attention_mask
|
| 1042 |
+
return None
|
| 1043 |
+
|
| 1044 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
| 1045 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
| 1046 |
+
# to infer the attention mask.
|
| 1047 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 1048 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
| 1049 |
+
|
| 1050 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
| 1051 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
| 1052 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
| 1053 |
+
attention_mask,
|
| 1054 |
+
inputs_embeds=input_tensor,
|
| 1055 |
+
past_key_values_length=past_seen_tokens,
|
| 1056 |
+
is_training=self.training,
|
| 1057 |
+
):
|
| 1058 |
+
return None
|
| 1059 |
+
|
| 1060 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 1061 |
+
sequence_length = input_tensor.shape[1]
|
| 1062 |
+
if using_static_cache:
|
| 1063 |
+
target_length = past_key_values.get_max_cache_shape()
|
| 1064 |
+
else:
|
| 1065 |
+
target_length = (
|
| 1066 |
+
attention_mask.shape[-1]
|
| 1067 |
+
if isinstance(attention_mask, torch.Tensor)
|
| 1068 |
+
else past_seen_tokens + sequence_length + 1
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
| 1072 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
| 1073 |
+
attention_mask,
|
| 1074 |
+
sequence_length=sequence_length,
|
| 1075 |
+
target_length=target_length,
|
| 1076 |
+
dtype=dtype,
|
| 1077 |
+
device=device,
|
| 1078 |
+
cache_position=cache_position,
|
| 1079 |
+
batch_size=input_tensor.shape[0],
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
if (
|
| 1083 |
+
self.config._attn_implementation == "sdpa"
|
| 1084 |
+
and attention_mask is not None
|
| 1085 |
+
and attention_mask.device.type == "cuda"
|
| 1086 |
+
and not output_attentions
|
| 1087 |
+
):
|
| 1088 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 1089 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 1090 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 1091 |
+
min_dtype = torch.finfo(dtype).min
|
| 1092 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
| 1093 |
+
|
| 1094 |
+
return causal_mask
|
| 1095 |
+
|
| 1096 |
+
@staticmethod
|
| 1097 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
| 1098 |
+
attention_mask: torch.Tensor,
|
| 1099 |
+
sequence_length: int,
|
| 1100 |
+
target_length: int,
|
| 1101 |
+
dtype: torch.dtype,
|
| 1102 |
+
device: torch.device,
|
| 1103 |
+
cache_position: torch.Tensor,
|
| 1104 |
+
batch_size: int,
|
| 1105 |
+
**kwargs,
|
| 1106 |
+
):
|
| 1107 |
+
"""
|
| 1108 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
| 1109 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
| 1110 |
+
|
| 1111 |
+
Args:
|
| 1112 |
+
attention_mask (`torch.Tensor`):
|
| 1113 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
| 1114 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
| 1115 |
+
sequence_length (`int`):
|
| 1116 |
+
The sequence length being processed.
|
| 1117 |
+
target_length (`int`):
|
| 1118 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
| 1119 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
| 1120 |
+
dtype (`torch.dtype`):
|
| 1121 |
+
The dtype to use for the 4D attention mask.
|
| 1122 |
+
device (`torch.device`):
|
| 1123 |
+
The device to plcae the 4D attention mask on.
|
| 1124 |
+
cache_position (`torch.Tensor`):
|
| 1125 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 1126 |
+
batch_size (`torch.Tensor`):
|
| 1127 |
+
Batch size.
|
| 1128 |
+
"""
|
| 1129 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
| 1130 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
| 1131 |
+
causal_mask = attention_mask
|
| 1132 |
+
else:
|
| 1133 |
+
min_dtype = torch.finfo(dtype).min
|
| 1134 |
+
causal_mask = torch.full(
|
| 1135 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
| 1136 |
+
)
|
| 1137 |
+
if sequence_length != 1:
|
| 1138 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
| 1139 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
| 1140 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
| 1141 |
+
if attention_mask is not None:
|
| 1142 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
| 1143 |
+
mask_length = attention_mask.shape[-1]
|
| 1144 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
| 1145 |
+
padding_mask = padding_mask == 0
|
| 1146 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
| 1147 |
+
padding_mask, min_dtype
|
| 1148 |
+
)
|
| 1149 |
+
|
| 1150 |
+
return causal_mask
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
+
class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
|
| 1154 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1155 |
+
|
| 1156 |
+
def __init__(self, config):
|
| 1157 |
+
super().__init__(config)
|
| 1158 |
+
self.model = LlamaModel(config)
|
| 1159 |
+
self.vocab_size = config.vocab_size
|
| 1160 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1161 |
+
|
| 1162 |
+
# Initialize weights and apply final processing
|
| 1163 |
+
self.post_init()
|
| 1164 |
+
|
| 1165 |
+
def get_input_embeddings(self):
|
| 1166 |
+
return self.model.embed_tokens
|
| 1167 |
+
|
| 1168 |
+
def set_input_embeddings(self, value):
|
| 1169 |
+
self.model.embed_tokens = value
|
| 1170 |
+
|
| 1171 |
+
def get_output_embeddings(self):
|
| 1172 |
+
return self.lm_head
|
| 1173 |
+
|
| 1174 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1175 |
+
self.lm_head = new_embeddings
|
| 1176 |
+
|
| 1177 |
+
def set_decoder(self, decoder):
|
| 1178 |
+
self.model = decoder
|
| 1179 |
+
|
| 1180 |
+
def get_decoder(self):
|
| 1181 |
+
return self.model
|
| 1182 |
+
|
| 1183 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 1184 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 1185 |
+
def forward(
|
| 1186 |
+
self,
|
| 1187 |
+
input_ids: torch.LongTensor = None,
|
| 1188 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1189 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1190 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1191 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1192 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1193 |
+
use_cache: Optional[bool] = None,
|
| 1194 |
+
output_attentions: Optional[bool] = None,
|
| 1195 |
+
output_hidden_states: Optional[bool] = None,
|
| 1196 |
+
return_dict: Optional[bool] = None,
|
| 1197 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1198 |
+
num_logits_to_keep: int = 0,
|
| 1199 |
+
**loss_kwargs,
|
| 1200 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 1201 |
+
r"""
|
| 1202 |
+
Args:
|
| 1203 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1204 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1205 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1206 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1207 |
+
|
| 1208 |
+
num_logits_to_keep (`int`, *optional*):
|
| 1209 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
| 1210 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
| 1211 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
| 1212 |
+
|
| 1213 |
+
Returns:
|
| 1214 |
+
|
| 1215 |
+
Example:
|
| 1216 |
+
|
| 1217 |
+
```python
|
| 1218 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
| 1219 |
+
|
| 1220 |
+
>>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
|
| 1221 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
| 1222 |
+
|
| 1223 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 1224 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1225 |
+
|
| 1226 |
+
>>> # Generate
|
| 1227 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1228 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1229 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1230 |
+
```"""
|
| 1231 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1232 |
+
output_hidden_states = (
|
| 1233 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1234 |
+
)
|
| 1235 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1236 |
+
|
| 1237 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1238 |
+
outputs = self.model(
|
| 1239 |
+
input_ids=input_ids,
|
| 1240 |
+
attention_mask=attention_mask,
|
| 1241 |
+
position_ids=position_ids,
|
| 1242 |
+
past_key_values=past_key_values,
|
| 1243 |
+
inputs_embeds=inputs_embeds,
|
| 1244 |
+
use_cache=use_cache,
|
| 1245 |
+
output_attentions=output_attentions,
|
| 1246 |
+
output_hidden_states=output_hidden_states,
|
| 1247 |
+
return_dict=return_dict,
|
| 1248 |
+
cache_position=cache_position,
|
| 1249 |
+
)
|
| 1250 |
+
|
| 1251 |
+
hidden_states = outputs[0]
|
| 1252 |
+
if self.config.pretraining_tp > 1:
|
| 1253 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
| 1254 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 1255 |
+
logits = torch.cat(logits, dim=-1)
|
| 1256 |
+
else:
|
| 1257 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1258 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
| 1259 |
+
|
| 1260 |
+
loss = None
|
| 1261 |
+
if labels is not None:
|
| 1262 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **loss_kwargs)
|
| 1263 |
+
|
| 1264 |
+
if not return_dict:
|
| 1265 |
+
output = (logits,) + outputs[1:]
|
| 1266 |
+
return (loss,) + output if loss is not None else output
|
| 1267 |
+
|
| 1268 |
+
return CausalLMOutputWithPast(
|
| 1269 |
+
loss=loss,
|
| 1270 |
+
logits=logits,
|
| 1271 |
+
past_key_values=outputs.past_key_values,
|
| 1272 |
+
hidden_states=outputs.hidden_states,
|
| 1273 |
+
attentions=outputs.attentions,
|
| 1274 |
+
)
|
| 1275 |
+
|
| 1276 |
+
|
| 1277 |
+
@add_start_docstrings(
|
| 1278 |
+
"""
|
| 1279 |
+
The LLaMa Model transformer with a sequence classification head on top (linear layer).
|
| 1280 |
+
|
| 1281 |
+
[`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 1282 |
+
(e.g. GPT-2) do.
|
| 1283 |
+
|
| 1284 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1285 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1286 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1287 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1288 |
+
each row of the batch).
|
| 1289 |
+
""",
|
| 1290 |
+
LLAMA_START_DOCSTRING,
|
| 1291 |
+
)
|
| 1292 |
+
class LlamaForSequenceClassification(LlamaPreTrainedModel):
|
| 1293 |
+
def __init__(self, config):
|
| 1294 |
+
super().__init__(config)
|
| 1295 |
+
self.num_labels = config.num_labels
|
| 1296 |
+
self.model = LlamaModel(config)
|
| 1297 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 1298 |
+
|
| 1299 |
+
# Initialize weights and apply final processing
|
| 1300 |
+
self.post_init()
|
| 1301 |
+
|
| 1302 |
+
def get_input_embeddings(self):
|
| 1303 |
+
return self.model.embed_tokens
|
| 1304 |
+
|
| 1305 |
+
def set_input_embeddings(self, value):
|
| 1306 |
+
self.model.embed_tokens = value
|
| 1307 |
+
|
| 1308 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 1309 |
+
def forward(
|
| 1310 |
+
self,
|
| 1311 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1312 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1313 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1314 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1315 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1316 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1317 |
+
use_cache: Optional[bool] = None,
|
| 1318 |
+
output_attentions: Optional[bool] = None,
|
| 1319 |
+
output_hidden_states: Optional[bool] = None,
|
| 1320 |
+
return_dict: Optional[bool] = None,
|
| 1321 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1322 |
+
r"""
|
| 1323 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1324 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1325 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1326 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1327 |
+
"""
|
| 1328 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1329 |
+
|
| 1330 |
+
transformer_outputs = self.model(
|
| 1331 |
+
input_ids,
|
| 1332 |
+
attention_mask=attention_mask,
|
| 1333 |
+
position_ids=position_ids,
|
| 1334 |
+
past_key_values=past_key_values,
|
| 1335 |
+
inputs_embeds=inputs_embeds,
|
| 1336 |
+
use_cache=use_cache,
|
| 1337 |
+
output_attentions=output_attentions,
|
| 1338 |
+
output_hidden_states=output_hidden_states,
|
| 1339 |
+
return_dict=return_dict,
|
| 1340 |
+
)
|
| 1341 |
+
hidden_states = transformer_outputs[0]
|
| 1342 |
+
logits = self.score(hidden_states)
|
| 1343 |
+
|
| 1344 |
+
if input_ids is not None:
|
| 1345 |
+
batch_size = input_ids.shape[0]
|
| 1346 |
+
else:
|
| 1347 |
+
batch_size = inputs_embeds.shape[0]
|
| 1348 |
+
|
| 1349 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1350 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1351 |
+
if self.config.pad_token_id is None:
|
| 1352 |
+
sequence_lengths = -1
|
| 1353 |
+
else:
|
| 1354 |
+
if input_ids is not None:
|
| 1355 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
| 1356 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
| 1357 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
| 1358 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
| 1359 |
+
else:
|
| 1360 |
+
sequence_lengths = -1
|
| 1361 |
+
|
| 1362 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1363 |
+
|
| 1364 |
+
loss = None
|
| 1365 |
+
if labels is not None:
|
| 1366 |
+
loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
|
| 1367 |
+
|
| 1368 |
+
if not return_dict:
|
| 1369 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1370 |
+
return ((loss,) + output) if loss is not None else output
|
| 1371 |
+
|
| 1372 |
+
return SequenceClassifierOutputWithPast(
|
| 1373 |
+
loss=loss,
|
| 1374 |
+
logits=pooled_logits,
|
| 1375 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1376 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1377 |
+
attentions=transformer_outputs.attentions,
|
| 1378 |
+
)
|
| 1379 |
+
|
| 1380 |
+
|
| 1381 |
+
@add_start_docstrings(
|
| 1382 |
+
"""
|
| 1383 |
+
The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
|
| 1384 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1385 |
+
""",
|
| 1386 |
+
LLAMA_START_DOCSTRING,
|
| 1387 |
+
)
|
| 1388 |
+
class LlamaForQuestionAnswering(LlamaPreTrainedModel):
|
| 1389 |
+
base_model_prefix = "transformer"
|
| 1390 |
+
|
| 1391 |
+
# Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
|
| 1392 |
+
def __init__(self, config):
|
| 1393 |
+
super().__init__(config)
|
| 1394 |
+
self.transformer = LlamaModel(config)
|
| 1395 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
| 1396 |
+
|
| 1397 |
+
# Initialize weights and apply final processing
|
| 1398 |
+
self.post_init()
|
| 1399 |
+
|
| 1400 |
+
def get_input_embeddings(self):
|
| 1401 |
+
return self.transformer.embed_tokens
|
| 1402 |
+
|
| 1403 |
+
def set_input_embeddings(self, value):
|
| 1404 |
+
self.transformer.embed_tokens = value
|
| 1405 |
+
|
| 1406 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 1407 |
+
def forward(
|
| 1408 |
+
self,
|
| 1409 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1410 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1411 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1412 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
| 1413 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1414 |
+
start_positions: Optional[torch.LongTensor] = None,
|
| 1415 |
+
end_positions: Optional[torch.LongTensor] = None,
|
| 1416 |
+
output_attentions: Optional[bool] = None,
|
| 1417 |
+
output_hidden_states: Optional[bool] = None,
|
| 1418 |
+
return_dict: Optional[bool] = None,
|
| 1419 |
+
**kwargs,
|
| 1420 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
| 1421 |
+
r"""
|
| 1422 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1423 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1424 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1425 |
+
are not taken into account for computing the loss.
|
| 1426 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1427 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1428 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1429 |
+
are not taken into account for computing the loss.
|
| 1430 |
+
"""
|
| 1431 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1432 |
+
|
| 1433 |
+
outputs = self.transformer(
|
| 1434 |
+
input_ids,
|
| 1435 |
+
attention_mask=attention_mask,
|
| 1436 |
+
position_ids=position_ids,
|
| 1437 |
+
past_key_values=past_key_values,
|
| 1438 |
+
inputs_embeds=inputs_embeds,
|
| 1439 |
+
output_attentions=output_attentions,
|
| 1440 |
+
output_hidden_states=output_hidden_states,
|
| 1441 |
+
return_dict=return_dict,
|
| 1442 |
+
)
|
| 1443 |
+
|
| 1444 |
+
sequence_output = outputs[0]
|
| 1445 |
+
|
| 1446 |
+
logits = self.qa_outputs(sequence_output)
|
| 1447 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1448 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1449 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1450 |
+
|
| 1451 |
+
loss = None
|
| 1452 |
+
if start_positions is not None and end_positions is not None:
|
| 1453 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
| 1454 |
+
|
| 1455 |
+
if not return_dict:
|
| 1456 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1457 |
+
return ((loss,) + output) if loss is not None else output
|
| 1458 |
+
|
| 1459 |
+
return QuestionAnsweringModelOutput(
|
| 1460 |
+
loss=loss,
|
| 1461 |
+
start_logits=start_logits,
|
| 1462 |
+
end_logits=end_logits,
|
| 1463 |
+
hidden_states=outputs.hidden_states,
|
| 1464 |
+
attentions=outputs.attentions,
|
| 1465 |
+
)
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
@add_start_docstrings(
|
| 1469 |
+
"""
|
| 1470 |
+
The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
| 1471 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
| 1472 |
+
""",
|
| 1473 |
+
LLAMA_START_DOCSTRING,
|
| 1474 |
+
)
|
| 1475 |
+
class LlamaForTokenClassification(LlamaPreTrainedModel):
|
| 1476 |
+
def __init__(self, config):
|
| 1477 |
+
super().__init__(config)
|
| 1478 |
+
self.num_labels = config.num_labels
|
| 1479 |
+
self.model = LlamaModel(config)
|
| 1480 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
| 1481 |
+
classifier_dropout = config.classifier_dropout
|
| 1482 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
| 1483 |
+
classifier_dropout = config.hidden_dropout
|
| 1484 |
+
else:
|
| 1485 |
+
classifier_dropout = 0.1
|
| 1486 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1487 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
| 1488 |
+
|
| 1489 |
+
# Initialize weights and apply final processing
|
| 1490 |
+
self.post_init()
|
| 1491 |
+
|
| 1492 |
+
def get_input_embeddings(self):
|
| 1493 |
+
return self.model.embed_tokens
|
| 1494 |
+
|
| 1495 |
+
def set_input_embeddings(self, value):
|
| 1496 |
+
self.model.embed_tokens = value
|
| 1497 |
+
|
| 1498 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
| 1499 |
+
@add_code_sample_docstrings(
|
| 1500 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1501 |
+
output_type=TokenClassifierOutput,
|
| 1502 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1503 |
+
)
|
| 1504 |
+
def forward(
|
| 1505 |
+
self,
|
| 1506 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1507 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1508 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1509 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1510 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1511 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1512 |
+
use_cache: Optional[bool] = None,
|
| 1513 |
+
output_attentions: Optional[bool] = None,
|
| 1514 |
+
output_hidden_states: Optional[bool] = None,
|
| 1515 |
+
return_dict: Optional[bool] = None,
|
| 1516 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
| 1517 |
+
r"""
|
| 1518 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1519 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1520 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1521 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1522 |
+
"""
|
| 1523 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1524 |
+
|
| 1525 |
+
outputs = self.model(
|
| 1526 |
+
input_ids,
|
| 1527 |
+
attention_mask=attention_mask,
|
| 1528 |
+
position_ids=position_ids,
|
| 1529 |
+
past_key_values=past_key_values,
|
| 1530 |
+
inputs_embeds=inputs_embeds,
|
| 1531 |
+
use_cache=use_cache,
|
| 1532 |
+
output_attentions=output_attentions,
|
| 1533 |
+
output_hidden_states=output_hidden_states,
|
| 1534 |
+
return_dict=return_dict,
|
| 1535 |
+
)
|
| 1536 |
+
sequence_output = outputs[0]
|
| 1537 |
+
sequence_output = self.dropout(sequence_output)
|
| 1538 |
+
logits = self.score(sequence_output)
|
| 1539 |
+
|
| 1540 |
+
loss = None
|
| 1541 |
+
if labels is not None:
|
| 1542 |
+
loss = self.loss_function(logits, labels, self.config)
|
| 1543 |
+
|
| 1544 |
+
if not return_dict:
|
| 1545 |
+
output = (logits,) + outputs[2:]
|
| 1546 |
+
return ((loss,) + output) if loss is not None else output
|
| 1547 |
+
|
| 1548 |
+
return TokenClassifierOutput(
|
| 1549 |
+
loss=loss,
|
| 1550 |
+
logits=logits,
|
| 1551 |
+
hidden_states=outputs.hidden_states,
|
| 1552 |
+
attentions=outputs.attentions,
|
| 1553 |
+
)
|