BerryLM-OS-DFlash2
Browse filesCo-authored-by: itwastony <itwastony@users.noreply.huggingface.co>
Files changed (7)
- .gitattributesAdded+35
- LICENSEAdded+202
- README.mdAdded+212
- config.jsonAdded+58
- model.safetensorsAdded+3
- sglang-pr39972-dflash.diffAdded+89
- vllm-pr57384-dflash.diffAdded+105
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212---license: apache-2.0language: [ru, en]base_model:- rwb-ai/BerryLM-OSinference: falsetags: [berrylm, speculative-decoding, dflash, dflash2, block-diffusion, draft-model, vllm, sglang, llama.cpp]---
# BerryLM-OS-DFlash2
Draft model for speculative decoding with [BerryLM-OS](https://huggingface.co/rwb-ai/BerryLM-OS), built on[DFlash 2](https://inco.ai/blog/dflash2/) (block-diffusion drafting). In one forward pass the drafter proposes a blockof 7 tokens, conditioned on hidden states of BerryLM-OS. BerryLM-OS then checks the whole block in one pass, keeps the accepted prefix and adds onetoken of its own. Every emitted token goes through BerryLM-OS's verification (rejection sampling), so the drafterchanges the speed of generation, not the output distribution (up to floating-point differences of batchedcomputation). It runs on vLLM, SGLang and llama.cpp; the GGUF file for llama.cpp is in[BerryLM-OS-GGUF](https://huggingface.co/rwb-ai/BerryLM-OS-GGUF).
## How it works
- **Input.** A block of 8 positions: the last accepted token (the anchor) and 7 mask tokens (token id 180215). All 7 draft tokens are predicted at once, not one after another.- **Target features.** The residual stream after BerryLM-OS decoder layers 3, 11, 20, 28 and 37 (0-based, before the final norm), concatenated, projected to 2048 by one linear layer and normalized. The drafter attends to these features over a sliding window of 2048 context positions and to the block itself in both directions.- **Drafter.** 5 decoder layers: hidden size 2048, 16 query and 2 key-value heads of dimension 256, MLP 6144. DFlash2 additions: two-tap dynamic grouped convolutions in every layer and a candidate selector (rank 256) that rescores the top-16 tokens of each position to pick the drafted path.- **Size.** About 0.41B own parameters (bf16, 815 MB). Token embeddings and the LM head are shared with BerryLM-OS and are not stored here.
## Training
Trained with the [speculators](https://github.com/vllm-project/speculators) library. The DFlash 2 training objectiveis not published; we trained with our own implementation. The training set has about 0.94M sequences (2.4B tokens) whoseresponses BerryLM-OS generated itself (temperature 1.0, top-p 0.95, top-k 20), 60% with thinking and 40% without;6 epochs, block size 8.
## Serving
The vLLM, SGLang and llama.cpp commands below use the BerryLM pull requests. The listed vLLM and SGLang revisions include DFlash2 support.
### vLLM
Use the BerryLM branch of vLLM. The commands below check out the revision tested with this drafter. [vLLM PR #57384](https://github.com/vllm-project/vllm/pull/57384)
```bashgit clone https://github.com/vllm-project/vllm.git && cd vllmgit fetch origin pull/57384/headgit checkout -b berrylm 7060026c613db283d70efc250f05ab6bbced9317VLLM_USE_PRECOMPILED=1 VLLM_PRECOMPILED_WHEEL_COMMIT=cb6458c5ce61632524c0447d49790725c1e1d9a2 pip install -e .VLLM_USE_V2_MODEL_RUNNER=1 vllm serve rwb-ai/BerryLM-OS \ --spec-model rwb-ai/BerryLM-OS-DFlash2 --spec-method dflash --spec-tokens 7 \ --speculative-config '{"draft_sample_method": "probabilistic"}' \ --tensor-parallel-size 1 \ --reasoning-parser berrylm --tool-call-parser berrylm --enable-auto-tool-choice```
BerryLM uses two changes in this vLLM revision for speculative decoding.
- **Hidden-state interface.** It adds `SupportsEagle3` / `EagleModelMixin` to the BerryLM model so that vLLM can return the residual streams of the layers listed in this drafter's config. Without it vLLM stops at startup with `Model does not support EAGLE3 interface`.- **KDA fix.** It passes dense tensors to the linear-attention recurrence that verifies draft tokens. That kernel assumes a dense memory layout; without the fix it reads the draft tokens with the wrong layout, which corrupts outputs during speculative decoding.
Notes:
- `--spec-tokens` must be 7: the drafter was trained with blocks of 8 positions.- `draft_sample_method: probabilistic` samples the drafted path from the selector scores instead of taking the top candidate. With the sampling settings of BerryLM-OS it drafts more accepted tokens than the default greedy path. Remove the `--speculative-config` line to use greedy drafting.- Sampling parameters come from BerryLM-OS's `generation_config.json`, as without the drafter.
### SGLang
This SGLang revision captures the residual streams requested by the draft model for `--speculative-algorithm DFLASH`. [SGLang PR #55435](https://github.com/sgl-project/sglang/pull/55435)
```bashgit clone https://github.com/sgl-project/sglang.git && cd sglanggit fetch origin pull/55435/headgit checkout -b berrylm ebedc568181c5290660b3295666382556976ff05pip install -e "python"python -m sglang.launch_server --model-path rwb-ai/BerryLM-OS --port 8000 \ --speculative-algorithm DFLASH --speculative-draft-model-path rwb-ai/BerryLM-OS-DFlash2 \ --speculative-num-draft-tokens 8 \ --reasoning-parser berrylm --tool-call-parser berrylm```
`--speculative-num-draft-tokens` counts the whole block of 8 positions (the anchor and 7 draft tokens).
### llama.cpp
The drafter is converted to GGUF and stored next to the BerryLM-OS GGUF files: `BerryLM-OS-DFlash2-BF16.gguf` in[BerryLM-OS-GGUF](https://huggingface.co/rwb-ai/BerryLM-OS-GGUF). llama.cpp supports DFlash2 drafting; BerryLM itselfneeds the pull request [ggml-org/llama.cpp#30234](https://github.com/ggml-org/llama.cpp/pull/30234). Build llama.cppfrom it as described in BerryLM-OS-GGUF, then:
```bashhf download rwb-ai/BerryLM-OS-GGUF BerryLM-OS-Q6_K.gguf BerryLM-OS-DFlash2-BF16.gguf --local-dir ../build/bin/llama-server -m BerryLM-OS-Q6_K.gguf -md BerryLM-OS-DFlash2-BF16.gguf -ngl 99 -ngld 99 \ -c 32768 --no-reasoning-preserve --port 8080 \ --spec-type draft-dflash --spec-draft-n-max 7 --spec-draft-n-min 0 --spec-draft-p-min 0 \ --spec-draft-sampling probabilistic```
`--spec-draft-n-max` must be 7. The same drafter file works with every BerryLM-OS GGUF quantization.
## Speed
Output tokens per second with the drafter divided by the same engine without it, on the same machine, one GPU perserver. Protocol at the end of this section.
### vLLM
Output tokens per second of BerryLM-OS alone and with the drafter (probabilistic drafting, as in the maincommand above), the speedup, and the mean acceptance length τ: per request, 1 + accepted draft tokens perBerryLM-OS verification step, averaged over requests. Mean of three repetitions, protocol below.
#### 1 request
| task | BerryLM-OS alone, tok/s | with the drafter, tok/s | speedup | τ ||---|---:|---:|---:|---:|| GSM8K | 221 | 609 | 2.75× | 5.32 || HumanEval | 221 | 660 | 2.98× | 5.56 || MATH-500 | 222 | 686 | 3.09× | 5.65 || MBPP | 228 | 583 | 2.56× | 4.82 || MT-Bench | 222 | 521 | 2.35× | 4.38 |
#### 8 concurrent requests
| task | BerryLM-OS alone, tok/s | with the drafter, tok/s | speedup | τ ||---|---:|---:|---:|---:|| GSM8K | 955 | 2,682 | 2.81× | 5.33 || HumanEval | 949 | 2,780 | 2.93× | 5.59 || MATH-500 | 967 | 2,995 | 3.10× | 5.66 || MBPP | 957 | 2,409 | 2.52× | 4.83 || MT-Bench | 940 | 2,204 | 2.34× | 4.41 |
#### 32 concurrent requests
| task | BerryLM-OS alone, tok/s | with the drafter, tok/s | speedup | τ ||---|---:|---:|---:|---:|| GSM8K | 2,191 | 6,191 | 2.83× | 5.29 || HumanEval | 2,139 | 6,275 | 2.94× | 5.60 || MATH-500 | 2,360 | 7,265 | 3.08× | 5.65 || MBPP | 2,047 | 5,636 | 2.75× | 4.84 || MT-Bench | 2,166 | 5,082 | 2.35× | 4.38 |
Greedy drafting (without `--speculative-config`): 2.25–2.95× (τ 4.24–5.46) over the same conditions.The 95% confidence interval of each speedup (Student t over the three repetitions) is within ±17% of its value.
### SGLang
Speedup of SGLang with the drafter over SGLang alone, and τ at 1 request. Mean of three repetitions,same requests and sampling as for vLLM.
| task | 1 request | 8 concurrent | 32 concurrent | τ ||---|---:|---:|---:|---:|| GSM8K | 2.99× | 2.62× | 2.60× | 5.32 || HumanEval | 3.22× | 2.74× | 2.72× | 5.58 || MATH-500 | 3.30× | 2.91× | 2.93× | 5.62 || MBPP | 2.76× | 2.43× | 2.25× | 4.83 || MT-Bench | 2.48× | 2.20× | 2.29× | 4.38 |
With the drafter SGLang outputs 0.86–0.95 of vLLM's tokens per second (vLLM with the drafter, measured in the same run). SGLang alone is slower than vLLM alone at 1 request (0.84–0.87 of its tokens per second), so its speedup there is higher.
### llama.cpp
Speedup of `llama-server` with the drafter GGUF over `llama-server` alone with the same BerryLM-OS GGUF,1 request at a time, probabilistic drafting. Mean of three repetitions.
| task | `BF16` | `Q8_0` | `Q6_K` | `Q4_K_M` ||---|---:|---:|---:|---:|| GSM8K | 1.96× | 1.94× | 1.77× | 1.86× || HumanEval | 2.00× | 2.03× | 1.83× | 1.95× || MATH-500 | 2.14× | 2.12× | 1.91× | 2.05× || MBPP | 1.83× | 1.81× | 1.65× | 1.73× || MT-Bench | 1.71× | 1.67× | 1.51× | 1.61× |
τ is 4.49–5.71 and within ±0.1 of vLLM's on the same requests for every file: quantization of BerryLM-OS does not lower the acceptance.
Output quality, scored on the same generations: on vLLM (either drafting mode) and SGLang the share of correctanswers on GSM8K, MATH-500, HumanEval and MBPP with the drafter differs from BerryLM-OS alone by 1.3 pointsat most, and every 95% confidence interval of the difference includes zero and stays within ±4.0 points. Onllama.cpp the check used 32 requests per task, which resolves only large changes: the differences span-7.3 to +7.3 points (mean +1.3) over the four files and both drafting modes. The capof 4096 new tokens cuts many answers short, so these accuracies are not comparable with the evaluation of BerryLM-OS.
Protocol: one GPU per server, tensor parallel 1. vLLM and SGLang: bf16 BerryLM-OS, `--max-model-len 16384`(SGLang `--context-length 16384`), at most 32 running requests, prefix caching off; 128 requests per task from GSM8K,HumanEval, MATH-500, MBPP and MT-Bench (first turn only), formatted as in the DFlash authors' benchmark code, in a fixedrandom order; HumanEval (164 items) and MT-Bench (80 items) repeat some prompts; 1, 8 and 32 concurrent requests.llama.cpp: the drafter GGUF in BF16 with each BerryLM-OS GGUF, all layers on the GPU, context 17408, the first 32 ofthe same requests per task, 1 request at a time, prompts sent as token ids. All engines: thinking on, up to 4096 newtokens, temperature 0.8, top-p 0.95, top-k 20, three repetitions with different sampling seeds.
## Limitations
- Trained for the bf16 weights of BerryLM-OS. llama.cpp was also measured with the Q8_0, Q6_K and Q4_K_M GGUF files; [BerryLM-OS-FP8](https://huggingface.co/rwb-ai/BerryLM-OS-FP8) is not tested.- Measured with tensor parallel 1 on one GPU model. The speedup depends on the GPU (the drafter's cost relative to BerryLM-OS's); larger tensor parallel sizes are not tested.- llama.cpp was measured with 1 request at a time, on CUDA; on Apple silicon (Metal) only a short check was run (see [BerryLM-OS-GGUF](https://huggingface.co/rwb-ai/BerryLM-OS-GGUF)).- Measured with thinking on. Direct answers (`enable_thinking=False`) are not measured.
## License
Released under the Apache License 2.0.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758{ "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": null, "eos_token_id": null, "head_dim": 256, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 6144, "layer_types": [ "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention" ], "max_position_embeddings": 262144, "max_window_layers": 28, "model_type": "qwen3", "num_attention_heads": 16, "num_hidden_layers": 5, "num_key_value_heads": 2, "pad_token_id": null, "rms_norm_eps": 1e-06, "rope_parameters": { "rope_theta": 10000000, "rope_type": "default" }, "sliding_window": 2048, "tie_word_embeddings": false, "use_cache": true, "use_sliding_window": true, "vocab_size": 180224, "architectures": [ "DFlash2DraftModel" ], "dtype": "bfloat16", "is_causal": false, "num_target_layers": 40, "transformers_version": "5.16.1", "dflash_config": { "block_size": 8, "mask_token": "<|endoftext|>", "mask_token_id": 180215, "target_layer_ids": [ 3, 11, 20, 28, 37 ], "conv_kernel_size": 2, "conv_group_size": 16, "selector_rank": 256, "selector_top_k": 16 }}123version https://git-lfs.github.com/spec/v1oid sha256:114177cfb2635ea2cfde00987301a0f6829404f49877322902711679143dc1f5size 8149704481234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889diff --git a/python/sglang/srt/models/berrylm.py b/python/sglang/srt/models/berrylm.pyindex 2d238e3601..9432074d7a 100644--- a/python/sglang/srt/models/berrylm.py+++ b/python/sglang/srt/models/berrylm.py@@ -54,6 +54,7 @@ from sglang.srt.layers.linear import ( ReplicatedLinear, RowParallelLinear, )+from sglang.srt.layers.aux_hidden_states import AuxHiddenStateList from sglang.srt.layers.logits_processor import LogitsProcessor from sglang.srt.layers.moe import ( get_moe_a2a_backend,@@ -1033,6 +1034,8 @@ class BerryLMModel(nn.Module): prefix=add_prefix("layers", prefix), ) self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)+ # Layers before which the completed residual stream is captured for a draft model.+ self.layers_to_capture: List[int] = [] def forward( self,@@ -1049,6 +1052,7 @@ class BerryLMModel(nn.Module): block = self.attn_res_block_size # Residual streams committed at block boundaries (embeddings first). completed: List[torch.Tensor] = []+ aux_hidden_states = AuxHiddenStateList() for layer_idx in range(self._start_layer, self._end_layer): layer = self.layers[layer_idx] with get_global_expert_distribution_recorder().with_current_layer(@@ -1059,6 +1063,9 @@ class BerryLMModel(nn.Module): # previous layer's output into it, mix, and hand the mixed # stream to the layer as an already-written residual. stream = residual_batch.fold(hidden_states, forward_batch)+ if layer_idx in self.layers_to_capture:+ # The completed stream after layer layer_idx - 1, before this layer's AttnRes.+ aux_hidden_states.capture(stream) if layer_idx % block == 0: completed.append(stream) hidden_states = residual_batch.set_written(@@ -1069,9 +1076,12 @@ class BerryLMModel(nn.Module): hidden_states=hidden_states, forward_batch=forward_batch, )- return residual_batch.final_norm(+ hidden_states = residual_batch.final_norm( hidden_states, forward_batch, self.norm, skip_empty=True )+ return (+ (hidden_states, aux_hidden_states) if aux_hidden_states else hidden_states+ ) class BerryLMForCausalLM(nn.Module):@@ -1102,6 +1112,7 @@ class BerryLMForCausalLM(nn.Module): prefix=add_prefix("lm_head", prefix), ) self.logits_processor = LogitsProcessor(config)+ self.capture_aux_hidden_states = False def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens@@ -1115,10 +1126,26 @@ class BerryLMForCausalLM(nn.Module): input_embeds: Optional[torch.Tensor] = None, ) -> torch.Tensor: hidden_states = self.model(input_ids, positions, forward_batch, input_embeds)+ aux_hidden_states = None+ if self.capture_aux_hidden_states:+ hidden_states, aux_hidden_states = hidden_states return self.logits_processor(- input_ids, hidden_states, self.lm_head, forward_batch+ input_ids, hidden_states, self.lm_head, forward_batch, aux_hidden_states ) + def set_dflash_layers_to_capture(self, layer_ids: List[int]):+ if layer_ids is None:+ raise ValueError("DFLASH requires explicit layer_ids for aux hidden capture.")+ # The stream is captured where the layer loop folds it, which needs AttnRes.+ if not self.model.attn_res_block_size:+ raise NotImplementedError("BerryLM aux hidden capture needs attn_res_block_size > 0")+ # Capture before layer k + 1 gives the completed output of target layer k (HF hidden_states[k + 1]).+ layers = [val + 1 for val in layer_ids]+ if not all(1 <= layer < self.config.num_hidden_layers for layer in layers):+ raise ValueError(f"BerryLM cannot capture after layers {layer_ids}")+ self.capture_aux_hidden_states = True+ self.model.layers_to_capture = layers+ def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]): stacked_params_mapping = [ # (param_name, shard_name, shard_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105--- a/vllm/model_executor/models/berrylm.py+++ b/vllm/model_executor/models/berrylm.py@@ -86,9 +86,11 @@ ) from vllm.model_executor.model_loader.weight_utils import sharded_weight_loader from vllm.model_executor.models.interfaces import (+ EagleModelMixin, HasInnerState, IsHybrid, MixtureOfExperts,+ SupportsEagle3, SupportsLoRA, ) from vllm.model_executor.models.utils import (@@ -1573,12 +1575,13 @@ assert qkv_spec is not None assert spec_query_start_loc is not None q_spec, k_spec, v_spec = self._split_qkv(qkv_spec)+ # The low-level recurrence requires dense token strides. core_attn_out_spec, _ = fused_recurrent_kda_fwd(- q=q_spec,- k=k_spec,- v=v_spec,- g=self._fused_gate(g_spec),- beta=beta_spec,+ q=q_spec.contiguous(),+ k=k_spec.contiguous(),+ v=v_spec.contiguous(),+ g=self._fused_gate(g_spec).contiguous(),+ beta=beta_spec.contiguous(), scale=self.head_k_dim**-0.5, initial_state=recurrent_state, inplace_final_state=True,@@ -1839,7 +1842,7 @@ @support_torch_compile-class BerryLMModel(nn.Module):+class BerryLMModel(nn.Module, EagleModelMixin): hf_to_vllm_mapper = WeightsMapper( orig_to_new_stacked={ # weight_name: (param_name, shard_id)@@ -1925,6 +1928,9 @@ # first); local graph intermediates, so CUDA-graph safe. The stream entering # the first layer of a block is committed by that layer's entry kernel. completed: list[torch.Tensor] = []+ aux_hidden_states = self._maybe_add_hidden_state(+ [], self.start_layer, hidden_states, residual+ ) for layer_idx, layer in enumerate( islice(self.layers, self.start_layer, self.end_layer), start=self.start_layer,@@ -1942,12 +1948,17 @@ residual=residual, input_normed=bool(block_size), )+ self._maybe_add_hidden_state(+ aux_hidden_states, layer_idx + 1, hidden_states, residual+ ) if not get_pp_group().is_last_rank: return IntermediateTensors( {"hidden_states": hidden_states, "residual": residual} ) hidden_states, _ = self.norm(hidden_states, residual)+ if aux_hidden_states:+ return hidden_states, aux_hidden_states return hidden_states def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:@@ -2011,6 +2022,7 @@ class BerryLMForCausalLM( nn.Module, HasInnerState,+ SupportsEagle3, SupportsLoRA, BerryLMMixtureOfExperts, IsHybrid,@@ -2044,6 +2056,10 @@ self.scheduler_config = scheduler_config self.model = BerryLMModel( vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")+ )+ self._reject_sharded_aux_streams = any(+ getattr(layer, "use_attn_reduce_scatter_for_moe", False)+ for layer in self.model.layers ) if get_pp_group().is_last_rank: if config.tie_word_embeddings:@@ -2067,6 +2083,15 @@ def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.model.embed_input_ids(input_ids) + def set_aux_hidden_state_layers(self, layers: tuple[int, ...]) -> None:+ if layers and self._reject_sharded_aux_streams:+ raise NotImplementedError(+ "BerryLM aux hidden states need the full residual stream; "+ "attention reduce-scatter for MoE shards it across TP ranks. "+ "Serve with tensor-parallel-size 1 (data parallel instead)."+ )+ SupportsEagle3.set_aux_hidden_state_layers(self, layers)+ def forward( self, input_ids: torch.Tensor | None,.gitattributesAdded+35
LICENSEAdded+202
README.mdAdded+212
config.jsonAdded+58
model.safetensorsAdded+3
sglang-pr39972-dflash.diffAdded+89
vllm-pr57384-dflash.diffAdded+105