Instructions to use CrowdMind/Blueberry with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use CrowdMind/Blueberry with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="CrowdMind/Blueberry", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("CrowdMind/Blueberry", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use CrowdMind/Blueberry with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "CrowdMind/Blueberry" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CrowdMind/Blueberry", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/CrowdMind/Blueberry
- SGLang
How to use CrowdMind/Blueberry with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "CrowdMind/Blueberry" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CrowdMind/Blueberry", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "CrowdMind/Blueberry" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CrowdMind/Blueberry", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use CrowdMind/Blueberry with Docker Model Runner:
docker model run hf.co/CrowdMind/Blueberry
Release Blueberry gated three-pass model
Browse files- LICENSE-CODE +203 -0
- README.md +44 -0
- chat_template.jinja +21 -0
- config.json +40 -0
- configuration_blueberry.py +137 -0
- generation_config.json +13 -0
- model.safetensors +3 -0
- modeling_blueberry.py +473 -0
- tokenizer.json +0 -0
- tokenizer_config.json +23 -0
LICENSE-CODE
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2018- The Hugging Face team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Apache License
|
| 4 |
+
Version 2.0, January 2004
|
| 5 |
+
http://www.apache.org/licenses/
|
| 6 |
+
|
| 7 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 8 |
+
|
| 9 |
+
1. Definitions.
|
| 10 |
+
|
| 11 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 12 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 13 |
+
|
| 14 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 15 |
+
the copyright owner that is granting the License.
|
| 16 |
+
|
| 17 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 18 |
+
other entities that control, are controlled by, or are under common
|
| 19 |
+
control with that entity. For the purposes of this definition,
|
| 20 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 21 |
+
direction or management of such entity, whether by contract or
|
| 22 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 23 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 24 |
+
|
| 25 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 26 |
+
exercising permissions granted by this License.
|
| 27 |
+
|
| 28 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 29 |
+
including but not limited to software source code, documentation
|
| 30 |
+
source, and configuration files.
|
| 31 |
+
|
| 32 |
+
"Object" form shall mean any form resulting from mechanical
|
| 33 |
+
transformation or translation of a Source form, including but
|
| 34 |
+
not limited to compiled object code, generated documentation,
|
| 35 |
+
and conversions to other media types.
|
| 36 |
+
|
| 37 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 38 |
+
Object form, made available under the License, as indicated by a
|
| 39 |
+
copyright notice that is included in or attached to the work
|
| 40 |
+
(an example is provided in the Appendix below).
|
| 41 |
+
|
| 42 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 43 |
+
form, that is based on (or derived from) the Work and for which the
|
| 44 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 45 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 46 |
+
of this License, Derivative Works shall not include works that remain
|
| 47 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 48 |
+
the Work and Derivative Works thereof.
|
| 49 |
+
|
| 50 |
+
"Contribution" shall mean any work of authorship, including
|
| 51 |
+
the original version of the Work and any modifications or additions
|
| 52 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 53 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 54 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 55 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 56 |
+
means any form of electronic, verbal, or written communication sent
|
| 57 |
+
to the Licensor or its representatives, including but not limited to
|
| 58 |
+
communication on electronic mailing lists, source code control systems,
|
| 59 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 60 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 61 |
+
excluding communication that is conspicuously marked or otherwise
|
| 62 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 63 |
+
|
| 64 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 65 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 66 |
+
subsequently incorporated within the Work.
|
| 67 |
+
|
| 68 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 69 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 70 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 71 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 72 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 73 |
+
Work and such Derivative Works in Source or Object form.
|
| 74 |
+
|
| 75 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 76 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 77 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 78 |
+
(except as stated in this section) patent license to make, have made,
|
| 79 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 80 |
+
where such license applies only to those patent claims licensable
|
| 81 |
+
by such Contributor that are necessarily infringed by their
|
| 82 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 83 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 84 |
+
institute patent litigation against any entity (including a
|
| 85 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 86 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 87 |
+
or contributory patent infringement, then any patent licenses
|
| 88 |
+
granted to You under this License for that Work shall terminate
|
| 89 |
+
as of the date such litigation is filed.
|
| 90 |
+
|
| 91 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 92 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 93 |
+
modifications, and in Source or Object form, provided that You
|
| 94 |
+
meet the following conditions:
|
| 95 |
+
|
| 96 |
+
(a) You must give any other recipients of the Work or
|
| 97 |
+
Derivative Works a copy of this License; and
|
| 98 |
+
|
| 99 |
+
(b) You must cause any modified files to carry prominent notices
|
| 100 |
+
stating that You changed the files; and
|
| 101 |
+
|
| 102 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 103 |
+
that You distribute, all copyright, patent, trademark, and
|
| 104 |
+
attribution notices from the Source form of the Work,
|
| 105 |
+
excluding those notices that do not pertain to any part of
|
| 106 |
+
the Derivative Works; and
|
| 107 |
+
|
| 108 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 109 |
+
distribution, then any Derivative Works that You distribute must
|
| 110 |
+
include a readable copy of the attribution notices contained
|
| 111 |
+
within such NOTICE file, excluding those notices that do not
|
| 112 |
+
pertain to any part of the Derivative Works, in at least one
|
| 113 |
+
of the following places: within a NOTICE text file distributed
|
| 114 |
+
as part of the Derivative Works; within the Source form or
|
| 115 |
+
documentation, if provided along with the Derivative Works; or,
|
| 116 |
+
within a display generated by the Derivative Works, if and
|
| 117 |
+
wherever such third-party notices normally appear. The contents
|
| 118 |
+
of the NOTICE file are for informational purposes only and
|
| 119 |
+
do not modify the License. You may add Your own attribution
|
| 120 |
+
notices within Derivative Works that You distribute, alongside
|
| 121 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 122 |
+
that such additional attribution notices cannot be construed
|
| 123 |
+
as modifying the License.
|
| 124 |
+
|
| 125 |
+
You may add Your own copyright statement to Your modifications and
|
| 126 |
+
may provide additional or different license terms and conditions
|
| 127 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 128 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 129 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 130 |
+
the conditions stated in this License.
|
| 131 |
+
|
| 132 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 133 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 134 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 135 |
+
this License, without any additional terms or conditions.
|
| 136 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 137 |
+
the terms of any separate license agreement you may have executed
|
| 138 |
+
with Licensor regarding such Contributions.
|
| 139 |
+
|
| 140 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 141 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 142 |
+
except as required for reasonable and customary use in describing the
|
| 143 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 144 |
+
|
| 145 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 146 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 147 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 148 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 149 |
+
implied, including, without limitation, any warranties or conditions
|
| 150 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 151 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 152 |
+
appropriateness of using or redistributing the Work and assume any
|
| 153 |
+
risks associated with Your exercise of permissions under this License.
|
| 154 |
+
|
| 155 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 156 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 157 |
+
unless required by applicable law (such as deliberate and grossly
|
| 158 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 159 |
+
liable to You for damages, including any direct, indirect, special,
|
| 160 |
+
incidental, or consequential damages of any character arising as a
|
| 161 |
+
result of this License or out of the use or inability to use the
|
| 162 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 163 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 164 |
+
other commercial damages or losses), even if such Contributor
|
| 165 |
+
has been advised of the possibility of such damages.
|
| 166 |
+
|
| 167 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 168 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 169 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 170 |
+
or other liability obligations and/or rights consistent with this
|
| 171 |
+
License. However, in accepting such obligations, You may act only
|
| 172 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 173 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 174 |
+
defend, and hold each Contributor harmless for any liability
|
| 175 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 176 |
+
of your accepting any such warranty or additional liability.
|
| 177 |
+
|
| 178 |
+
END OF TERMS AND CONDITIONS
|
| 179 |
+
|
| 180 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 181 |
+
|
| 182 |
+
To apply the Apache License to your work, attach the following
|
| 183 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 184 |
+
replaced with your own identifying information. (Don't include
|
| 185 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 186 |
+
comment syntax for the file format. We also recommend that a
|
| 187 |
+
file or class name and description of purpose be included on the
|
| 188 |
+
same "printed page" as the copyright notice for easier
|
| 189 |
+
identification within third-party archives.
|
| 190 |
+
|
| 191 |
+
Copyright [yyyy] [name of copyright owner]
|
| 192 |
+
|
| 193 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 194 |
+
you may not use this file except in compliance with the License.
|
| 195 |
+
You may obtain a copy of the License at
|
| 196 |
+
|
| 197 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 198 |
+
|
| 199 |
+
Unless required by applicable law or agreed to in writing, software
|
| 200 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 201 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 202 |
+
See the License for the specific language governing permissions and
|
| 203 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
pipeline_tag: text-generation
|
| 4 |
+
tags:
|
| 5 |
+
- custom_code
|
| 6 |
+
- blueberry
|
| 7 |
+
base_model: CrowdMind/Blueberry-base
|
| 8 |
+
base_model_relation: finetune
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Blueberry
|
| 12 |
+
|
| 13 |
+
Blueberry is a 125.8-million-parameter decoder-only language model by Dustin Loring (dustinwloring1988@gmail.com).
|
| 14 |
+
It has eight distinct Transformer blocks and runs the middle four three times with shared weights, for 16 block executions.
|
| 15 |
+
A learned per-token gate mixes the state entering the loop with the previous pass at each loop boundary.
|
| 16 |
+
The training context is 2,048 tokens.
|
| 17 |
+
|
| 18 |
+
This is the supervised fine-tuned chat checkpoint at step 1,867. It starts from [Blueberry-base](https://huggingface.co/CrowdMind/Blueberry-base).
|
| 19 |
+
|
| 20 |
+
The training run recorded a validation loss of 0.4138 bits per byte for this stage.
|
| 21 |
+
Training code is available in the [Blueberry project](https://github.com/blueberry-llm/blueberry), which builds on
|
| 22 |
+
[Andrej Karpathy's NanoChat](https://github.com/karpathy/nanochat).
|
| 23 |
+
|
| 24 |
+
## Usage
|
| 25 |
+
|
| 26 |
+
Install Transformers 5.24.0 and PyTorch. The repository includes the Blueberry model implementation and SafeTensors weights.
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 30 |
+
|
| 31 |
+
repo = "CrowdMind/Blueberry"
|
| 32 |
+
tokenizer = AutoTokenizer.from_pretrained(repo)
|
| 33 |
+
model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True)
|
| 34 |
+
messages = [{"role": "user", "content": "In one sentence, explain why the sky is blue."}]
|
| 35 |
+
inputs = tokenizer.apply_chat_template(
|
| 36 |
+
messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
|
| 37 |
+
)
|
| 38 |
+
output = model.generate(**inputs, max_new_tokens=64, do_sample=False)
|
| 39 |
+
print(tokenizer.decode(output[0, inputs.input_ids.shape[1] :], skip_special_tokens=True))
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Limitations
|
| 43 |
+
|
| 44 |
+
Blueberry is a small language model and can generate inaccurate or biased text.
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{- bos_token -}}
|
| 2 |
+
{%- set turns = messages -%}
|
| 3 |
+
{%- set system_prefix = '' -%}
|
| 4 |
+
{%- if turns and turns[0]['role'] == 'system' -%}
|
| 5 |
+
{%- set system_prefix = turns[0]['content'] + '
|
| 6 |
+
|
| 7 |
+
' -%}
|
| 8 |
+
{%- set turns = turns[1:] -%}
|
| 9 |
+
{%- endif -%}
|
| 10 |
+
{%- for message in turns -%}
|
| 11 |
+
{%- if loop.index0 % 2 == 0 and message['role'] == 'user' -%}
|
| 12 |
+
{{- '<|user_start|>' + (system_prefix if loop.first else '') + message['content'] + '<|user_end|>' -}}
|
| 13 |
+
{%- elif loop.index0 % 2 == 1 and message['role'] == 'assistant' -%}
|
| 14 |
+
{{- '<|assistant_start|>' + message['content'] + '<|assistant_end|>' -}}
|
| 15 |
+
{%- else -%}
|
| 16 |
+
{{- raise_exception('Blueberry expects alternating user and assistant turns beginning with the user.') -}}
|
| 17 |
+
{%- endif -%}
|
| 18 |
+
{%- endfor -%}
|
| 19 |
+
{%- if add_generation_prompt -%}
|
| 20 |
+
{{- '<|assistant_start|>' -}}
|
| 21 |
+
{%- endif -%}
|
config.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"BlueberryForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_blueberry.BlueberryConfig",
|
| 7 |
+
"AutoModel": "modeling_blueberry.BlueberryModel",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_blueberry.BlueberryForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 32759,
|
| 11 |
+
"dtype": "float32",
|
| 12 |
+
"eos_token_id": [
|
| 13 |
+
32759,
|
| 14 |
+
32763
|
| 15 |
+
],
|
| 16 |
+
"final_logit_softcapping": 15.0,
|
| 17 |
+
"hidden_act": "relu2",
|
| 18 |
+
"hidden_size": 512,
|
| 19 |
+
"intermediate_size": 2048,
|
| 20 |
+
"loop_gate": true,
|
| 21 |
+
"loop_repeats": 3,
|
| 22 |
+
"max_position_embeddings": 2048,
|
| 23 |
+
"model_type": "blueberry",
|
| 24 |
+
"num_attention_heads": 4,
|
| 25 |
+
"num_key_value_heads": 4,
|
| 26 |
+
"num_unique_layers": 8,
|
| 27 |
+
"pad_token_id": 32759,
|
| 28 |
+
"rope_parameters": {
|
| 29 |
+
"rope_theta": 100000.0,
|
| 30 |
+
"rope_type": "default"
|
| 31 |
+
},
|
| 32 |
+
"sliding_window": 513,
|
| 33 |
+
"smear_gate_channels": 24,
|
| 34 |
+
"tie_word_embeddings": false,
|
| 35 |
+
"transformers_version": "5.24.0.dev0",
|
| 36 |
+
"use_cache": true,
|
| 37 |
+
"value_gate_channels": 12,
|
| 38 |
+
"vocab_size": 32768,
|
| 39 |
+
"window_pattern": "SSS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🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/blueberry/modular_blueberry.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_blueberry.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 Dustin Loring and the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from huggingface_hub.dataclasses import strict
|
| 22 |
+
|
| 23 |
+
from transformers.configuration_utils import PreTrainedConfig
|
| 24 |
+
from transformers.modeling_rope_utils import RopeParameters
|
| 25 |
+
from transformers.utils import auto_docstring
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@auto_docstring(checkpoint="CrowdMind/Blueberry-base")
|
| 29 |
+
@strict
|
| 30 |
+
class BlueberryConfig(PreTrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
num_unique_layers (`int`, *optional*, defaults to 8):
|
| 33 |
+
Number of distinct decoder blocks. `num_hidden_layers` counts their executions, including repeated passes.
|
| 34 |
+
loop_repeats (`int`, *optional*, defaults to 3):
|
| 35 |
+
Total passes through the middle half of the decoder blocks.
|
| 36 |
+
loop_gate (`bool`, *optional*, defaults to `True`):
|
| 37 |
+
Whether to learn a per-token mix of the prelude and previous pass at loop boundaries.
|
| 38 |
+
window_pattern (`str`, *optional*, defaults to `"SSSL"`):
|
| 39 |
+
Pattern tiled across distinct blocks. `S` uses a short sliding window and `L` uses full causal attention.
|
| 40 |
+
The final block always uses full attention.
|
| 41 |
+
sliding_window (`int`, *optional*):
|
| 42 |
+
Short attention window including the current token. Defaults to the quarter-context window rounded up
|
| 43 |
+
to a multiple of 128 predecessors, plus the current token.
|
| 44 |
+
value_gate_channels (`int`, *optional*, defaults to 12):
|
| 45 |
+
Number of hidden channels used by each attention value gate.
|
| 46 |
+
smear_gate_channels (`int`, *optional*, defaults to 24):
|
| 47 |
+
Number of token embedding channels used by the previous-token mixing gate.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
model_type = "blueberry"
|
| 51 |
+
|
| 52 |
+
vocab_size: int = 32768
|
| 53 |
+
hidden_size: int = 512
|
| 54 |
+
intermediate_size: int | None = None
|
| 55 |
+
num_unique_layers: int = 8
|
| 56 |
+
num_attention_heads: int = 4
|
| 57 |
+
num_key_value_heads: int | None = None
|
| 58 |
+
hidden_act: str = "relu2"
|
| 59 |
+
max_position_embeddings: int = 2048
|
| 60 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 61 |
+
loop_repeats: int = 3
|
| 62 |
+
loop_gate: bool = True
|
| 63 |
+
window_pattern: str = "SSSL"
|
| 64 |
+
sliding_window: int | None = None
|
| 65 |
+
value_gate_channels: int = 12
|
| 66 |
+
smear_gate_channels: int = 24
|
| 67 |
+
final_logit_softcapping: float = 15.0
|
| 68 |
+
use_cache: bool = True
|
| 69 |
+
bos_token_id: int | None = None
|
| 70 |
+
eos_token_id: int | list[int] | None = None
|
| 71 |
+
pad_token_id: int | None = None
|
| 72 |
+
tie_word_embeddings: bool = False
|
| 73 |
+
|
| 74 |
+
def __post_init__(self, **kwargs):
|
| 75 |
+
self.intermediate_size = self.intermediate_size if self.intermediate_size is not None else 4 * self.hidden_size
|
| 76 |
+
if self.num_key_value_heads is None:
|
| 77 |
+
self.num_key_value_heads = self.num_attention_heads
|
| 78 |
+
if self.rope_parameters is None:
|
| 79 |
+
self.rope_parameters = {"rope_type": "default", "rope_theta": 100_000.0}
|
| 80 |
+
if self.sliding_window is None:
|
| 81 |
+
self.sliding_window = ((self.max_position_embeddings + 511) // 512) * 128 + 1
|
| 82 |
+
self.window_pattern = self.window_pattern.upper()
|
| 83 |
+
super().__post_init__(**kwargs)
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def loop_start(self):
|
| 87 |
+
return self.num_unique_layers // 4
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def layer_indices(self):
|
| 91 |
+
indices = tuple(range(self.num_unique_layers))
|
| 92 |
+
loop_end = self.loop_start + self.num_unique_layers // 2
|
| 93 |
+
return (
|
| 94 |
+
indices[: self.loop_start] + indices[self.loop_start : loop_end] * self.loop_repeats + indices[loop_end:]
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
@property
|
| 98 |
+
def num_hidden_layers(self):
|
| 99 |
+
return len(self.layer_indices)
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def layer_types(self):
|
| 103 |
+
if not self.window_pattern:
|
| 104 |
+
return []
|
| 105 |
+
types = [
|
| 106 |
+
"sliding_attention" if self.window_pattern[index % len(self.window_pattern)] == "S" else "full_attention"
|
| 107 |
+
for index in self.layer_indices
|
| 108 |
+
]
|
| 109 |
+
# The last cache slot holds full attention KV and the previous unsmeared token embedding.
|
| 110 |
+
return types[:-1] + ["hybrid"]
|
| 111 |
+
|
| 112 |
+
def has_value_embedding(self, layer_idx):
|
| 113 |
+
return layer_idx % 2 == (self.num_unique_layers - 1) % 2
|
| 114 |
+
|
| 115 |
+
def validate_architecture(self):
|
| 116 |
+
if self.num_unique_layers < 1 or self.loop_repeats < 1:
|
| 117 |
+
raise ValueError("Blueberry requires at least one decoder block and one loop pass.")
|
| 118 |
+
if self.loop_repeats > 1 and (self.num_unique_layers < 4 or self.num_unique_layers % 2):
|
| 119 |
+
raise ValueError("Multiple loop passes require an even number of distinct blocks of at least four.")
|
| 120 |
+
if self.loop_gate and self.loop_repeats == 1:
|
| 121 |
+
raise ValueError("The loop gate requires at least two loop passes.")
|
| 122 |
+
if not self.window_pattern or set(self.window_pattern) - {"S", "L"}:
|
| 123 |
+
raise ValueError("`window_pattern` must contain one or more S or L characters.")
|
| 124 |
+
if self.sliding_window < 1:
|
| 125 |
+
raise ValueError("`sliding_window` must be positive.")
|
| 126 |
+
if (
|
| 127 |
+
self.num_attention_heads < 1
|
| 128 |
+
or self.hidden_size % (2 * self.num_attention_heads)
|
| 129 |
+
or self.num_key_value_heads < 1
|
| 130 |
+
or self.num_attention_heads % self.num_key_value_heads
|
| 131 |
+
):
|
| 132 |
+
raise ValueError("Blueberry requires an even head dimension and valid grouped heads.")
|
| 133 |
+
if not (0 < self.value_gate_channels <= self.hidden_size and 0 < self.smear_gate_channels <= self.hidden_size):
|
| 134 |
+
raise ValueError("Gate channel counts must be positive and at most hidden_size.")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
__all__ = ["BlueberryConfig"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 32759,
|
| 4 |
+
"eos_token_id": [
|
| 5 |
+
32759,
|
| 6 |
+
32763
|
| 7 |
+
],
|
| 8 |
+
"output_attentions": false,
|
| 9 |
+
"output_hidden_states": false,
|
| 10 |
+
"pad_token_id": 32759,
|
| 11 |
+
"transformers_version": "5.24.0.dev0",
|
| 12 |
+
"use_cache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🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/blueberry/modular_blueberry.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_blueberry.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 Dustin Loring and the HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn as nn
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
|
| 27 |
+
from transformers import initialization as init
|
| 28 |
+
from transformers.activations import ACT2FN
|
| 29 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 30 |
+
from transformers.generation import GenerationMixin
|
| 31 |
+
from transformers.masking_utils import create_masks_for_generate
|
| 32 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 33 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 34 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 35 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel, slice_logits_to_keep
|
| 36 |
+
from transformers.processing_utils import Unpack
|
| 37 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 38 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 39 |
+
from transformers.utils.generic import merge_with_config_defaults
|
| 40 |
+
from transformers.utils.output_capturing import capture_outputs
|
| 41 |
+
from .configuration_blueberry import BlueberryConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class BlueberryRotaryEmbedding(nn.Module):
|
| 45 |
+
def __init__(self, config: BlueberryConfig):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 48 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 49 |
+
|
| 50 |
+
self.config = config
|
| 51 |
+
|
| 52 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 53 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 54 |
+
if self.rope_type != "default":
|
| 55 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 56 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config)
|
| 57 |
+
|
| 58 |
+
self.inv_freq = nn.Buffer(inv_freq, persistent=False)
|
| 59 |
+
self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False)
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def compute_default_rope_parameters(config: BlueberryConfig, **kwargs) -> tuple[torch.Tensor, float]:
|
| 63 |
+
"""
|
| 64 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 65 |
+
Args:
|
| 66 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 67 |
+
The model configuration.
|
| 68 |
+
Returns:
|
| 69 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 70 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 71 |
+
"""
|
| 72 |
+
base = config.rope_parameters["rope_theta"]
|
| 73 |
+
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 74 |
+
|
| 75 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 76 |
+
# Compute the inverse frequencies
|
| 77 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
|
| 78 |
+
return inv_freq, attention_factor
|
| 79 |
+
|
| 80 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 81 |
+
def forward(self, x, position_ids):
|
| 82 |
+
freqs = position_ids[..., None].float() * self.inv_freq.to(device=x.device, dtype=torch.float)
|
| 83 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 84 |
+
cos = emb.cos() * self.attention_scaling
|
| 85 |
+
sin = emb.sin() * self.attention_scaling
|
| 86 |
+
|
| 87 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class BlueberryMLP(nn.Module):
|
| 91 |
+
def __init__(self, config):
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.config = config
|
| 94 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 95 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 96 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 97 |
+
|
| 98 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 99 |
+
hidden_states = self.fc1(hidden_states)
|
| 100 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 101 |
+
hidden_states = self.fc2(hidden_states)
|
| 102 |
+
return hidden_states
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 106 |
+
"""
|
| 107 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 108 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 109 |
+
"""
|
| 110 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 111 |
+
if n_rep == 1:
|
| 112 |
+
return hidden_states
|
| 113 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 114 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def eager_attention_forward(
|
| 118 |
+
module: nn.Module,
|
| 119 |
+
query: torch.Tensor,
|
| 120 |
+
key: torch.Tensor,
|
| 121 |
+
value: torch.Tensor,
|
| 122 |
+
attention_mask: torch.Tensor | None,
|
| 123 |
+
scaling: float,
|
| 124 |
+
dropout: float = 0.0,
|
| 125 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 126 |
+
):
|
| 127 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 128 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 129 |
+
|
| 130 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 131 |
+
if attention_mask is not None:
|
| 132 |
+
attn_weights = attn_weights + attention_mask
|
| 133 |
+
|
| 134 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 135 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 136 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 137 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 138 |
+
|
| 139 |
+
return attn_output, attn_weights
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 143 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
q (`torch.Tensor`): The query tensor.
|
| 147 |
+
k (`torch.Tensor`): The key tensor.
|
| 148 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 149 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 150 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 151 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 152 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 153 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 154 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 155 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 156 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 157 |
+
Returns:
|
| 158 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 159 |
+
"""
|
| 160 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 161 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 162 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 163 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 164 |
+
return q_embed, k_embed
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def rotate_half(x):
|
| 168 |
+
"""Rotates half the hidden dims of the input with flipped signs for Blueberry."""
|
| 169 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 170 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 171 |
+
return torch.cat((x2, -x1), dim=-1)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def blueberry_rms_norm(hidden_states):
|
| 175 |
+
return F.rms_norm(hidden_states, (hidden_states.shape[-1],))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class BlueberryAttention(nn.Module):
|
| 179 |
+
def __init__(self, config: BlueberryConfig, layer_idx: int):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.config = config
|
| 182 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 183 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 184 |
+
self.is_causal = True
|
| 185 |
+
|
| 186 |
+
kv_size = config.num_key_value_heads * self.head_dim
|
| 187 |
+
self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 188 |
+
self.k_proj = nn.Linear(config.hidden_size, kv_size, bias=False)
|
| 189 |
+
self.v_proj = nn.Linear(config.hidden_size, kv_size, bias=False)
|
| 190 |
+
self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
| 191 |
+
self.value_gate = (
|
| 192 |
+
nn.Linear(config.value_gate_channels, config.num_key_value_heads, bias=False)
|
| 193 |
+
if config.has_value_embedding(layer_idx)
|
| 194 |
+
else None
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def forward(
|
| 198 |
+
self,
|
| 199 |
+
hidden_states: torch.Tensor,
|
| 200 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 201 |
+
attention_mask: torch.Tensor | None,
|
| 202 |
+
value_embeddings: torch.Tensor | None = None,
|
| 203 |
+
cache: Cache | None = None,
|
| 204 |
+
execution_idx: int = 0,
|
| 205 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 206 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 207 |
+
input_shape = hidden_states.shape[:-1]
|
| 208 |
+
head_shape = (*input_shape, -1, self.head_dim)
|
| 209 |
+
query = self.q_proj(hidden_states).view(head_shape).transpose(1, 2)
|
| 210 |
+
key = self.k_proj(hidden_states).view(head_shape).transpose(1, 2)
|
| 211 |
+
value = self.v_proj(hidden_states).view(head_shape).transpose(1, 2)
|
| 212 |
+
|
| 213 |
+
if value_embeddings is not None:
|
| 214 |
+
gate_input = hidden_states[..., : self.config.value_gate_channels]
|
| 215 |
+
gate = 3 * torch.sigmoid(self.value_gate(gate_input)).transpose(1, 2).unsqueeze(-1)
|
| 216 |
+
value = value + gate * value_embeddings.view(head_shape).transpose(1, 2).to(value.dtype)
|
| 217 |
+
|
| 218 |
+
query, key = apply_rotary_pos_emb(query, key, *position_embeddings)
|
| 219 |
+
query = 1.2 * blueberry_rms_norm(query)
|
| 220 |
+
key = 1.2 * blueberry_rms_norm(key)
|
| 221 |
+
if cache is not None:
|
| 222 |
+
key, value = cache.update(key, value, execution_idx, kwargs=kwargs)
|
| 223 |
+
|
| 224 |
+
attention = ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, eager_attention_forward)
|
| 225 |
+
output, weights = attention(self, query, key, value, attention_mask, scaling=self.head_dim**-0.5, **kwargs)
|
| 226 |
+
return self.o_proj(output.reshape(*input_shape, -1)), weights
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class BlueberryDecoderLayer(GradientCheckpointingLayer):
|
| 230 |
+
def __init__(self, config: BlueberryConfig, layer_idx: int):
|
| 231 |
+
super().__init__()
|
| 232 |
+
self.self_attn = BlueberryAttention(config, layer_idx)
|
| 233 |
+
self.mlp = BlueberryMLP(config)
|
| 234 |
+
|
| 235 |
+
def forward(
|
| 236 |
+
self,
|
| 237 |
+
hidden_states: torch.Tensor,
|
| 238 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 239 |
+
attention_mask: torch.Tensor | None,
|
| 240 |
+
value_embeddings: torch.Tensor | None = None,
|
| 241 |
+
cache: Cache | None = None,
|
| 242 |
+
execution_idx: int = 0,
|
| 243 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 244 |
+
) -> torch.Tensor:
|
| 245 |
+
attention_output, _ = self.self_attn(
|
| 246 |
+
blueberry_rms_norm(hidden_states),
|
| 247 |
+
position_embeddings=position_embeddings,
|
| 248 |
+
attention_mask=attention_mask,
|
| 249 |
+
value_embeddings=value_embeddings,
|
| 250 |
+
cache=cache,
|
| 251 |
+
execution_idx=execution_idx,
|
| 252 |
+
**kwargs,
|
| 253 |
+
)
|
| 254 |
+
hidden_states = hidden_states + attention_output
|
| 255 |
+
return hidden_states + self.mlp(blueberry_rms_norm(hidden_states))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@auto_docstring
|
| 259 |
+
class BlueberryPreTrainedModel(PreTrainedModel):
|
| 260 |
+
config: BlueberryConfig
|
| 261 |
+
base_model_prefix = "model"
|
| 262 |
+
_no_split_modules = ["BlueberryDecoderLayer"]
|
| 263 |
+
_supports_sdpa = True
|
| 264 |
+
_can_compile_fullgraph = True
|
| 265 |
+
supports_gradient_checkpointing = True
|
| 266 |
+
_can_record_outputs = {"hidden_states": BlueberryDecoderLayer, "attentions": BlueberryAttention}
|
| 267 |
+
|
| 268 |
+
def _resize_token_embeddings(self, new_num_tokens, pad_to_multiple_of=None, mean_resizing=True):
|
| 269 |
+
embeddings = super()._resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
|
| 270 |
+
value_embeds = self.base_model.value_embeds
|
| 271 |
+
for key, embedding in value_embeds.items():
|
| 272 |
+
value_embeds[key] = self._get_resized_embeddings(
|
| 273 |
+
embedding, new_num_tokens, pad_to_multiple_of, mean_resizing
|
| 274 |
+
)
|
| 275 |
+
return embeddings
|
| 276 |
+
|
| 277 |
+
def _init_weights(self, module: nn.Module):
|
| 278 |
+
super()._init_weights(module)
|
| 279 |
+
bound = (3 / self.config.hidden_size) ** 0.5
|
| 280 |
+
if isinstance(module, BlueberryModel):
|
| 281 |
+
init.normal_(module.embed_tokens.weight, std=0.8)
|
| 282 |
+
for embedding in module.value_embeds.values():
|
| 283 |
+
init.uniform_(embedding.weight, -bound, bound)
|
| 284 |
+
init.copy_(module.resid_lambdas, torch.linspace(1.15, 1.05, self.config.num_unique_layers))
|
| 285 |
+
init.copy_(module.x0_lambdas, torch.linspace(0.20, 0.05, self.config.num_unique_layers))
|
| 286 |
+
init.zeros_(module.smear_lambda)
|
| 287 |
+
init.uniform_(module.smear_gate.weight, 0.0, 0.02)
|
| 288 |
+
init.constant_(module.backout_lambda, 0.2)
|
| 289 |
+
if module.loop_gate is not None:
|
| 290 |
+
init.zeros_(module.loop_gate.weight)
|
| 291 |
+
init.constant_(module.loop_gate_bias, -4.0)
|
| 292 |
+
elif isinstance(module, BlueberryAttention):
|
| 293 |
+
for projection in (module.q_proj, module.k_proj, module.v_proj):
|
| 294 |
+
init.uniform_(projection.weight, -bound, bound)
|
| 295 |
+
init.zeros_(module.o_proj.weight)
|
| 296 |
+
if module.value_gate is not None:
|
| 297 |
+
init.uniform_(module.value_gate.weight, 0.0, 0.02)
|
| 298 |
+
elif isinstance(module, BlueberryMLP):
|
| 299 |
+
init.uniform_(module.fc1.weight, -0.4 * bound, 0.4 * bound)
|
| 300 |
+
init.zeros_(module.fc2.weight)
|
| 301 |
+
elif isinstance(module, BlueberryForCausalLM):
|
| 302 |
+
init.normal_(module.lm_head.weight, std=0.001)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@auto_docstring
|
| 306 |
+
class BlueberryModel(BlueberryPreTrainedModel):
|
| 307 |
+
def __init__(self, config: BlueberryConfig):
|
| 308 |
+
super().__init__(config)
|
| 309 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 310 |
+
self.layers = nn.ModuleList([BlueberryDecoderLayer(config, idx) for idx in range(config.num_unique_layers)])
|
| 311 |
+
self.rotary_emb = BlueberryRotaryEmbedding(config)
|
| 312 |
+
self.layer_indices = config.layer_indices
|
| 313 |
+
self.attention_types = tuple(
|
| 314 |
+
"full_attention" if layer_type == "hybrid" else layer_type for layer_type in config.layer_types
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
kv_size = config.num_key_value_heads * (config.hidden_size // config.num_attention_heads)
|
| 318 |
+
self.value_embeds = nn.ModuleDict(
|
| 319 |
+
{
|
| 320 |
+
str(idx): nn.Embedding(config.vocab_size, kv_size)
|
| 321 |
+
for idx in range(config.num_unique_layers)
|
| 322 |
+
if config.has_value_embedding(idx)
|
| 323 |
+
}
|
| 324 |
+
)
|
| 325 |
+
self.resid_lambdas = nn.Parameter(torch.empty(config.num_unique_layers))
|
| 326 |
+
self.x0_lambdas = nn.Parameter(torch.empty(config.num_unique_layers))
|
| 327 |
+
self.smear_gate = nn.Linear(config.smear_gate_channels, 1, bias=False)
|
| 328 |
+
self.smear_lambda = nn.Parameter(torch.empty(1))
|
| 329 |
+
self.backout_lambda = nn.Parameter(torch.empty(1))
|
| 330 |
+
self.loop_gate = nn.Linear(2 * config.hidden_size, 1, bias=False) if config.loop_gate else None
|
| 331 |
+
self.loop_gate_bias = nn.Parameter(torch.empty(1)) if config.loop_gate else None
|
| 332 |
+
|
| 333 |
+
loop_size = config.num_unique_layers // 2
|
| 334 |
+
self.loop_pass_starts = tuple(config.loop_start + loop_size * idx for idx in range(1, config.loop_repeats))
|
| 335 |
+
self.gradient_checkpointing = False
|
| 336 |
+
self.post_init()
|
| 337 |
+
|
| 338 |
+
@merge_with_config_defaults
|
| 339 |
+
@capture_outputs
|
| 340 |
+
@auto_docstring
|
| 341 |
+
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
|
| 342 |
+
def forward(
|
| 343 |
+
self,
|
| 344 |
+
input_ids: torch.LongTensor | None = None,
|
| 345 |
+
attention_mask: torch.Tensor | dict | None = None,
|
| 346 |
+
position_ids: torch.LongTensor | None = None,
|
| 347 |
+
cache: Cache | None = None,
|
| 348 |
+
use_cache: bool | None = None,
|
| 349 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 350 |
+
) -> BaseModelOutputWithPast:
|
| 351 |
+
r"""
|
| 352 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 353 |
+
Token IDs used to look up both the input and per-layer value embeddings.
|
| 354 |
+
"""
|
| 355 |
+
if input_ids is None:
|
| 356 |
+
raise ValueError("Blueberry requires input_ids to look up the per-layer value embeddings.")
|
| 357 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 358 |
+
|
| 359 |
+
if self.gradient_checkpointing and self.training:
|
| 360 |
+
use_cache = False
|
| 361 |
+
if use_cache is False:
|
| 362 |
+
cache = None
|
| 363 |
+
elif cache is None:
|
| 364 |
+
cache = DynamicCache(config=self.config)
|
| 365 |
+
|
| 366 |
+
if position_ids is None:
|
| 367 |
+
if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2:
|
| 368 |
+
position_ids = (attention_mask.long().cumsum(-1) - 1).clamp_min(0)[:, -input_ids.shape[1] :]
|
| 369 |
+
else:
|
| 370 |
+
past_length = cache.get_seq_length() if cache is not None else 0
|
| 371 |
+
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0) + past_length
|
| 372 |
+
|
| 373 |
+
masks = attention_mask
|
| 374 |
+
if not isinstance(masks, dict):
|
| 375 |
+
masks = create_masks_for_generate(self.config, inputs_embeds, attention_mask, cache, position_ids)
|
| 376 |
+
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
|
| 377 |
+
|
| 378 |
+
hidden_states = blueberry_rms_norm(inputs_embeds)
|
| 379 |
+
history = hidden_states.transpose(1, 2)
|
| 380 |
+
if cache is not None:
|
| 381 |
+
history = cache.update_conv_state(history, len(self.layer_indices) - 1, conv_kernel_size=1)
|
| 382 |
+
previous = F.pad(history, (1, 0))[..., -input_ids.shape[1] - 1 : -1].transpose(1, 2)
|
| 383 |
+
smear_input = hidden_states[..., : self.config.smear_gate_channels]
|
| 384 |
+
smear = self.smear_lambda.to(hidden_states.dtype) * torch.sigmoid(self.smear_gate(smear_input))
|
| 385 |
+
hidden_states = hidden_states + smear * previous * (position_ids > 0).unsqueeze(-1)
|
| 386 |
+
|
| 387 |
+
initial_states = hidden_states
|
| 388 |
+
backout_states = prelude = hidden_states
|
| 389 |
+
backout_idx = len(self.layer_indices) // 2
|
| 390 |
+
for execution_idx, (layer_idx, attention_type) in enumerate(zip(self.layer_indices, self.attention_types)):
|
| 391 |
+
if self.loop_gate is not None:
|
| 392 |
+
if execution_idx == self.config.loop_start:
|
| 393 |
+
prelude = hidden_states
|
| 394 |
+
elif execution_idx in self.loop_pass_starts:
|
| 395 |
+
gate_input = torch.cat((blueberry_rms_norm(prelude), blueberry_rms_norm(hidden_states)), dim=-1)
|
| 396 |
+
gate = torch.sigmoid(self.loop_gate(gate_input) + self.loop_gate_bias.to(hidden_states.dtype))
|
| 397 |
+
hidden_states = torch.lerp(prelude, hidden_states, gate)
|
| 398 |
+
|
| 399 |
+
hidden_states = self.resid_lambdas[layer_idx] * hidden_states + self.x0_lambdas[layer_idx] * initial_states
|
| 400 |
+
value_embeddings = (
|
| 401 |
+
self.value_embeds[str(layer_idx)](input_ids) if str(layer_idx) in self.value_embeds else None
|
| 402 |
+
)
|
| 403 |
+
hidden_states = self.layers[layer_idx](
|
| 404 |
+
hidden_states,
|
| 405 |
+
position_embeddings=position_embeddings,
|
| 406 |
+
attention_mask=masks[attention_type],
|
| 407 |
+
value_embeddings=value_embeddings,
|
| 408 |
+
cache=cache,
|
| 409 |
+
execution_idx=execution_idx,
|
| 410 |
+
**kwargs,
|
| 411 |
+
)
|
| 412 |
+
if execution_idx == backout_idx:
|
| 413 |
+
backout_states = hidden_states
|
| 414 |
+
|
| 415 |
+
hidden_states = hidden_states - self.backout_lambda.to(hidden_states.dtype) * backout_states
|
| 416 |
+
return BaseModelOutputWithPast(last_hidden_state=blueberry_rms_norm(hidden_states), cache=cache)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@auto_docstring
|
| 420 |
+
class BlueberryForCausalLM(BlueberryPreTrainedModel, GenerationMixin):
|
| 421 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 422 |
+
|
| 423 |
+
def __init__(self, config: BlueberryConfig):
|
| 424 |
+
super().__init__(config)
|
| 425 |
+
self.model = BlueberryModel(config)
|
| 426 |
+
self.vocab_size = config.vocab_size
|
| 427 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 428 |
+
self.post_init()
|
| 429 |
+
|
| 430 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 431 |
+
# The per-layer value embeddings also require the original token IDs.
|
| 432 |
+
return super().prepare_inputs_for_generation(input_ids, **kwargs)
|
| 433 |
+
|
| 434 |
+
@can_return_tuple
|
| 435 |
+
@auto_docstring
|
| 436 |
+
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
|
| 437 |
+
def forward(
|
| 438 |
+
self,
|
| 439 |
+
input_ids: torch.LongTensor | None = None,
|
| 440 |
+
attention_mask: torch.Tensor | dict | None = None,
|
| 441 |
+
position_ids: torch.LongTensor | None = None,
|
| 442 |
+
cache: Cache | None = None,
|
| 443 |
+
labels: torch.LongTensor | None = None,
|
| 444 |
+
use_cache: bool | None = None,
|
| 445 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 446 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 447 |
+
) -> CausalLMOutputWithPast:
|
| 448 |
+
r"""
|
| 449 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 450 |
+
Token IDs used to look up both the input and per-layer value embeddings.
|
| 451 |
+
"""
|
| 452 |
+
outputs = self.model(
|
| 453 |
+
input_ids=input_ids,
|
| 454 |
+
attention_mask=attention_mask,
|
| 455 |
+
position_ids=position_ids,
|
| 456 |
+
cache=cache,
|
| 457 |
+
use_cache=use_cache,
|
| 458 |
+
**kwargs,
|
| 459 |
+
)
|
| 460 |
+
hidden_states = slice_logits_to_keep(outputs.last_hidden_state, logits_to_keep)
|
| 461 |
+
softcap = self.config.final_logit_softcapping
|
| 462 |
+
logits = softcap * torch.tanh(self.lm_head(hidden_states).float() / softcap)
|
| 463 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs) if labels is not None else None
|
| 464 |
+
return CausalLMOutputWithPast(
|
| 465 |
+
logits=logits,
|
| 466 |
+
loss=loss,
|
| 467 |
+
cache=outputs.cache,
|
| 468 |
+
hidden_states=outputs.hidden_states,
|
| 469 |
+
attentions=outputs.attentions,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
__all__ = ["BlueberryForCausalLM", "BlueberryModel", "BlueberryPreTrainedModel"]
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|bos|>",
|
| 4 |
+
"eos_token": "<|bos|>",
|
| 5 |
+
"extra_special_tokens": [
|
| 6 |
+
"<|assistant_end|>",
|
| 7 |
+
"<|assistant_start|>",
|
| 8 |
+
"<|output_end|>",
|
| 9 |
+
"<|output_start|>",
|
| 10 |
+
"<|python_end|>",
|
| 11 |
+
"<|python_start|>",
|
| 12 |
+
"<|user_end|>",
|
| 13 |
+
"<|user_start|>"
|
| 14 |
+
],
|
| 15 |
+
"model_input_names": [
|
| 16 |
+
"input_ids",
|
| 17 |
+
"attention_mask"
|
| 18 |
+
],
|
| 19 |
+
"model_max_length": 2048,
|
| 20 |
+
"pad_token": "<|bos|>",
|
| 21 |
+
"padding_side": "left",
|
| 22 |
+
"tokenizer_class": "TokenizersBackend"
|
| 23 |
+
}
|