Upload verified plain block FP8 Agnes Preview weights
Browse files- LICENSE +201 -0
- chat_template.jinja +170 -0
- config.json +458 -0
- configuration_agnes.py +203 -0
- generation_config.json +12 -0
- image_processing_agnes.py +190 -0
- inference_manifest.json +184 -0
- merges.txt +0 -0
- model-00001.safetensors +3 -0
- model-00002.safetensors +3 -0
- model-00003.safetensors +3 -0
- model-00004.safetensors +3 -0
- model-00005.safetensors +3 -0
- model-00006.safetensors +3 -0
- model-00007.safetensors +3 -0
- model-00008.safetensors +3 -0
- model-00009.safetensors +3 -0
- model-00010.safetensors +3 -0
- model-00011.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_agnes.py +1559 -0
- preprocessor_config.json +25 -0
- processing_agnes.py +116 -0
- serve.sh +36 -0
- sglang_patch/agnes_sglang_config.py +57 -0
- sglang_patch/apply_patch.py +130 -0
- sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/configs/agnes.py +57 -0
- sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/models/qwen3_5.py +0 -0
- sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/utils/hf_transformers/common.py +729 -0
- sglang_patch/v0.5.19/sglang/srt/configs/agnes.py +57 -0
- sglang_patch/v0.5.19/sglang/srt/models/qwen3_5.py +0 -0
- sglang_patch/v0.5.19/sglang/srt/utils/hf_transformers/common.py +670 -0
- tokenizer.json +0 -0
- tokenizer_config.json +413 -0
- video_preprocessor_config.json +27 -0
- video_processing_agnes.py +197 -0
- vocab.json +0 -0
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- set image_count = namespace(value=0) %}
|
| 2 |
+
{%- set video_count = namespace(value=0) %}
|
| 3 |
+
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
|
| 4 |
+
{%- if content is string %}
|
| 5 |
+
{{- content }}
|
| 6 |
+
{%- elif content is iterable and content is not mapping %}
|
| 7 |
+
{%- for item in content %}
|
| 8 |
+
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
|
| 9 |
+
{%- if is_system_content %}
|
| 10 |
+
{{- raise_exception('System message cannot contain images.') }}
|
| 11 |
+
{%- endif %}
|
| 12 |
+
{%- if do_vision_count %}
|
| 13 |
+
{%- set image_count.value = image_count.value + 1 %}
|
| 14 |
+
{%- endif %}
|
| 15 |
+
{%- if add_vision_id %}
|
| 16 |
+
{{- 'Picture ' ~ image_count.value ~ ': ' }}
|
| 17 |
+
{%- endif %}
|
| 18 |
+
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
|
| 19 |
+
{%- elif 'video' in item or item.type == 'video' %}
|
| 20 |
+
{%- if is_system_content %}
|
| 21 |
+
{{- raise_exception('System message cannot contain videos.') }}
|
| 22 |
+
{%- endif %}
|
| 23 |
+
{%- if do_vision_count %}
|
| 24 |
+
{%- set video_count.value = video_count.value + 1 %}
|
| 25 |
+
{%- endif %}
|
| 26 |
+
{%- if add_vision_id %}
|
| 27 |
+
{{- 'Video ' ~ video_count.value ~ ': ' }}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
|
| 30 |
+
{%- elif 'text' in item %}
|
| 31 |
+
{{- item.text }}
|
| 32 |
+
{%- else %}
|
| 33 |
+
{{- raise_exception('Unexpected item type in content.') }}
|
| 34 |
+
{%- endif %}
|
| 35 |
+
{%- endfor %}
|
| 36 |
+
{%- elif content is none or content is undefined %}
|
| 37 |
+
{{- '' }}
|
| 38 |
+
{%- else %}
|
| 39 |
+
{{- raise_exception('Unexpected content type.') }}
|
| 40 |
+
{%- endif %}
|
| 41 |
+
{%- endmacro %}
|
| 42 |
+
{%- if not messages %}
|
| 43 |
+
{{- raise_exception('No messages provided.') }}
|
| 44 |
+
{%- endif %}
|
| 45 |
+
{%- set reasoning_instructions = '' %}
|
| 46 |
+
{%- if enable_thinking is undefined or enable_thinking is true %}
|
| 47 |
+
{%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
|
| 48 |
+
{%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
|
| 49 |
+
{{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
|
| 50 |
+
{%- endif %}
|
| 51 |
+
{%- if resolved_reasoning_effort == 'xhigh' %}
|
| 52 |
+
{%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
|
| 53 |
+
{%- elif resolved_reasoning_effort == 'low' %}
|
| 54 |
+
{%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
|
| 55 |
+
{%- endif %}
|
| 56 |
+
{%- endif %}
|
| 57 |
+
{%- if tools and tools is iterable and tools is not mapping %}
|
| 58 |
+
{{- '<|im_start|>system\n' }}
|
| 59 |
+
{%- if reasoning_instructions %}
|
| 60 |
+
{{- reasoning_instructions + '\n\n' }}
|
| 61 |
+
{%- endif %}
|
| 62 |
+
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
|
| 63 |
+
{%- for tool in tools %}
|
| 64 |
+
{{- "\n" }}
|
| 65 |
+
{{- tool | tojson }}
|
| 66 |
+
{%- endfor %}
|
| 67 |
+
{{- "\n</tools>" }}
|
| 68 |
+
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
|
| 69 |
+
{%- if messages[0].role == 'system' %}
|
| 70 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 71 |
+
{%- if content %}
|
| 72 |
+
{{- '\n\n' + content }}
|
| 73 |
+
{%- endif %}
|
| 74 |
+
{%- endif %}
|
| 75 |
+
{{- '<|im_end|>\n' }}
|
| 76 |
+
{%- else %}
|
| 77 |
+
{%- if messages[0].role == 'system' %}
|
| 78 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 79 |
+
{%- if content %}
|
| 80 |
+
{{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}
|
| 81 |
+
{%- elif reasoning_instructions %}
|
| 82 |
+
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
|
| 83 |
+
{%- endif %}
|
| 84 |
+
{%- elif reasoning_instructions %}
|
| 85 |
+
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
|
| 86 |
+
{%- endif %}
|
| 87 |
+
{%- endif %}
|
| 88 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 89 |
+
{%- for message in messages[::-1] %}
|
| 90 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 91 |
+
{%- if ns.multi_step_tool and message.role == "user" %}
|
| 92 |
+
{%- set content = render_content(message.content, false)|trim %}
|
| 93 |
+
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
|
| 94 |
+
{%- set ns.multi_step_tool = false %}
|
| 95 |
+
{%- set ns.last_query_index = index %}
|
| 96 |
+
{%- endif %}
|
| 97 |
+
{%- endif %}
|
| 98 |
+
{%- endfor %}
|
| 99 |
+
{%- if ns.multi_step_tool %}
|
| 100 |
+
{{- raise_exception('No user query found in messages.') }}
|
| 101 |
+
{%- endif %}
|
| 102 |
+
{%- for message in messages %}
|
| 103 |
+
{%- set content = render_content(message.content, true)|trim %}
|
| 104 |
+
{%- if message.role == "system" %}
|
| 105 |
+
{%- if not loop.first %}
|
| 106 |
+
{{- raise_exception('System message must be at the beginning.') }}
|
| 107 |
+
{%- endif %}
|
| 108 |
+
{%- elif message.role == "user" %}
|
| 109 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 110 |
+
{%- elif message.role == "assistant" %}
|
| 111 |
+
{%- set reasoning_content = '' %}
|
| 112 |
+
{%- if message.reasoning_content is string %}
|
| 113 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 114 |
+
{%- endif %}
|
| 115 |
+
{%- set reasoning_content = reasoning_content|trim %}
|
| 116 |
+
{%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}
|
| 117 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
|
| 118 |
+
{%- else %}
|
| 119 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 120 |
+
{%- endif %}
|
| 121 |
+
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 122 |
+
{%- for tool_call in message.tool_calls %}
|
| 123 |
+
{%- if tool_call.function is defined %}
|
| 124 |
+
{%- set tool_call = tool_call.function %}
|
| 125 |
+
{%- endif %}
|
| 126 |
+
{%- if loop.first %}
|
| 127 |
+
{%- if content|trim %}
|
| 128 |
+
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 129 |
+
{%- else %}
|
| 130 |
+
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 131 |
+
{%- endif %}
|
| 132 |
+
{%- else %}
|
| 133 |
+
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 134 |
+
{%- endif %}
|
| 135 |
+
{%- if tool_call.arguments is defined and tool_call.arguments != '' %}
|
| 136 |
+
{%- for args_name, args_value in tool_call.arguments|items %}
|
| 137 |
+
{{- '<parameter=' + args_name + '>\n' }}
|
| 138 |
+
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
|
| 139 |
+
{{- args_value }}
|
| 140 |
+
{{- '\n</parameter>\n' }}
|
| 141 |
+
{%- endfor %}
|
| 142 |
+
{%- endif %}
|
| 143 |
+
{{- '</function>\n</tool_call>' }}
|
| 144 |
+
{%- endfor %}
|
| 145 |
+
{%- endif %}
|
| 146 |
+
{{- '<|im_end|>\n' }}
|
| 147 |
+
{%- elif message.role == "tool" %}
|
| 148 |
+
{%- if loop.previtem and loop.previtem.role != "tool" %}
|
| 149 |
+
{{- '<|im_start|>user' }}
|
| 150 |
+
{%- endif %}
|
| 151 |
+
{{- '\n<tool_response>\n' }}
|
| 152 |
+
{{- content }}
|
| 153 |
+
{{- '\n</tool_response>' }}
|
| 154 |
+
{%- if not loop.last and loop.nextitem.role != "tool" %}
|
| 155 |
+
{{- '<|im_end|>\n' }}
|
| 156 |
+
{%- elif loop.last %}
|
| 157 |
+
{{- '<|im_end|>\n' }}
|
| 158 |
+
{%- endif %}
|
| 159 |
+
{%- else %}
|
| 160 |
+
{{- raise_exception('Unexpected message role.') }}
|
| 161 |
+
{%- endif %}
|
| 162 |
+
{%- endfor %}
|
| 163 |
+
{%- if add_generation_prompt %}
|
| 164 |
+
{{- '<|im_start|>assistant\n' }}
|
| 165 |
+
{%- if enable_thinking is defined and enable_thinking is false %}
|
| 166 |
+
{{- '<think>\n\n</think>\n\n' }}
|
| 167 |
+
{%- else %}
|
| 168 |
+
{{- '<think>\n' }}
|
| 169 |
+
{%- endif %}
|
| 170 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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_map": {
|
| 7 |
+
"AutoConfig": "configuration_agnes.AgnesConfig",
|
| 8 |
+
"AutoModel": "modeling_agnes.AgnesModel",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_agnes.AgnesForConditionalGeneration",
|
| 10 |
+
"AutoModelForImageTextToText": "modeling_agnes.AgnesForConditionalGeneration"
|
| 11 |
+
},
|
| 12 |
+
"text_config": {
|
| 13 |
+
"model_type": "agnes_text",
|
| 14 |
+
"hidden_size": 5120,
|
| 15 |
+
"num_hidden_layers": 72,
|
| 16 |
+
"intermediate_size": 19456,
|
| 17 |
+
"parallel_ffn_intermediate_size": 0,
|
| 18 |
+
"vocab_size": 248320,
|
| 19 |
+
"layer_types": [
|
| 20 |
+
"agnes_delta_attention",
|
| 21 |
+
"agnes_delta_attention",
|
| 22 |
+
"agnes_delta_attention",
|
| 23 |
+
"agnes_global_attention",
|
| 24 |
+
"agnes_delta_attention",
|
| 25 |
+
"agnes_delta_attention",
|
| 26 |
+
"agnes_delta_attention",
|
| 27 |
+
"agnes_global_attention",
|
| 28 |
+
"agnes_delta_attention",
|
| 29 |
+
"agnes_delta_attention",
|
| 30 |
+
"agnes_delta_attention",
|
| 31 |
+
"agnes_global_attention",
|
| 32 |
+
"agnes_delta_attention",
|
| 33 |
+
"agnes_delta_attention",
|
| 34 |
+
"agnes_delta_attention",
|
| 35 |
+
"agnes_global_attention",
|
| 36 |
+
"agnes_delta_attention",
|
| 37 |
+
"agnes_delta_attention",
|
| 38 |
+
"agnes_delta_attention",
|
| 39 |
+
"agnes_global_attention",
|
| 40 |
+
"agnes_delta_attention",
|
| 41 |
+
"agnes_delta_attention",
|
| 42 |
+
"agnes_delta_attention",
|
| 43 |
+
"agnes_global_attention",
|
| 44 |
+
"agnes_delta_attention",
|
| 45 |
+
"agnes_delta_attention",
|
| 46 |
+
"agnes_delta_attention",
|
| 47 |
+
"agnes_global_attention",
|
| 48 |
+
"agnes_delta_attention",
|
| 49 |
+
"agnes_delta_attention",
|
| 50 |
+
"agnes_delta_attention",
|
| 51 |
+
"agnes_global_attention",
|
| 52 |
+
"agnes_delta_attention",
|
| 53 |
+
"agnes_delta_attention",
|
| 54 |
+
"agnes_delta_attention",
|
| 55 |
+
"agnes_global_attention",
|
| 56 |
+
"agnes_delta_attention",
|
| 57 |
+
"agnes_delta_attention",
|
| 58 |
+
"agnes_delta_attention",
|
| 59 |
+
"agnes_global_attention",
|
| 60 |
+
"agnes_delta_attention",
|
| 61 |
+
"agnes_delta_attention",
|
| 62 |
+
"agnes_delta_attention",
|
| 63 |
+
"agnes_global_attention",
|
| 64 |
+
"agnes_delta_attention",
|
| 65 |
+
"agnes_delta_attention",
|
| 66 |
+
"agnes_delta_attention",
|
| 67 |
+
"agnes_global_attention",
|
| 68 |
+
"agnes_delta_attention",
|
| 69 |
+
"agnes_delta_attention",
|
| 70 |
+
"agnes_delta_attention",
|
| 71 |
+
"agnes_global_attention",
|
| 72 |
+
"agnes_delta_attention",
|
| 73 |
+
"agnes_delta_attention",
|
| 74 |
+
"agnes_delta_attention",
|
| 75 |
+
"agnes_global_attention",
|
| 76 |
+
"agnes_delta_attention",
|
| 77 |
+
"agnes_delta_attention",
|
| 78 |
+
"agnes_delta_attention",
|
| 79 |
+
"agnes_global_attention",
|
| 80 |
+
"agnes_delta_attention",
|
| 81 |
+
"agnes_delta_attention",
|
| 82 |
+
"agnes_delta_attention",
|
| 83 |
+
"agnes_global_attention",
|
| 84 |
+
"agnes_delta_attention",
|
| 85 |
+
"agnes_delta_attention",
|
| 86 |
+
"agnes_delta_attention",
|
| 87 |
+
"agnes_global_attention",
|
| 88 |
+
"agnes_delta_attention",
|
| 89 |
+
"agnes_delta_attention",
|
| 90 |
+
"agnes_delta_attention",
|
| 91 |
+
"agnes_global_attention"
|
| 92 |
+
],
|
| 93 |
+
"global_attention_interval": 4,
|
| 94 |
+
"num_attention_heads": 24,
|
| 95 |
+
"num_key_value_heads": 4,
|
| 96 |
+
"head_dim": 256,
|
| 97 |
+
"attention_bias": false,
|
| 98 |
+
"attention_dropout": 0.0,
|
| 99 |
+
"attn_output_gate": true,
|
| 100 |
+
"partial_rotary_factor": 0.25,
|
| 101 |
+
"linear_num_key_heads": 16,
|
| 102 |
+
"linear_num_value_heads": 48,
|
| 103 |
+
"linear_key_head_dim": 128,
|
| 104 |
+
"linear_value_head_dim": 128,
|
| 105 |
+
"linear_conv_kernel_dim": 4,
|
| 106 |
+
"output_gate_type": "swish",
|
| 107 |
+
"mamba_ssm_dtype": "float32",
|
| 108 |
+
"hidden_act": "silu",
|
| 109 |
+
"rms_norm_eps": 1e-06,
|
| 110 |
+
"initializer_range": 0.02,
|
| 111 |
+
"rope_parameters": {
|
| 112 |
+
"mrope_interleaved": true,
|
| 113 |
+
"mrope_section": [
|
| 114 |
+
11,
|
| 115 |
+
11,
|
| 116 |
+
10
|
| 117 |
+
],
|
| 118 |
+
"partial_rotary_factor": 0.25,
|
| 119 |
+
"rope_theta": 10000000,
|
| 120 |
+
"rope_type": "default"
|
| 121 |
+
},
|
| 122 |
+
"max_position_embeddings": 262144,
|
| 123 |
+
"mtp_num_hidden_layers": 1,
|
| 124 |
+
"mtp_use_dedicated_embeddings": false,
|
| 125 |
+
"bos_token_id": 248044,
|
| 126 |
+
"eos_token_id": 248044,
|
| 127 |
+
"pad_token_id": null,
|
| 128 |
+
"tie_word_embeddings": false,
|
| 129 |
+
"use_cache": true,
|
| 130 |
+
"dtype": "bfloat16",
|
| 131 |
+
"agnes_original_intermediate_size": 17408,
|
| 132 |
+
"agnes_original_parallel_ffn_intermediate_size": 2048
|
| 133 |
+
},
|
| 134 |
+
"vision_config": {
|
| 135 |
+
"model_type": "agnes_vision",
|
| 136 |
+
"depth": 27,
|
| 137 |
+
"hidden_size": 1152,
|
| 138 |
+
"intermediate_size": 4304,
|
| 139 |
+
"num_heads": 16,
|
| 140 |
+
"out_hidden_size": 5120,
|
| 141 |
+
"patch_size": 16,
|
| 142 |
+
"spatial_merge_size": 2,
|
| 143 |
+
"temporal_patch_size": 2,
|
| 144 |
+
"in_channels": 3,
|
| 145 |
+
"num_position_embeddings": 2304,
|
| 146 |
+
"deepstack_visual_indexes": [],
|
| 147 |
+
"hidden_act": "gelu_pytorch_tanh",
|
| 148 |
+
"initializer_range": 0.02
|
| 149 |
+
},
|
| 150 |
+
"image_token_id": 248056,
|
| 151 |
+
"video_token_id": 248057,
|
| 152 |
+
"vision_start_token_id": 248053,
|
| 153 |
+
"vision_end_token_id": 248054,
|
| 154 |
+
"tie_word_embeddings": false,
|
| 155 |
+
"quantization_config": {
|
| 156 |
+
"quant_method": "fp8",
|
| 157 |
+
"fmt": "e4m3",
|
| 158 |
+
"activation_scheme": "dynamic",
|
| 159 |
+
"weight_block_size": [
|
| 160 |
+
128,
|
| 161 |
+
128
|
| 162 |
+
],
|
| 163 |
+
"modules_to_not_convert": [
|
| 164 |
+
"lm_head",
|
| 165 |
+
"model.language_model.layers.0.delta_attn",
|
| 166 |
+
"model.language_model.layers.0.linear_attn",
|
| 167 |
+
"model.language_model.layers.1.delta_attn",
|
| 168 |
+
"model.language_model.layers.1.linear_attn",
|
| 169 |
+
"model.language_model.layers.10.delta_attn",
|
| 170 |
+
"model.language_model.layers.10.linear_attn",
|
| 171 |
+
"model.language_model.layers.11.delta_attn",
|
| 172 |
+
"model.language_model.layers.11.linear_attn",
|
| 173 |
+
"model.language_model.layers.12.delta_attn",
|
| 174 |
+
"model.language_model.layers.12.linear_attn",
|
| 175 |
+
"model.language_model.layers.13.delta_attn",
|
| 176 |
+
"model.language_model.layers.13.linear_attn",
|
| 177 |
+
"model.language_model.layers.14.delta_attn",
|
| 178 |
+
"model.language_model.layers.14.linear_attn",
|
| 179 |
+
"model.language_model.layers.15.delta_attn",
|
| 180 |
+
"model.language_model.layers.15.linear_attn",
|
| 181 |
+
"model.language_model.layers.16.delta_attn",
|
| 182 |
+
"model.language_model.layers.16.linear_attn",
|
| 183 |
+
"model.language_model.layers.17.delta_attn",
|
| 184 |
+
"model.language_model.layers.17.linear_attn",
|
| 185 |
+
"model.language_model.layers.18.delta_attn",
|
| 186 |
+
"model.language_model.layers.18.linear_attn",
|
| 187 |
+
"model.language_model.layers.19.delta_attn",
|
| 188 |
+
"model.language_model.layers.19.linear_attn",
|
| 189 |
+
"model.language_model.layers.2.delta_attn",
|
| 190 |
+
"model.language_model.layers.2.linear_attn",
|
| 191 |
+
"model.language_model.layers.20.delta_attn",
|
| 192 |
+
"model.language_model.layers.20.linear_attn",
|
| 193 |
+
"model.language_model.layers.21.delta_attn",
|
| 194 |
+
"model.language_model.layers.21.linear_attn",
|
| 195 |
+
"model.language_model.layers.22.delta_attn",
|
| 196 |
+
"model.language_model.layers.22.linear_attn",
|
| 197 |
+
"model.language_model.layers.23.delta_attn",
|
| 198 |
+
"model.language_model.layers.23.linear_attn",
|
| 199 |
+
"model.language_model.layers.24.delta_attn",
|
| 200 |
+
"model.language_model.layers.24.linear_attn",
|
| 201 |
+
"model.language_model.layers.25.delta_attn",
|
| 202 |
+
"model.language_model.layers.25.linear_attn",
|
| 203 |
+
"model.language_model.layers.26.delta_attn",
|
| 204 |
+
"model.language_model.layers.26.linear_attn",
|
| 205 |
+
"model.language_model.layers.27.delta_attn",
|
| 206 |
+
"model.language_model.layers.27.linear_attn",
|
| 207 |
+
"model.language_model.layers.28.delta_attn",
|
| 208 |
+
"model.language_model.layers.28.linear_attn",
|
| 209 |
+
"model.language_model.layers.29.delta_attn",
|
| 210 |
+
"model.language_model.layers.29.linear_attn",
|
| 211 |
+
"model.language_model.layers.3.delta_attn",
|
| 212 |
+
"model.language_model.layers.3.linear_attn",
|
| 213 |
+
"model.language_model.layers.30.delta_attn",
|
| 214 |
+
"model.language_model.layers.30.linear_attn",
|
| 215 |
+
"model.language_model.layers.31.delta_attn",
|
| 216 |
+
"model.language_model.layers.31.linear_attn",
|
| 217 |
+
"model.language_model.layers.32.delta_attn",
|
| 218 |
+
"model.language_model.layers.32.linear_attn",
|
| 219 |
+
"model.language_model.layers.33.delta_attn",
|
| 220 |
+
"model.language_model.layers.33.linear_attn",
|
| 221 |
+
"model.language_model.layers.34.delta_attn",
|
| 222 |
+
"model.language_model.layers.34.linear_attn",
|
| 223 |
+
"model.language_model.layers.35.delta_attn",
|
| 224 |
+
"model.language_model.layers.35.linear_attn",
|
| 225 |
+
"model.language_model.layers.36.delta_attn",
|
| 226 |
+
"model.language_model.layers.36.linear_attn",
|
| 227 |
+
"model.language_model.layers.37.delta_attn",
|
| 228 |
+
"model.language_model.layers.37.linear_attn",
|
| 229 |
+
"model.language_model.layers.38.delta_attn",
|
| 230 |
+
"model.language_model.layers.38.linear_attn",
|
| 231 |
+
"model.language_model.layers.39.delta_attn",
|
| 232 |
+
"model.language_model.layers.39.linear_attn",
|
| 233 |
+
"model.language_model.layers.4.delta_attn",
|
| 234 |
+
"model.language_model.layers.4.linear_attn",
|
| 235 |
+
"model.language_model.layers.40.delta_attn",
|
| 236 |
+
"model.language_model.layers.40.linear_attn",
|
| 237 |
+
"model.language_model.layers.41.delta_attn",
|
| 238 |
+
"model.language_model.layers.41.linear_attn",
|
| 239 |
+
"model.language_model.layers.42.delta_attn",
|
| 240 |
+
"model.language_model.layers.42.linear_attn",
|
| 241 |
+
"model.language_model.layers.43.delta_attn",
|
| 242 |
+
"model.language_model.layers.43.linear_attn",
|
| 243 |
+
"model.language_model.layers.44.delta_attn",
|
| 244 |
+
"model.language_model.layers.44.linear_attn",
|
| 245 |
+
"model.language_model.layers.45.delta_attn",
|
| 246 |
+
"model.language_model.layers.45.linear_attn",
|
| 247 |
+
"model.language_model.layers.46.delta_attn",
|
| 248 |
+
"model.language_model.layers.46.linear_attn",
|
| 249 |
+
"model.language_model.layers.47.delta_attn",
|
| 250 |
+
"model.language_model.layers.47.linear_attn",
|
| 251 |
+
"model.language_model.layers.48.delta_attn",
|
| 252 |
+
"model.language_model.layers.48.linear_attn",
|
| 253 |
+
"model.language_model.layers.49.delta_attn",
|
| 254 |
+
"model.language_model.layers.49.linear_attn",
|
| 255 |
+
"model.language_model.layers.5.delta_attn",
|
| 256 |
+
"model.language_model.layers.5.linear_attn",
|
| 257 |
+
"model.language_model.layers.50.delta_attn",
|
| 258 |
+
"model.language_model.layers.50.linear_attn",
|
| 259 |
+
"model.language_model.layers.51.delta_attn",
|
| 260 |
+
"model.language_model.layers.51.linear_attn",
|
| 261 |
+
"model.language_model.layers.52.delta_attn",
|
| 262 |
+
"model.language_model.layers.52.linear_attn",
|
| 263 |
+
"model.language_model.layers.53.delta_attn",
|
| 264 |
+
"model.language_model.layers.53.linear_attn",
|
| 265 |
+
"model.language_model.layers.54.delta_attn",
|
| 266 |
+
"model.language_model.layers.54.linear_attn",
|
| 267 |
+
"model.language_model.layers.55.delta_attn",
|
| 268 |
+
"model.language_model.layers.55.linear_attn",
|
| 269 |
+
"model.language_model.layers.56.delta_attn",
|
| 270 |
+
"model.language_model.layers.56.linear_attn",
|
| 271 |
+
"model.language_model.layers.57.delta_attn",
|
| 272 |
+
"model.language_model.layers.57.linear_attn",
|
| 273 |
+
"model.language_model.layers.58.delta_attn",
|
| 274 |
+
"model.language_model.layers.58.linear_attn",
|
| 275 |
+
"model.language_model.layers.59.delta_attn",
|
| 276 |
+
"model.language_model.layers.59.linear_attn",
|
| 277 |
+
"model.language_model.layers.6.delta_attn",
|
| 278 |
+
"model.language_model.layers.6.linear_attn",
|
| 279 |
+
"model.language_model.layers.60.delta_attn",
|
| 280 |
+
"model.language_model.layers.60.linear_attn",
|
| 281 |
+
"model.language_model.layers.61.delta_attn",
|
| 282 |
+
"model.language_model.layers.61.linear_attn",
|
| 283 |
+
"model.language_model.layers.62.delta_attn",
|
| 284 |
+
"model.language_model.layers.62.linear_attn",
|
| 285 |
+
"model.language_model.layers.63.delta_attn",
|
| 286 |
+
"model.language_model.layers.63.linear_attn",
|
| 287 |
+
"model.language_model.layers.64.delta_attn",
|
| 288 |
+
"model.language_model.layers.64.linear_attn",
|
| 289 |
+
"model.language_model.layers.65.delta_attn",
|
| 290 |
+
"model.language_model.layers.65.linear_attn",
|
| 291 |
+
"model.language_model.layers.66.delta_attn",
|
| 292 |
+
"model.language_model.layers.66.linear_attn",
|
| 293 |
+
"model.language_model.layers.67.delta_attn",
|
| 294 |
+
"model.language_model.layers.67.linear_attn",
|
| 295 |
+
"model.language_model.layers.68.delta_attn",
|
| 296 |
+
"model.language_model.layers.68.linear_attn",
|
| 297 |
+
"model.language_model.layers.69.delta_attn",
|
| 298 |
+
"model.language_model.layers.69.linear_attn",
|
| 299 |
+
"model.language_model.layers.7.delta_attn",
|
| 300 |
+
"model.language_model.layers.7.linear_attn",
|
| 301 |
+
"model.language_model.layers.70.delta_attn",
|
| 302 |
+
"model.language_model.layers.70.linear_attn",
|
| 303 |
+
"model.language_model.layers.71.delta_attn",
|
| 304 |
+
"model.language_model.layers.71.linear_attn",
|
| 305 |
+
"model.language_model.layers.8.delta_attn",
|
| 306 |
+
"model.language_model.layers.8.linear_attn",
|
| 307 |
+
"model.language_model.layers.9.delta_attn",
|
| 308 |
+
"model.language_model.layers.9.linear_attn",
|
| 309 |
+
"model.layers.0.delta_attn",
|
| 310 |
+
"model.layers.0.linear_attn",
|
| 311 |
+
"model.layers.1.delta_attn",
|
| 312 |
+
"model.layers.1.linear_attn",
|
| 313 |
+
"model.layers.10.delta_attn",
|
| 314 |
+
"model.layers.10.linear_attn",
|
| 315 |
+
"model.layers.11.delta_attn",
|
| 316 |
+
"model.layers.11.linear_attn",
|
| 317 |
+
"model.layers.12.delta_attn",
|
| 318 |
+
"model.layers.12.linear_attn",
|
| 319 |
+
"model.layers.13.delta_attn",
|
| 320 |
+
"model.layers.13.linear_attn",
|
| 321 |
+
"model.layers.14.delta_attn",
|
| 322 |
+
"model.layers.14.linear_attn",
|
| 323 |
+
"model.layers.15.delta_attn",
|
| 324 |
+
"model.layers.15.linear_attn",
|
| 325 |
+
"model.layers.16.delta_attn",
|
| 326 |
+
"model.layers.16.linear_attn",
|
| 327 |
+
"model.layers.17.delta_attn",
|
| 328 |
+
"model.layers.17.linear_attn",
|
| 329 |
+
"model.layers.18.delta_attn",
|
| 330 |
+
"model.layers.18.linear_attn",
|
| 331 |
+
"model.layers.19.delta_attn",
|
| 332 |
+
"model.layers.19.linear_attn",
|
| 333 |
+
"model.layers.2.delta_attn",
|
| 334 |
+
"model.layers.2.linear_attn",
|
| 335 |
+
"model.layers.20.delta_attn",
|
| 336 |
+
"model.layers.20.linear_attn",
|
| 337 |
+
"model.layers.21.delta_attn",
|
| 338 |
+
"model.layers.21.linear_attn",
|
| 339 |
+
"model.layers.22.delta_attn",
|
| 340 |
+
"model.layers.22.linear_attn",
|
| 341 |
+
"model.layers.23.delta_attn",
|
| 342 |
+
"model.layers.23.linear_attn",
|
| 343 |
+
"model.layers.24.delta_attn",
|
| 344 |
+
"model.layers.24.linear_attn",
|
| 345 |
+
"model.layers.25.delta_attn",
|
| 346 |
+
"model.layers.25.linear_attn",
|
| 347 |
+
"model.layers.26.delta_attn",
|
| 348 |
+
"model.layers.26.linear_attn",
|
| 349 |
+
"model.layers.27.delta_attn",
|
| 350 |
+
"model.layers.27.linear_attn",
|
| 351 |
+
"model.layers.28.delta_attn",
|
| 352 |
+
"model.layers.28.linear_attn",
|
| 353 |
+
"model.layers.29.delta_attn",
|
| 354 |
+
"model.layers.29.linear_attn",
|
| 355 |
+
"model.layers.3.delta_attn",
|
| 356 |
+
"model.layers.3.linear_attn",
|
| 357 |
+
"model.layers.30.delta_attn",
|
| 358 |
+
"model.layers.30.linear_attn",
|
| 359 |
+
"model.layers.31.delta_attn",
|
| 360 |
+
"model.layers.31.linear_attn",
|
| 361 |
+
"model.layers.32.delta_attn",
|
| 362 |
+
"model.layers.32.linear_attn",
|
| 363 |
+
"model.layers.33.delta_attn",
|
| 364 |
+
"model.layers.33.linear_attn",
|
| 365 |
+
"model.layers.34.delta_attn",
|
| 366 |
+
"model.layers.34.linear_attn",
|
| 367 |
+
"model.layers.35.delta_attn",
|
| 368 |
+
"model.layers.35.linear_attn",
|
| 369 |
+
"model.layers.36.delta_attn",
|
| 370 |
+
"model.layers.36.linear_attn",
|
| 371 |
+
"model.layers.37.delta_attn",
|
| 372 |
+
"model.layers.37.linear_attn",
|
| 373 |
+
"model.layers.38.delta_attn",
|
| 374 |
+
"model.layers.38.linear_attn",
|
| 375 |
+
"model.layers.39.delta_attn",
|
| 376 |
+
"model.layers.39.linear_attn",
|
| 377 |
+
"model.layers.4.delta_attn",
|
| 378 |
+
"model.layers.4.linear_attn",
|
| 379 |
+
"model.layers.40.delta_attn",
|
| 380 |
+
"model.layers.40.linear_attn",
|
| 381 |
+
"model.layers.41.delta_attn",
|
| 382 |
+
"model.layers.41.linear_attn",
|
| 383 |
+
"model.layers.42.delta_attn",
|
| 384 |
+
"model.layers.42.linear_attn",
|
| 385 |
+
"model.layers.43.delta_attn",
|
| 386 |
+
"model.layers.43.linear_attn",
|
| 387 |
+
"model.layers.44.delta_attn",
|
| 388 |
+
"model.layers.44.linear_attn",
|
| 389 |
+
"model.layers.45.delta_attn",
|
| 390 |
+
"model.layers.45.linear_attn",
|
| 391 |
+
"model.layers.46.delta_attn",
|
| 392 |
+
"model.layers.46.linear_attn",
|
| 393 |
+
"model.layers.47.delta_attn",
|
| 394 |
+
"model.layers.47.linear_attn",
|
| 395 |
+
"model.layers.48.delta_attn",
|
| 396 |
+
"model.layers.48.linear_attn",
|
| 397 |
+
"model.layers.49.delta_attn",
|
| 398 |
+
"model.layers.49.linear_attn",
|
| 399 |
+
"model.layers.5.delta_attn",
|
| 400 |
+
"model.layers.5.linear_attn",
|
| 401 |
+
"model.layers.50.delta_attn",
|
| 402 |
+
"model.layers.50.linear_attn",
|
| 403 |
+
"model.layers.51.delta_attn",
|
| 404 |
+
"model.layers.51.linear_attn",
|
| 405 |
+
"model.layers.52.delta_attn",
|
| 406 |
+
"model.layers.52.linear_attn",
|
| 407 |
+
"model.layers.53.delta_attn",
|
| 408 |
+
"model.layers.53.linear_attn",
|
| 409 |
+
"model.layers.54.delta_attn",
|
| 410 |
+
"model.layers.54.linear_attn",
|
| 411 |
+
"model.layers.55.delta_attn",
|
| 412 |
+
"model.layers.55.linear_attn",
|
| 413 |
+
"model.layers.56.delta_attn",
|
| 414 |
+
"model.layers.56.linear_attn",
|
| 415 |
+
"model.layers.57.delta_attn",
|
| 416 |
+
"model.layers.57.linear_attn",
|
| 417 |
+
"model.layers.58.delta_attn",
|
| 418 |
+
"model.layers.58.linear_attn",
|
| 419 |
+
"model.layers.59.delta_attn",
|
| 420 |
+
"model.layers.59.linear_attn",
|
| 421 |
+
"model.layers.6.delta_attn",
|
| 422 |
+
"model.layers.6.linear_attn",
|
| 423 |
+
"model.layers.60.delta_attn",
|
| 424 |
+
"model.layers.60.linear_attn",
|
| 425 |
+
"model.layers.61.delta_attn",
|
| 426 |
+
"model.layers.61.linear_attn",
|
| 427 |
+
"model.layers.62.delta_attn",
|
| 428 |
+
"model.layers.62.linear_attn",
|
| 429 |
+
"model.layers.63.delta_attn",
|
| 430 |
+
"model.layers.63.linear_attn",
|
| 431 |
+
"model.layers.64.delta_attn",
|
| 432 |
+
"model.layers.64.linear_attn",
|
| 433 |
+
"model.layers.65.delta_attn",
|
| 434 |
+
"model.layers.65.linear_attn",
|
| 435 |
+
"model.layers.66.delta_attn",
|
| 436 |
+
"model.layers.66.linear_attn",
|
| 437 |
+
"model.layers.67.delta_attn",
|
| 438 |
+
"model.layers.67.linear_attn",
|
| 439 |
+
"model.layers.68.delta_attn",
|
| 440 |
+
"model.layers.68.linear_attn",
|
| 441 |
+
"model.layers.69.delta_attn",
|
| 442 |
+
"model.layers.69.linear_attn",
|
| 443 |
+
"model.layers.7.delta_attn",
|
| 444 |
+
"model.layers.7.linear_attn",
|
| 445 |
+
"model.layers.70.delta_attn",
|
| 446 |
+
"model.layers.70.linear_attn",
|
| 447 |
+
"model.layers.71.delta_attn",
|
| 448 |
+
"model.layers.71.linear_attn",
|
| 449 |
+
"model.layers.8.delta_attn",
|
| 450 |
+
"model.layers.8.linear_attn",
|
| 451 |
+
"model.layers.9.delta_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Agnes AI. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Agnes 3.0 Flash model configuration."""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from transformers.configuration_utils import PreTrainedConfig
|
| 19 |
+
from transformers.modeling_rope_utils import RopeParameters
|
| 20 |
+
from transformers.utils import auto_docstring
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
LAYER_GLOBAL = "agnes_global_attention"
|
| 24 |
+
LAYER_DELTA = "agnes_delta_attention"
|
| 25 |
+
LAYER_TYPES = (LAYER_GLOBAL, LAYER_DELTA)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@auto_docstring
|
| 29 |
+
@strict
|
| 30 |
+
class AgnesTextConfig(PreTrainedConfig):
|
| 31 |
+
r"""
|
| 32 |
+
linear_num_key_heads (`int`, *optional*, defaults to 16):
|
| 33 |
+
Number of key heads in the delta-rule (recurrent) attention layers.
|
| 34 |
+
linear_num_value_heads (`int`, *optional*, defaults to 32):
|
| 35 |
+
Number of value heads in the delta-rule attention layers.
|
| 36 |
+
linear_key_head_dim (`int`, *optional*, defaults to 128):
|
| 37 |
+
Per-head key width in the delta-rule attention layers.
|
| 38 |
+
linear_value_head_dim (`int`, *optional*, defaults to 128):
|
| 39 |
+
Per-head value width in the delta-rule attention layers.
|
| 40 |
+
linear_conv_kernel_dim (`int`, *optional*, defaults to 4):
|
| 41 |
+
Kernel width of the causal depthwise convolution feeding the delta-rule layers.
|
| 42 |
+
parallel_ffn_intermediate_size (`int`, *optional*, defaults to 0):
|
| 43 |
+
Width of the dense SwiGLU branch that runs beside the main MLP in every
|
| 44 |
+
decoder layer and is summed into the same residual. 0 disables the branch.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
model_type = "agnes_text"
|
| 48 |
+
base_config_key = "text_config"
|
| 49 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 50 |
+
ignore_keys_at_rope_validation = {"mrope_section", "mrope_interleaved"}
|
| 51 |
+
|
| 52 |
+
# core dimensions
|
| 53 |
+
hidden_size: int = 4096
|
| 54 |
+
num_hidden_layers: int = 32
|
| 55 |
+
intermediate_size: int = 12288
|
| 56 |
+
parallel_ffn_intermediate_size: int = 0
|
| 57 |
+
vocab_size: int = 248320
|
| 58 |
+
|
| 59 |
+
# layer plan
|
| 60 |
+
layer_types: list[str] | None = None
|
| 61 |
+
|
| 62 |
+
# global attention
|
| 63 |
+
num_attention_heads: int = 16
|
| 64 |
+
num_key_value_heads: int = 4
|
| 65 |
+
head_dim: int = 256
|
| 66 |
+
attention_bias: bool = False
|
| 67 |
+
attention_dropout: float | int = 0.0
|
| 68 |
+
|
| 69 |
+
# delta-rule attention
|
| 70 |
+
linear_num_key_heads: int = 16
|
| 71 |
+
linear_num_value_heads: int = 32
|
| 72 |
+
linear_key_head_dim: int = 128
|
| 73 |
+
linear_value_head_dim: int = 128
|
| 74 |
+
linear_conv_kernel_dim: int = 4
|
| 75 |
+
|
| 76 |
+
# ffn / norm / init
|
| 77 |
+
hidden_act: str = "silu"
|
| 78 |
+
rms_norm_eps: float = 1e-6
|
| 79 |
+
initializer_range: float = 0.02
|
| 80 |
+
|
| 81 |
+
# positions
|
| 82 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 83 |
+
max_position_embeddings: int = 32768
|
| 84 |
+
|
| 85 |
+
# tokens / runtime
|
| 86 |
+
bos_token_id: int | None = None
|
| 87 |
+
eos_token_id: int | list[int] | None = None
|
| 88 |
+
pad_token_id: int | None = None
|
| 89 |
+
tie_word_embeddings: bool = False
|
| 90 |
+
use_cache: bool = True
|
| 91 |
+
|
| 92 |
+
base_model_pp_plan = {
|
| 93 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
| 94 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
| 95 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
| 96 |
+
}
|
| 97 |
+
base_model_tp_plan = {
|
| 98 |
+
"layers.*.global_attn.q_proj": "colwise",
|
| 99 |
+
"layers.*.global_attn.k_proj": "colwise",
|
| 100 |
+
"layers.*.global_attn.v_proj": "colwise",
|
| 101 |
+
"layers.*.global_attn.o_proj": "rowwise",
|
| 102 |
+
"layers.*.global_attn.q_norm": "replicated_with_grad_allreduce",
|
| 103 |
+
"layers.*.global_attn.k_norm": "replicated_with_grad_allreduce",
|
| 104 |
+
"layers.*.mlp.gate_proj": "colwise",
|
| 105 |
+
"layers.*.mlp.up_proj": "colwise",
|
| 106 |
+
"layers.*.mlp.down_proj": "rowwise",
|
| 107 |
+
"layers.*.mlp.parallel_ffn.gate_proj": "colwise",
|
| 108 |
+
"layers.*.mlp.parallel_ffn.up_proj": "colwise",
|
| 109 |
+
"layers.*.mlp.parallel_ffn.down_proj": "rowwise",
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
def __post_init__(self, **kwargs):
|
| 113 |
+
# rotary embedding covers a quarter of each head unless told otherwise
|
| 114 |
+
kwargs.setdefault("partial_rotary_factor", 0.25)
|
| 115 |
+
if self.layer_types is None:
|
| 116 |
+
period = kwargs.pop("global_attention_interval", kwargs.pop("full_attention_interval", 4))
|
| 117 |
+
plan = []
|
| 118 |
+
for i in range(self.num_hidden_layers):
|
| 119 |
+
is_global = (i + 1) % period == 0
|
| 120 |
+
plan.append(LAYER_GLOBAL if is_global else LAYER_DELTA)
|
| 121 |
+
self.layer_types = plan
|
| 122 |
+
super().__post_init__(**kwargs)
|
| 123 |
+
|
| 124 |
+
def validate_layer_type(self):
|
| 125 |
+
"""The layer plan uses this model's own type names, so the generic
|
| 126 |
+
allow-list in the base class does not apply."""
|
| 127 |
+
plan = self.layer_types
|
| 128 |
+
if plan is None:
|
| 129 |
+
return
|
| 130 |
+
unknown = sorted({t for t in plan if t not in LAYER_TYPES})
|
| 131 |
+
if unknown:
|
| 132 |
+
raise ValueError(f"`layer_types` entries must be in {LAYER_TYPES}, got {unknown}")
|
| 133 |
+
if self.num_hidden_layers is not None and self.num_hidden_layers != len(plan):
|
| 134 |
+
raise ValueError(
|
| 135 |
+
f"`num_hidden_layers` ({self.num_hidden_layers}) must equal the number of `layer_types` ({len(plan)})"
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@auto_docstring
|
| 140 |
+
@strict
|
| 141 |
+
class AgnesVisionConfig(PreTrainedConfig):
|
| 142 |
+
r"""
|
| 143 |
+
out_hidden_size (`int`, *optional*, defaults to 3584):
|
| 144 |
+
Width of the merged visual tokens handed to the language model.
|
| 145 |
+
num_position_embeddings (`int`, *optional*, defaults to 2304):
|
| 146 |
+
Size of the learned 2-D position table (a square grid, side = sqrt of this).
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
model_type = "agnes_vision"
|
| 150 |
+
base_config_key = "vision_config"
|
| 151 |
+
|
| 152 |
+
depth: int = 27
|
| 153 |
+
hidden_size: int = 1152
|
| 154 |
+
intermediate_size: int = 4304
|
| 155 |
+
num_heads: int = 16
|
| 156 |
+
out_hidden_size: int = 3584
|
| 157 |
+
patch_size: int | list[int] | tuple[int, int] = 16
|
| 158 |
+
spatial_merge_size: int = 2
|
| 159 |
+
temporal_patch_size: int | list[int] | tuple[int, int] = 2
|
| 160 |
+
in_channels: int = 3
|
| 161 |
+
num_position_embeddings: int = 2304
|
| 162 |
+
hidden_act: str = "gelu_pytorch_tanh"
|
| 163 |
+
initializer_range: float = 0.02
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@auto_docstring
|
| 167 |
+
@strict
|
| 168 |
+
class AgnesConfig(PreTrainedConfig):
|
| 169 |
+
r"""
|
| 170 |
+
Example:
|
| 171 |
+
|
| 172 |
+
```python
|
| 173 |
+
>>> from transformers import AutoConfig
|
| 174 |
+
|
| 175 |
+
>>> configuration = AutoConfig.from_pretrained("<model dir>", trust_remote_code=True)
|
| 176 |
+
>>> configuration.text_config.num_hidden_layers
|
| 177 |
+
72
|
| 178 |
+
```"""
|
| 179 |
+
|
| 180 |
+
model_type = "agnes"
|
| 181 |
+
sub_configs = {"text_config": AgnesTextConfig, "vision_config": AgnesVisionConfig}
|
| 182 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 183 |
+
|
| 184 |
+
text_config: dict | PreTrainedConfig | None = None
|
| 185 |
+
vision_config: dict | PreTrainedConfig | None = None
|
| 186 |
+
|
| 187 |
+
image_token_id: int = 248056
|
| 188 |
+
video_token_id: int = 248057
|
| 189 |
+
vision_start_token_id: int = 248053
|
| 190 |
+
vision_end_token_id: int = 248054
|
| 191 |
+
tie_word_embeddings: bool = False
|
| 192 |
+
|
| 193 |
+
def __post_init__(self, **kwargs):
|
| 194 |
+
for key, cls in self.sub_configs.items():
|
| 195 |
+
value = getattr(self, key)
|
| 196 |
+
if isinstance(value, dict):
|
| 197 |
+
setattr(self, key, cls(**value))
|
| 198 |
+
elif value is None:
|
| 199 |
+
setattr(self, key, cls())
|
| 200 |
+
super().__post_init__(**kwargs)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
__all__ = ["AgnesConfig", "AgnesTextConfig", "AgnesVisionConfig", "LAYER_GLOBAL", "LAYER_DELTA", "LAYER_TYPES"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 248044,
|
| 3 |
+
"do_sample": true,
|
| 4 |
+
"eos_token_id": [
|
| 5 |
+
248046,
|
| 6 |
+
248044
|
| 7 |
+
],
|
| 8 |
+
"pad_token_id": 248044,
|
| 9 |
+
"temperature": 1.0,
|
| 10 |
+
"top_k": 20,
|
| 11 |
+
"top_p": 0.95
|
| 12 |
+
}
|
image_processing_agnes.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Agnes AI. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Image processor for Agnes 3.0 Flash: dynamic-resolution patching."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
from collections.abc import Iterable
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from torchvision.transforms.v2 import functional as tvF
|
| 21 |
+
|
| 22 |
+
from transformers.image_processing_backends import TorchvisionBackend
|
| 23 |
+
from transformers.image_processing_utils import BatchFeature
|
| 24 |
+
from transformers.image_transforms import group_images_by_shape, reorder_images
|
| 25 |
+
from transformers.image_utils import ImageInput, PILImageResampling, SizeDict
|
| 26 |
+
from transformers.processing_utils import ImagesKwargs, Unpack
|
| 27 |
+
from transformers.utils import TensorType, auto_docstring
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class AgnesImageProcessorKwargs(ImagesKwargs, total=False):
|
| 31 |
+
r"""
|
| 32 |
+
min_pixels (`int`, *optional*, defaults to `256 * 256`):
|
| 33 |
+
Lower bound on the pixel count after resizing.
|
| 34 |
+
max_pixels (`int`, *optional*, defaults to `4096 * 4096`):
|
| 35 |
+
Upper bound on the pixel count after resizing.
|
| 36 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 37 |
+
Spatial patch size of the vision tower.
|
| 38 |
+
temporal_patch_size (`int`, *optional*, defaults to 2):
|
| 39 |
+
Temporal patch size of the vision tower (images are duplicated to fill it).
|
| 40 |
+
merge_size (`int`, *optional*, defaults to 2):
|
| 41 |
+
Side of the patch square merged into one language-model token.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
min_pixels: int
|
| 45 |
+
max_pixels: int
|
| 46 |
+
patch_size: int
|
| 47 |
+
temporal_patch_size: int
|
| 48 |
+
merge_size: int
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def fit_to_grid(height: int, width: int, factor: int = 32, min_pixels: int = 256 * 256, max_pixels: int = 4096 * 4096):
|
| 52 |
+
"""Pick a (height, width) that is a multiple of `factor` on both sides,
|
| 53 |
+
keeps the pixel count inside [min_pixels, max_pixels] and stays as close
|
| 54 |
+
as possible to the original aspect ratio."""
|
| 55 |
+
if max(height, width) / min(height, width) > 200:
|
| 56 |
+
raise ValueError(f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}")
|
| 57 |
+
h = round(height / factor) * factor
|
| 58 |
+
w = round(width / factor) * factor
|
| 59 |
+
if h * w > max_pixels:
|
| 60 |
+
scale = math.sqrt((height * width) / max_pixels)
|
| 61 |
+
h = max(factor, math.floor(height / scale / factor) * factor)
|
| 62 |
+
w = max(factor, math.floor(width / scale / factor) * factor)
|
| 63 |
+
elif h * w < min_pixels:
|
| 64 |
+
scale = math.sqrt(min_pixels / (height * width))
|
| 65 |
+
h = math.ceil(height * scale / factor) * factor
|
| 66 |
+
w = math.ceil(width * scale / factor) * factor
|
| 67 |
+
return h, w
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@auto_docstring
|
| 71 |
+
class AgnesImageProcessor(TorchvisionBackend):
|
| 72 |
+
do_resize = True
|
| 73 |
+
resample = PILImageResampling.BICUBIC
|
| 74 |
+
size = {"shortest_edge": 256 * 256, "longest_edge": 4096 * 4096}
|
| 75 |
+
default_to_square = False
|
| 76 |
+
do_rescale = True
|
| 77 |
+
do_normalize = True
|
| 78 |
+
image_mean = [0.5, 0.5, 0.5]
|
| 79 |
+
image_std = [0.5, 0.5, 0.5]
|
| 80 |
+
do_convert_rgb = True
|
| 81 |
+
patch_size = 16
|
| 82 |
+
temporal_patch_size = 2
|
| 83 |
+
merge_size = 2
|
| 84 |
+
valid_kwargs = AgnesImageProcessorKwargs
|
| 85 |
+
model_input_names = ["pixel_values", "image_grid_thw"]
|
| 86 |
+
|
| 87 |
+
def __init__(self, **kwargs: Unpack[AgnesImageProcessorKwargs]):
|
| 88 |
+
size = kwargs.pop("size", None)
|
| 89 |
+
min_pixels = kwargs.pop("min_pixels", None)
|
| 90 |
+
max_pixels = kwargs.pop("max_pixels", None)
|
| 91 |
+
size = self.size if size is None else size
|
| 92 |
+
# min_pixels / max_pixels are the older spelling of the two size keys
|
| 93 |
+
if min_pixels is not None:
|
| 94 |
+
size["shortest_edge"] = min_pixels
|
| 95 |
+
size.pop("min_pixels", None)
|
| 96 |
+
if max_pixels is not None:
|
| 97 |
+
size["longest_edge"] = max_pixels
|
| 98 |
+
size.pop("max_pixels", None)
|
| 99 |
+
if "shortest_edge" not in size or "longest_edge" not in size:
|
| 100 |
+
raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
|
| 101 |
+
super().__init__(size=size, **kwargs)
|
| 102 |
+
|
| 103 |
+
def _standardize_kwargs(
|
| 104 |
+
self,
|
| 105 |
+
size: int | Iterable[int] | dict[str, int] | SizeDict | None = None,
|
| 106 |
+
min_pixels: int | None = None,
|
| 107 |
+
max_pixels: int | None = None,
|
| 108 |
+
**kwargs,
|
| 109 |
+
) -> dict:
|
| 110 |
+
if min_pixels is not None and max_pixels is not None:
|
| 111 |
+
size = SizeDict(shortest_edge=min_pixels, longest_edge=max_pixels)
|
| 112 |
+
kwargs = super()._standardize_kwargs(size=size, **kwargs)
|
| 113 |
+
size = kwargs.get("size", self.size)
|
| 114 |
+
if not size.shortest_edge or not size.longest_edge:
|
| 115 |
+
raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
|
| 116 |
+
return kwargs
|
| 117 |
+
|
| 118 |
+
@auto_docstring
|
| 119 |
+
def preprocess(self, images: ImageInput, **kwargs: Unpack[AgnesImageProcessorKwargs]) -> BatchFeature:
|
| 120 |
+
return super().preprocess(images, **kwargs)
|
| 121 |
+
|
| 122 |
+
def _preprocess(
|
| 123 |
+
self,
|
| 124 |
+
images: list["torch.Tensor"],
|
| 125 |
+
do_resize: bool,
|
| 126 |
+
size: SizeDict,
|
| 127 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
|
| 128 |
+
do_rescale: bool,
|
| 129 |
+
rescale_factor: float,
|
| 130 |
+
do_normalize: bool,
|
| 131 |
+
image_mean: float | list[float] | None,
|
| 132 |
+
image_std: float | list[float] | None,
|
| 133 |
+
patch_size: int,
|
| 134 |
+
temporal_patch_size: int,
|
| 135 |
+
merge_size: int,
|
| 136 |
+
disable_grouping: bool | None,
|
| 137 |
+
return_tensors: str | TensorType | None,
|
| 138 |
+
**kwargs,
|
| 139 |
+
) -> BatchFeature:
|
| 140 |
+
# 1. resize, batched per input shape
|
| 141 |
+
by_shape, order = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 142 |
+
resized = {}
|
| 143 |
+
for shape, batch in by_shape.items():
|
| 144 |
+
height, width = batch.shape[-2:]
|
| 145 |
+
if do_resize:
|
| 146 |
+
new_h, new_w = fit_to_grid(
|
| 147 |
+
height, width, factor=patch_size * merge_size,
|
| 148 |
+
min_pixels=size.shortest_edge, max_pixels=size.longest_edge,
|
| 149 |
+
)
|
| 150 |
+
batch = self.resize(image=batch, size=SizeDict(height=new_h, width=new_w), resample=resample)
|
| 151 |
+
resized[shape] = batch
|
| 152 |
+
images = reorder_images(resized, order)
|
| 153 |
+
|
| 154 |
+
# 2. normalise and cut into merge-ordered patches, batched per resized shape
|
| 155 |
+
by_shape, order = group_images_by_shape(images, disable_grouping=disable_grouping)
|
| 156 |
+
flat = {}
|
| 157 |
+
grids = {}
|
| 158 |
+
for shape, batch in by_shape.items():
|
| 159 |
+
new_h, new_w = batch.shape[-2:]
|
| 160 |
+
px = self.rescale_and_normalize(batch, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
|
| 161 |
+
n, c = px.shape[:2]
|
| 162 |
+
gh, gw = new_h // patch_size, new_w // patch_size
|
| 163 |
+
px = px.reshape(n, c, gh // merge_size, merge_size, patch_size, gw // merge_size, merge_size, patch_size)
|
| 164 |
+
# -> [n, gh/merge, gw/merge, merge, merge, c, patch, patch]: patches of one
|
| 165 |
+
# merge square end up adjacent in the flattened sequence
|
| 166 |
+
px = px.permute(0, 2, 5, 3, 6, 1, 4, 7)
|
| 167 |
+
px = (
|
| 168 |
+
px.unsqueeze(6)
|
| 169 |
+
.expand(-1, -1, -1, -1, -1, -1, temporal_patch_size, -1, -1)
|
| 170 |
+
.reshape(n, gh * gw, c * temporal_patch_size * patch_size * patch_size)
|
| 171 |
+
)
|
| 172 |
+
flat[shape] = px
|
| 173 |
+
grids[shape] = [[1, gh, gw]] * n
|
| 174 |
+
|
| 175 |
+
pixel_values = torch.cat(reorder_images(flat, order), dim=0)
|
| 176 |
+
image_grid_thw = torch.tensor(reorder_images(grids, order), dtype=torch.long)
|
| 177 |
+
return BatchFeature(data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw}, tensor_type=return_tensors)
|
| 178 |
+
|
| 179 |
+
def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
|
| 180 |
+
"""Number of vision patches an image of this size produces (used by
|
| 181 |
+
serving engines to lay out placeholders without running the processor)."""
|
| 182 |
+
min_pixels = images_kwargs["min_pixels"] if "min_pixels" in images_kwargs else self.size["shortest_edge"]
|
| 183 |
+
max_pixels = images_kwargs["max_pixels"] if "max_pixels" in images_kwargs else self.size["longest_edge"]
|
| 184 |
+
patch_size = images_kwargs.get("patch_size", self.patch_size)
|
| 185 |
+
merge_size = images_kwargs.get("merge_size", self.merge_size)
|
| 186 |
+
new_h, new_w = fit_to_grid(height, width, patch_size * merge_size, min_pixels=min_pixels, max_pixels=max_pixels)
|
| 187 |
+
return (new_h // patch_size) * (new_w // patch_size)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
__all__ = ["AgnesImageProcessor"]
|
inference_manifest.json
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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b2f796219e87dcf35d0ab4"
|
| 7 |
+
},
|
| 8 |
+
{
|
| 9 |
+
"name": "chat_template.jinja",
|
| 10 |
+
"size": 8952,
|
| 11 |
+
"sha256": "c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041"
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"name": "config.json",
|
| 15 |
+
"size": 17515,
|
| 16 |
+
"sha256": "3d657d45e1d0b619e97be53ef426a372364854e00bde11cafa2b31eee8026063"
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"name": "configuration_agnes.py",
|
| 20 |
+
"size": 7516,
|
| 21 |
+
"sha256": "b504c8a6052933ef46f5e9df0d52a09a45b6df41f1f3a2168bfdb4718d7c2342"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"name": "generation_config.json",
|
| 25 |
+
"size": 202,
|
| 26 |
+
"sha256": "e70c136c1b78ddc1fb0905bac8e733a4dc448d4f852a5dd75143fffc70be550e"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"name": "image_processing_agnes.py",
|
| 30 |
+
"size": 8700,
|
| 31 |
+
"sha256": "e7c131d219cd1f8f80730c5b650c32ce107a76f3a5168e12b4a35f754f5253ca"
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"name": "merges.txt",
|
| 35 |
+
"size": 3353259,
|
| 36 |
+
"sha256": "a9d356d7bdf1ef4949e3e748e95b8e10ad9d4e2e838eddc38a0a7b6b94d1db8d"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"name": "model-00001.safetensors",
|
| 40 |
+
"size": 2542796928,
|
| 41 |
+
"sha256": "54d83c1d36631de231876217a8e0c2483eccee8746369a482b79442bdfc5d958"
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"name": "model-00002.safetensors",
|
| 45 |
+
"size": 4439047312,
|
| 46 |
+
"sha256": "e63715ddcf2d7de72a3561034d9f791c3dae259f73fc5e8bd49e47a3108940a6"
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"name": "model-00003.safetensors",
|
| 50 |
+
"size": 4422852680,
|
| 51 |
+
"sha256": "b41468b596836b51cfa561687154e9dd4a6f54a77ab5b87e65f7bf2f6d3e4312"
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"name": "model-00004.safetensors",
|
| 55 |
+
"size": 4422852680,
|
| 56 |
+
"sha256": "2ca193e4db478721f503d35a8588b065b5ada8c1f553b7256082e5de8869ebd6"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"name": "model-00005.safetensors",
|
| 60 |
+
"size": 4495263520,
|
| 61 |
+
"sha256": "05814cf21a497469ea0c2597c8bf13575447148b25374185016ac13b02c3447b"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"name": "model-00006.safetensors",
|
| 65 |
+
"size": 4422852672,
|
| 66 |
+
"sha256": "fe0c5a9a1301686cbca7e7940ea8c1c6f406c6444c3077dab87891b7425c1f5b"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"name": "model-00007.safetensors",
|
| 70 |
+
"size": 4459566912,
|
| 71 |
+
"sha256": "2b2c237285b8f059de1cd8efd15683d4fae3df7f3dfbb3b1a46d15143645720a"
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"name": "model-00008.safetensors",
|
| 75 |
+
"size": 4459576904,
|
| 76 |
+
"sha256": "ea8005e19a879b173fda7ba9029a459f0e0f29099921cd0c51f2b11f2af31f18"
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"name": "model-00009.safetensors",
|
| 80 |
+
"size": 4417634288,
|
| 81 |
+
"sha256": "7765ac98fc25e68b7a46052fffe35cf4d0fe6ab3337ba2eb489cfc678295fe03"
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"name": "model-00010.safetensors",
|
| 85 |
+
"size": 4343701536,
|
| 86 |
+
"sha256": "9c0f78f02d06afc1e68e54f41a71f628e5965ba58a7c7c0b1877030d0dc35791"
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"name": "model-00011.safetensors",
|
| 90 |
+
"size": 356557464,
|
| 91 |
+
"sha256": "116fa885398765cc312c0cf99fe92b533a3a7924d381193757adf2d67f4ac888"
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"name": "model.safetensors.index.json",
|
| 95 |
+
"size": 138501,
|
| 96 |
+
"sha256": "eaf5133c51efdf9fac4bcc06f75887a13a47719740ce7bc81f185b6caa7c93d7"
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"name": "modeling_agnes.py",
|
| 100 |
+
"size": 70576,
|
| 101 |
+
"sha256": "21eb5cf1c2f6686253000937c668030934bebb53cf1ce423ccd4c2eb47a074c5"
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"name": "preprocessor_config.json",
|
| 105 |
+
"size": 476,
|
| 106 |
+
"sha256": "362459e4ba0bcb92bfdfb2a592063368976106eb10c5e9acdb946d727c08f4c8"
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"name": "processing_agnes.py",
|
| 110 |
+
"size": 5849,
|
| 111 |
+
"sha256": "98316a130c4f67e4d5bef9ebe80aabf908666cdf989ee7e5e5949c071f26ffdd"
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"name": "serve.sh",
|
| 115 |
+
"size": 1481,
|
| 116 |
+
"sha256": "1a9f4db808b9f0ddc9e04b6408a81ff13924e2d39a7daa34076149170e4407bd"
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"name": "sglang_patch/agnes_sglang_config.py",
|
| 120 |
+
"size": 3174,
|
| 121 |
+
"sha256": "959819231c778f901d97cd8d2c1d4379ea5a5497486b1df156fb9239a1873a15"
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"name": "sglang_patch/apply_patch.py",
|
| 125 |
+
"size": 4832,
|
| 126 |
+
"sha256": "97c3524bb895b9f2159c8d68467767797ead9ae9458407a667c55e7c8657d8e6"
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"name": "sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/configs/agnes.py",
|
| 130 |
+
"size": 3174,
|
| 131 |
+
"sha256": "959819231c778f901d97cd8d2c1d4379ea5a5497486b1df156fb9239a1873a15"
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"name": "sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/models/qwen3_5.py",
|
| 135 |
+
"size": 110335,
|
| 136 |
+
"sha256": "a489dcb3dc15e0b4c7a48ace8b1a9e2055dc49bc92fd59cc937cdb6648735c2d"
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"name": "sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/utils/hf_transformers/common.py",
|
| 140 |
+
"size": 25576,
|
| 141 |
+
"sha256": "62ab258bf96c1b586c42b41c6ff43e96549f902f8feddf84bd23b8921f01d575"
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"name": "sglang_patch/v0.5.19/sglang/srt/configs/agnes.py",
|
| 145 |
+
"size": 3174,
|
| 146 |
+
"sha256": "959819231c778f901d97cd8d2c1d4379ea5a5497486b1df156fb9239a1873a15"
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"name": "sglang_patch/v0.5.19/sglang/srt/models/qwen3_5.py",
|
| 150 |
+
"size": 109787,
|
| 151 |
+
"sha256": "dc61db0d04f5b3c56a13276f35148229e3dee85c5eacbe7220af09393be9ed7f"
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"name": "sglang_patch/v0.5.19/sglang/srt/utils/hf_transformers/common.py",
|
| 155 |
+
"size": 23485,
|
| 156 |
+
"sha256": "6ac72227e51040e22b692821a01bf36555d0b298f735740fece328a1817df9e4"
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"name": "tokenizer.json",
|
| 160 |
+
"size": 9835269,
|
| 161 |
+
"sha256": "f7ffe83fabdd9d1861e1d52e1ebf982a5c8accab07a0e867132d06ec6bdd3894"
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"name": "tokenizer_config.json",
|
| 165 |
+
"size": 18884,
|
| 166 |
+
"sha256": "914f96a0624c33e2d899a042413c957df6082176b6b2990f7c87045b7182263e"
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"name": "video_preprocessor_config.json",
|
| 170 |
+
"size": 460,
|
| 171 |
+
"sha256": "2ec70c5d9e01c6b0c14b882913b6319da78e1efa49037d20b143d59ea37455c1"
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"name": "video_processing_agnes.py",
|
| 175 |
+
"size": 8832,
|
| 176 |
+
"sha256": "b1c1f1849736a823903a7a3eb7f2b57ad81ee15131f65a4ee616ec32b9655b28"
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"name": "vocab.json",
|
| 180 |
+
"size": 6722759,
|
| 181 |
+
"sha256": "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003"
|
| 182 |
+
}
|
| 183 |
+
]
|
| 184 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model-00001.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:54d83c1d36631de231876217a8e0c2483eccee8746369a482b79442bdfc5d958
|
| 3 |
+
size 2542796928
|
model-00002.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e63715ddcf2d7de72a3561034d9f791c3dae259f73fc5e8bd49e47a3108940a6
|
| 3 |
+
size 4439047312
|
model-00003.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b41468b596836b51cfa561687154e9dd4a6f54a77ab5b87e65f7bf2f6d3e4312
|
| 3 |
+
size 4422852680
|
model-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2ca193e4db478721f503d35a8588b065b5ada8c1f553b7256082e5de8869ebd6
|
| 3 |
+
size 4422852680
|
model-00005.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:05814cf21a497469ea0c2597c8bf13575447148b25374185016ac13b02c3447b
|
| 3 |
+
size 4495263520
|
model-00006.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fe0c5a9a1301686cbca7e7940ea8c1c6f406c6444c3077dab87891b7425c1f5b
|
| 3 |
+
size 4422852672
|
model-00007.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b2c237285b8f059de1cd8efd15683d4fae3df7f3dfbb3b1a46d15143645720a
|
| 3 |
+
size 4459566912
|
model-00008.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ea8005e19a879b173fda7ba9029a459f0e0f29099921cd0c51f2b11f2af31f18
|
| 3 |
+
size 4459576904
|
model-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7765ac98fc25e68b7a46052fffe35cf4d0fe6ab3337ba2eb489cfc678295fe03
|
| 3 |
+
size 4417634288
|
model-00010.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c0f78f02d06afc1e68e54f41a71f628e5965ba58a7c7c0b1877030d0dc35791
|
| 3 |
+
size 4343701536
|
model-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:116fa885398765cc312c0cf99fe92b533a3a7924d381193757adf2d67f4ac888
|
| 3 |
+
size 356557464
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_agnes.py
ADDED
|
@@ -0,0 +1,1559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Agnes AI. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Agnes 3.0 Flash.
|
| 15 |
+
|
| 16 |
+
A hybrid decoder: three delta-rule recurrent layers followed by one global
|
| 17 |
+
attention layer, repeated; every layer carries a main SwiGLU MLP plus a
|
| 18 |
+
parallel SwiGLU branch summed into the same residual. A vision tower feeds
|
| 19 |
+
merged patch tokens into the language model through placeholder tokens.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import itertools
|
| 23 |
+
from collections.abc import Callable
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from typing import Any, Optional
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
from torch import nn
|
| 30 |
+
|
| 31 |
+
from transformers import initialization as init
|
| 32 |
+
from transformers.activations import ACT2FN
|
| 33 |
+
from transformers.cache_utils import LAYER_TYPE_CACHE_MAPPING, Cache, DynamicCache, DynamicLayer, LinearAttentionLayer
|
| 34 |
+
from transformers.generation import GenerationMixin
|
| 35 |
+
from transformers.masking_utils import LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING, create_causal_mask
|
| 36 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 37 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 38 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast
|
| 39 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 40 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 41 |
+
from transformers.processing_utils import Unpack
|
| 42 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging, torch_compilable_check
|
| 43 |
+
from transformers.utils.generic import (
|
| 44 |
+
accepts_precomputed_kwargs,
|
| 45 |
+
is_flash_attention_requested,
|
| 46 |
+
maybe_autocast,
|
| 47 |
+
merge_with_config_defaults,
|
| 48 |
+
)
|
| 49 |
+
from transformers.utils.import_utils import is_causal_conv1d_available, is_flash_linear_attention_available
|
| 50 |
+
from transformers.utils.output_capturing import capture_outputs
|
| 51 |
+
from transformers.vision_utils import get_vision_bilinear_indices_and_weights, get_vision_cu_seqlens, get_vision_position_ids
|
| 52 |
+
|
| 53 |
+
from .configuration_agnes import LAYER_DELTA, LAYER_GLOBAL, AgnesConfig, AgnesTextConfig, AgnesVisionConfig
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
logger = logging.get_logger(__name__)
|
| 57 |
+
|
| 58 |
+
# Optional fused kernels. When absent the pure-torch paths below are used;
|
| 59 |
+
# both paths are numerically interchangeable.
|
| 60 |
+
if is_causal_conv1d_available():
|
| 61 |
+
from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
|
| 62 |
+
else:
|
| 63 |
+
causal_conv1d_fn = causal_conv1d_update = None
|
| 64 |
+
|
| 65 |
+
if is_flash_linear_attention_available():
|
| 66 |
+
from fla.modules import FusedRMSNormGated
|
| 67 |
+
from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
|
| 68 |
+
else:
|
| 69 |
+
FusedRMSNormGated = None
|
| 70 |
+
chunk_gated_delta_rule = fused_recurrent_gated_delta_rule = None
|
| 71 |
+
|
| 72 |
+
_FUSED_DELTA_PATH = all((causal_conv1d_fn, causal_conv1d_update, chunk_gated_delta_rule, fused_recurrent_gated_delta_rule))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ---------------------------------------------------------------------------
|
| 76 |
+
# Layer-type plumbing: the cache builds one cache layer per entry of
|
| 77 |
+
# config.layer_types through a registry keyed by type name, and generation
|
| 78 |
+
# picks a mask function the same way. Both are told about this model's two
|
| 79 |
+
# layer types here, at import time.
|
| 80 |
+
# ---------------------------------------------------------------------------
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class AgnesGlobalCacheLayer(DynamicLayer):
|
| 84 |
+
layer_type = LAYER_GLOBAL
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class AgnesDeltaCacheLayer(LinearAttentionLayer):
|
| 88 |
+
layer_type = LAYER_DELTA
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# DynamicLayer subclasses self-register through CacheLayerMixin; the linear-attention
|
| 92 |
+
# base does not share that hook, and an unknown type silently falls back to a plain
|
| 93 |
+
# KV layer, so both entries are written explicitly.
|
| 94 |
+
LAYER_TYPE_CACHE_MAPPING[LAYER_GLOBAL] = AgnesGlobalCacheLayer
|
| 95 |
+
LAYER_TYPE_CACHE_MAPPING[LAYER_DELTA] = AgnesDeltaCacheLayer
|
| 96 |
+
LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING.setdefault(LAYER_GLOBAL, create_causal_mask)
|
| 97 |
+
LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING.setdefault(LAYER_DELTA, create_causal_mask)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ---------------------------------------------------------------------------
|
| 101 |
+
# Normalisation
|
| 102 |
+
# ---------------------------------------------------------------------------
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class _RMSNormFn(torch.autograd.Function):
|
| 106 |
+
"""RMS normalisation with a one-centred scale, y = x / rms(x) * (1 + w).
|
| 107 |
+
|
| 108 |
+
The forward matches the reference op-for-op (fp32 statistics, cast back to
|
| 109 |
+
the input dtype at the end); the backward is written out analytically
|
| 110 |
+
instead of being traced through the forward graph.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
@staticmethod
|
| 114 |
+
def forward(ctx, x, weight, eps):
|
| 115 |
+
xf = x.float()
|
| 116 |
+
inv = torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)
|
| 117 |
+
unit = xf * inv
|
| 118 |
+
out = unit * (1.0 + weight.float())
|
| 119 |
+
ctx.save_for_backward(unit, inv, weight)
|
| 120 |
+
ctx.in_dtype = x.dtype
|
| 121 |
+
return out.type_as(x)
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def backward(ctx, grad_out):
|
| 125 |
+
unit, inv, weight = ctx.saved_tensors
|
| 126 |
+
g = grad_out.float()
|
| 127 |
+
g_unit = g * (1.0 + weight.float())
|
| 128 |
+
grad_x = inv * (g_unit - unit * (g_unit * unit).mean(-1, keepdim=True))
|
| 129 |
+
grad_w = (g * unit).reshape(-1, unit.shape[-1]).sum(0)
|
| 130 |
+
return grad_x.to(ctx.in_dtype), grad_w.to(weight.dtype), None
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class AgnesRMSNorm(nn.Module):
|
| 134 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 135 |
+
super().__init__()
|
| 136 |
+
self.eps = eps
|
| 137 |
+
self.weight = nn.Parameter(torch.zeros(dim))
|
| 138 |
+
|
| 139 |
+
def forward(self, x):
|
| 140 |
+
return _RMSNormFn.apply(x, self.weight, self.eps)
|
| 141 |
+
|
| 142 |
+
def extra_repr(self):
|
| 143 |
+
return f"{tuple(self.weight.shape)}, eps={self.eps}"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class _GatedRMSNormFn(torch.autograd.Function):
|
| 147 |
+
"""RMS normalisation followed by a learned scale and a SiLU gate.
|
| 148 |
+
|
| 149 |
+
Forward order (matters for bit-exactness): fp32 statistics, cast to the
|
| 150 |
+
input dtype, multiply by the weight in that dtype, then multiply by the
|
| 151 |
+
fp32 gate activation and cast back.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
@staticmethod
|
| 155 |
+
def forward(ctx, x, weight, gate, eps):
|
| 156 |
+
in_dtype = x.dtype
|
| 157 |
+
xf = x.to(torch.float32)
|
| 158 |
+
inv = torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)
|
| 159 |
+
unit = xf * inv
|
| 160 |
+
scaled = weight * unit.to(in_dtype)
|
| 161 |
+
gate_f = gate.to(torch.float32)
|
| 162 |
+
act = F.silu(gate_f)
|
| 163 |
+
out = scaled * act
|
| 164 |
+
ctx.save_for_backward(unit, inv, weight, gate_f, scaled)
|
| 165 |
+
ctx.in_dtype = in_dtype
|
| 166 |
+
return out.to(in_dtype)
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def backward(ctx, grad_out):
|
| 170 |
+
unit, inv, weight, gate_f, scaled = ctx.saved_tensors
|
| 171 |
+
g = grad_out.float()
|
| 172 |
+
sig = torch.sigmoid(gate_f)
|
| 173 |
+
act = gate_f * sig
|
| 174 |
+
g_scaled = g * act
|
| 175 |
+
grad_w = (g_scaled * unit).reshape(-1, unit.shape[-1]).sum(0)
|
| 176 |
+
g_unit = g_scaled * weight.float()
|
| 177 |
+
grad_x = inv * (g_unit - unit * (g_unit * unit).mean(-1, keepdim=True))
|
| 178 |
+
grad_gate = g * scaled.float() * (sig * (1.0 + gate_f * (1.0 - sig)))
|
| 179 |
+
return grad_x.to(ctx.in_dtype), grad_w.to(weight.dtype), grad_gate.to(ctx.in_dtype), None
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class AgnesGatedNorm(nn.Module):
|
| 183 |
+
def __init__(self, hidden_size, eps=1e-6, **kwargs):
|
| 184 |
+
super().__init__()
|
| 185 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 186 |
+
self.variance_epsilon = eps
|
| 187 |
+
|
| 188 |
+
def forward(self, hidden_states, gate=None):
|
| 189 |
+
return _GatedRMSNormFn.apply(hidden_states, self.weight, gate, self.variance_epsilon)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# ---------------------------------------------------------------------------
|
| 193 |
+
# Feed-forward
|
| 194 |
+
# ---------------------------------------------------------------------------
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class AgnesMLP(nn.Module):
|
| 198 |
+
"""SwiGLU block. With `parallel_size > 0` a second, narrower SwiGLU runs
|
| 199 |
+
on the same input and its output is added to the main one."""
|
| 200 |
+
|
| 201 |
+
def __init__(self, config, intermediate_size: int, parallel_size: int = 0):
|
| 202 |
+
super().__init__()
|
| 203 |
+
self.config = config
|
| 204 |
+
self.hidden_size = config.hidden_size
|
| 205 |
+
self.intermediate_size = intermediate_size
|
| 206 |
+
self.gate_proj = nn.Linear(self.hidden_size, intermediate_size, bias=False)
|
| 207 |
+
self.up_proj = nn.Linear(self.hidden_size, intermediate_size, bias=False)
|
| 208 |
+
self.down_proj = nn.Linear(intermediate_size, self.hidden_size, bias=False)
|
| 209 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 210 |
+
self.parallel_ffn = AgnesMLP(config, parallel_size) if parallel_size > 0 else None
|
| 211 |
+
|
| 212 |
+
def forward(self, x):
|
| 213 |
+
y = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 214 |
+
if self.parallel_ffn is not None:
|
| 215 |
+
y = y + self.parallel_ffn(x)
|
| 216 |
+
return y
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# ---------------------------------------------------------------------------
|
| 220 |
+
# Rotary position encodings
|
| 221 |
+
# ---------------------------------------------------------------------------
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _swap_halves(x):
|
| 225 |
+
"""(a, b) -> (-b, a) along the last axis."""
|
| 226 |
+
half = x.shape[-1] // 2
|
| 227 |
+
return torch.cat((-x[..., half:], x[..., :half]), dim=-1)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _apply_rope(q, k, cos, sin, unsqueeze_dim=1):
|
| 231 |
+
"""Rotate the leading `cos.shape[-1]` channels of q and k; the rest pass through."""
|
| 232 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 233 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 234 |
+
n_rot = cos.shape[-1]
|
| 235 |
+
q_rot, q_rest = q[..., :n_rot], q[..., n_rot:]
|
| 236 |
+
k_rot, k_rest = k[..., :n_rot], k[..., n_rot:]
|
| 237 |
+
q_rot = (q_rot * cos) + (_swap_halves(q_rot) * sin)
|
| 238 |
+
k_rot = (k_rot * cos) + (_swap_halves(k_rot) * sin)
|
| 239 |
+
return torch.cat([q_rot, q_rest], dim=-1), torch.cat([k_rot, k_rest], dim=-1)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class AgnesRotaryEmbedding(nn.Module):
|
| 243 |
+
"""Three-axis (text / height / width) rotary tables with interleaved sections."""
|
| 244 |
+
|
| 245 |
+
inv_freq: torch.Tensor
|
| 246 |
+
|
| 247 |
+
def __init__(self, config: AgnesTextConfig, device=None):
|
| 248 |
+
super().__init__()
|
| 249 |
+
self.config = config
|
| 250 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 251 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 252 |
+
self.rope_type = config.rope_parameters["rope_type"]
|
| 253 |
+
builder: Callable = self.compute_default_rope_parameters
|
| 254 |
+
if self.rope_type != "default":
|
| 255 |
+
builder = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 256 |
+
inv_freq, self.attention_scaling = builder(config, device)
|
| 257 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 258 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 259 |
+
self.mrope_section = config.rope_parameters.get("mrope_section", [11, 11, 10])
|
| 260 |
+
|
| 261 |
+
@staticmethod
|
| 262 |
+
def compute_default_rope_parameters(
|
| 263 |
+
config: AgnesTextConfig | None = None,
|
| 264 |
+
device: Optional["torch.device"] = None,
|
| 265 |
+
seq_len: int | None = None,
|
| 266 |
+
) -> tuple["torch.Tensor", float]:
|
| 267 |
+
theta = config.rope_parameters["rope_theta"]
|
| 268 |
+
fraction = config.rope_parameters.get("partial_rotary_factor", 1.0)
|
| 269 |
+
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 270 |
+
n_rot = int(head_dim * fraction)
|
| 271 |
+
exponents = torch.arange(0, n_rot, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / n_rot
|
| 272 |
+
inv_freq = 1.0 / (theta**exponents)
|
| 273 |
+
return inv_freq, 1.0
|
| 274 |
+
|
| 275 |
+
@torch.no_grad()
|
| 276 |
+
@dynamic_rope_update
|
| 277 |
+
def forward(self, x, position_ids):
|
| 278 |
+
if position_ids.ndim == 2:
|
| 279 |
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
| 280 |
+
freq_col = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device)
|
| 281 |
+
pos_row = position_ids[:, :, None, :].float()
|
| 282 |
+
dev = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 283 |
+
with maybe_autocast(device_type=dev, enabled=False):
|
| 284 |
+
angles = (freq_col.float() @ pos_row.float()).transpose(2, 3)
|
| 285 |
+
angles = self._interleave_axes(angles, self.mrope_section)
|
| 286 |
+
table = torch.cat((angles, angles), dim=-1)
|
| 287 |
+
cos = table.cos() * self.attention_scaling
|
| 288 |
+
sin = table.sin() * self.attention_scaling
|
| 289 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 290 |
+
|
| 291 |
+
@staticmethod
|
| 292 |
+
def _interleave_axes(angles, section):
|
| 293 |
+
"""Fold the H and W axes into the T table at every 2nd / 3rd frequency slot."""
|
| 294 |
+
merged = angles[0]
|
| 295 |
+
for axis, offset in ((1, 1), (2, 2)):
|
| 296 |
+
take = slice(offset, section[axis] * 3, 3)
|
| 297 |
+
merged[..., take] = angles[axis, ..., take]
|
| 298 |
+
return merged
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class AgnesVisionRotary(nn.Module):
|
| 302 |
+
inv_freq: torch.Tensor
|
| 303 |
+
|
| 304 |
+
def __init__(self, dim: int, theta: float = 10000.0) -> None:
|
| 305 |
+
super().__init__()
|
| 306 |
+
self.dim = dim
|
| 307 |
+
self.theta = theta
|
| 308 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
|
| 309 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 310 |
+
|
| 311 |
+
def forward(self, position_ids: torch.Tensor) -> torch.Tensor:
|
| 312 |
+
return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _apply_vision_rope(q, k, cos, sin):
|
| 316 |
+
q_dtype, k_dtype = q.dtype, k.dtype
|
| 317 |
+
q, k = q.float(), k.float()
|
| 318 |
+
cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
|
| 319 |
+
q = (q * cos) + (_swap_halves(q) * sin)
|
| 320 |
+
k = (k * cos) + (_swap_halves(k) * sin)
|
| 321 |
+
return q.to(q_dtype), k.to(k_dtype)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# ---------------------------------------------------------------------------
|
| 325 |
+
# Global (softmax) attention
|
| 326 |
+
# ---------------------------------------------------------------------------
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _broadcast_kv(x: torch.Tensor, groups: int) -> torch.Tensor:
|
| 330 |
+
"""Repeat each kv head `groups` times along the head axis."""
|
| 331 |
+
b, h, t, d = x.shape
|
| 332 |
+
if groups == 1:
|
| 333 |
+
return x
|
| 334 |
+
return x[:, :, None, :, :].expand(b, h, groups, t, d).reshape(b, h * groups, t, d)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _dense_attention(
|
| 338 |
+
module: nn.Module,
|
| 339 |
+
query: torch.Tensor,
|
| 340 |
+
key: torch.Tensor,
|
| 341 |
+
value: torch.Tensor,
|
| 342 |
+
attention_mask: torch.Tensor | None,
|
| 343 |
+
scaling: float,
|
| 344 |
+
dropout: float = 0.0,
|
| 345 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 346 |
+
):
|
| 347 |
+
k = _broadcast_kv(key, module.num_key_value_groups)
|
| 348 |
+
v = _broadcast_kv(value, module.num_key_value_groups)
|
| 349 |
+
scores = torch.matmul(query, k.transpose(2, 3)) * scaling
|
| 350 |
+
if attention_mask is not None:
|
| 351 |
+
scores = scores + attention_mask
|
| 352 |
+
probs = nn.functional.softmax(scores, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 353 |
+
probs = nn.functional.dropout(probs, p=dropout, training=module.training)
|
| 354 |
+
out = torch.matmul(probs, v).transpose(1, 2).contiguous()
|
| 355 |
+
return out, probs
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class AgnesGlobalAttention(nn.Module):
|
| 359 |
+
"""Grouped-query softmax attention with per-head q/k normalisation and a
|
| 360 |
+
sigmoid output gate produced alongside the queries."""
|
| 361 |
+
|
| 362 |
+
def __init__(self, config: AgnesTextConfig, layer_idx: int):
|
| 363 |
+
super().__init__()
|
| 364 |
+
self.config = config
|
| 365 |
+
self.layer_idx = layer_idx
|
| 366 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 367 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 368 |
+
self.scaling = self.head_dim**-0.5
|
| 369 |
+
self.attention_dropout = config.attention_dropout
|
| 370 |
+
self.is_causal = True
|
| 371 |
+
q_width = config.num_attention_heads * self.head_dim
|
| 372 |
+
kv_width = config.num_key_value_heads * self.head_dim
|
| 373 |
+
self.q_proj = nn.Linear(config.hidden_size, q_width * 2, bias=config.attention_bias)
|
| 374 |
+
self.k_proj = nn.Linear(config.hidden_size, kv_width, bias=config.attention_bias)
|
| 375 |
+
self.v_proj = nn.Linear(config.hidden_size, kv_width, bias=config.attention_bias)
|
| 376 |
+
self.o_proj = nn.Linear(q_width, config.hidden_size, bias=config.attention_bias)
|
| 377 |
+
self.q_norm = AgnesRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 378 |
+
self.k_norm = AgnesRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 379 |
+
|
| 380 |
+
def forward(
|
| 381 |
+
self,
|
| 382 |
+
hidden_states: torch.Tensor,
|
| 383 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 384 |
+
attention_mask: torch.Tensor | None,
|
| 385 |
+
past_key_values: Cache | None = None,
|
| 386 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 387 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 388 |
+
lead = hidden_states.shape[:-1]
|
| 389 |
+
per_head = (*lead, -1, self.head_dim)
|
| 390 |
+
|
| 391 |
+
q, gate = torch.chunk(self.q_proj(hidden_states).view(*lead, -1, self.head_dim * 2), 2, dim=-1)
|
| 392 |
+
gate = gate.reshape(*lead, -1)
|
| 393 |
+
q = self.q_norm(q.view(per_head)).transpose(1, 2)
|
| 394 |
+
k = self.k_norm(self.k_proj(hidden_states).view(per_head)).transpose(1, 2)
|
| 395 |
+
v = self.v_proj(hidden_states).view(per_head).transpose(1, 2)
|
| 396 |
+
|
| 397 |
+
cos, sin = position_embeddings
|
| 398 |
+
q, k = _apply_rope(q, k, cos, sin)
|
| 399 |
+
if past_key_values is not None:
|
| 400 |
+
k, v = past_key_values.update(k, v, self.layer_idx)
|
| 401 |
+
|
| 402 |
+
attend: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, _dense_attention)
|
| 403 |
+
out, probs = attend(
|
| 404 |
+
self, q, k, v, attention_mask,
|
| 405 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 406 |
+
scaling=self.scaling,
|
| 407 |
+
**kwargs,
|
| 408 |
+
)
|
| 409 |
+
out = out.reshape(*lead, -1).contiguous()
|
| 410 |
+
out = out * torch.sigmoid(gate)
|
| 411 |
+
return self.o_proj(out), probs
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
# ---------------------------------------------------------------------------
|
| 415 |
+
# Delta-rule (recurrent) attention
|
| 416 |
+
# ---------------------------------------------------------------------------
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _zero_padded_positions(hidden_states, attention_mask):
|
| 420 |
+
"""Mask out padding tokens so they leave no trace in the recurrent state."""
|
| 421 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 422 |
+
dt = hidden_states.dtype
|
| 423 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dt)
|
| 424 |
+
return hidden_states
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def _causal_conv_step(hidden_states, conv_state, weight, bias=None, activation=None):
|
| 428 |
+
"""One decode step of the depthwise causal conv, updating `conv_state` in place."""
|
| 429 |
+
_, channels, steps = hidden_states.shape
|
| 430 |
+
window = conv_state.shape[-1]
|
| 431 |
+
joined = torch.cat([conv_state, hidden_states], dim=-1).to(weight.dtype)
|
| 432 |
+
conv_state.copy_(joined[:, :, -window:])
|
| 433 |
+
y = F.conv1d(joined, weight.unsqueeze(1), bias, padding=0, groups=channels)
|
| 434 |
+
y = F.silu(y[:, :, -steps:])
|
| 435 |
+
return y.to(hidden_states.dtype)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def _unit_normalize(x: torch.FloatTensor, dim: int = -1, eps: float = 1e-6):
|
| 439 |
+
return x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _delta_rule_chunked(
|
| 443 |
+
query, key, value, g, beta, chunk_size=64, initial_state=None, output_final_state=False,
|
| 444 |
+
use_qk_l2norm_in_kernel=False, **kwargs,
|
| 445 |
+
):
|
| 446 |
+
"""Chunk-parallel gated delta rule (prefill path)."""
|
| 447 |
+
out_dtype = query.dtype
|
| 448 |
+
if use_qk_l2norm_in_kernel:
|
| 449 |
+
query = _unit_normalize(query, dim=-1, eps=1e-6)
|
| 450 |
+
key = _unit_normalize(key, dim=-1, eps=1e-6)
|
| 451 |
+
query, key, value, beta, g = [t.transpose(1, 2).contiguous().to(torch.float32) for t in (query, key, value, beta, g)]
|
| 452 |
+
|
| 453 |
+
bsz, heads, seq, dk = key.shape
|
| 454 |
+
dv = value.shape[-1]
|
| 455 |
+
pad = (chunk_size - seq % chunk_size) % chunk_size
|
| 456 |
+
query = F.pad(query, (0, 0, 0, pad))
|
| 457 |
+
key = F.pad(key, (0, 0, 0, pad))
|
| 458 |
+
value = F.pad(value, (0, 0, 0, pad))
|
| 459 |
+
beta = F.pad(beta, (0, pad))
|
| 460 |
+
g = F.pad(g, (0, pad))
|
| 461 |
+
padded = seq + pad
|
| 462 |
+
query = query * (1 / (query.shape[-1] ** 0.5))
|
| 463 |
+
|
| 464 |
+
v_beta = value * beta.unsqueeze(-1)
|
| 465 |
+
k_beta = key * beta.unsqueeze(-1)
|
| 466 |
+
query, key, value, k_beta, v_beta = [
|
| 467 |
+
t.reshape(t.shape[0], t.shape[1], -1, chunk_size, t.shape[-1]) for t in (query, key, value, k_beta, v_beta)
|
| 468 |
+
]
|
| 469 |
+
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
|
| 470 |
+
upper = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
|
| 471 |
+
|
| 472 |
+
g = g.cumsum(dim=-1)
|
| 473 |
+
decay = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
|
| 474 |
+
solve = -((k_beta @ key.transpose(-1, -2)) * decay).masked_fill(upper, 0)
|
| 475 |
+
for i in range(1, chunk_size):
|
| 476 |
+
row = solve[..., i, :i].clone()
|
| 477 |
+
block = solve[..., :i, :i].clone()
|
| 478 |
+
solve[..., i, :i] = row + (row.unsqueeze(-1) * block).sum(-2)
|
| 479 |
+
solve = solve + torch.eye(chunk_size, dtype=solve.dtype, device=solve.device)
|
| 480 |
+
value = solve @ v_beta
|
| 481 |
+
k_decayed = solve @ (k_beta * g.exp().unsqueeze(-1))
|
| 482 |
+
state = (
|
| 483 |
+
torch.zeros(bsz, heads, dk, dv, dtype=value.dtype, device=value.device)
|
| 484 |
+
if initial_state is None
|
| 485 |
+
else initial_state.to(value)
|
| 486 |
+
)
|
| 487 |
+
out = torch.zeros_like(value)
|
| 488 |
+
strict_upper = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=1)
|
| 489 |
+
|
| 490 |
+
for i in range(0, padded // chunk_size):
|
| 491 |
+
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
|
| 492 |
+
local = q_i @ k_i.transpose(-1, -2) * decay[:, :, i]
|
| 493 |
+
v_pred = (k_decayed[:, :, i]) @ state
|
| 494 |
+
v_res = v_i - v_pred
|
| 495 |
+
carried = (q_i * g[:, :, i, :, None].exp()) @ state
|
| 496 |
+
out[:, :, i] = carried + local @ v_res
|
| 497 |
+
state = (
|
| 498 |
+
state * g[:, :, i, -1, None, None].exp()
|
| 499 |
+
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_res
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
if not output_final_state:
|
| 503 |
+
state = None
|
| 504 |
+
out = out.reshape(out.shape[0], out.shape[1], -1, out.shape[-1])
|
| 505 |
+
out = out[:, :, :seq]
|
| 506 |
+
return out.transpose(1, 2).contiguous().to(out_dtype), state
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _delta_rule_stepwise(query, key, value, g, beta, initial_state, output_final_state, use_qk_l2norm_in_kernel=False):
|
| 510 |
+
"""Token-by-token gated delta rule (decode path)."""
|
| 511 |
+
out_dtype = query.dtype
|
| 512 |
+
if use_qk_l2norm_in_kernel:
|
| 513 |
+
query = _unit_normalize(query, dim=-1, eps=1e-6)
|
| 514 |
+
key = _unit_normalize(key, dim=-1, eps=1e-6)
|
| 515 |
+
query, key, value, beta, g = [t.transpose(1, 2).contiguous().to(torch.float32) for t in (query, key, value, beta, g)]
|
| 516 |
+
|
| 517 |
+
bsz, heads, seq, dk = key.shape
|
| 518 |
+
dv = value.shape[-1]
|
| 519 |
+
query = query * (1 / (query.shape[-1] ** 0.5))
|
| 520 |
+
|
| 521 |
+
out = torch.zeros(bsz, heads, seq, dv, dtype=value.dtype, device=value.device)
|
| 522 |
+
state = (
|
| 523 |
+
torch.zeros(bsz, heads, dk, dv, dtype=value.dtype, device=value.device)
|
| 524 |
+
if initial_state is None
|
| 525 |
+
else initial_state.to(value)
|
| 526 |
+
)
|
| 527 |
+
for t in range(seq):
|
| 528 |
+
q_t, k_t, v_t = query[:, :, t], key[:, :, t], value[:, :, t]
|
| 529 |
+
decay_t = g[:, :, t].exp().unsqueeze(-1).unsqueeze(-1)
|
| 530 |
+
beta_t = beta[:, :, t].unsqueeze(-1)
|
| 531 |
+
state = state * decay_t
|
| 532 |
+
recalled = (state * k_t.unsqueeze(-1)).sum(dim=-2)
|
| 533 |
+
correction = (v_t - recalled) * beta_t
|
| 534 |
+
state = state + k_t.unsqueeze(-1) * correction.unsqueeze(-2)
|
| 535 |
+
out[:, :, t] = (state * q_t.unsqueeze(-1)).sum(dim=-2)
|
| 536 |
+
|
| 537 |
+
if not output_final_state:
|
| 538 |
+
state = None
|
| 539 |
+
return out.transpose(1, 2).contiguous().to(out_dtype), state
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
class AgnesDeltaAttention(nn.Module):
|
| 543 |
+
"""Gated delta-rule recurrent attention with a causal depthwise conv on
|
| 544 |
+
the projected q/k/v and a gated RMS norm on the output."""
|
| 545 |
+
|
| 546 |
+
def __init__(self, config: AgnesTextConfig, layer_idx: int):
|
| 547 |
+
super().__init__()
|
| 548 |
+
self.hidden_size = config.hidden_size
|
| 549 |
+
self.num_v_heads = config.linear_num_value_heads
|
| 550 |
+
self.num_k_heads = config.linear_num_key_heads
|
| 551 |
+
self.head_k_dim = config.linear_key_head_dim
|
| 552 |
+
self.head_v_dim = config.linear_value_head_dim
|
| 553 |
+
self.key_dim = self.head_k_dim * self.num_k_heads
|
| 554 |
+
self.value_dim = self.head_v_dim * self.num_v_heads
|
| 555 |
+
self.conv_kernel_size = config.linear_conv_kernel_dim
|
| 556 |
+
self.layer_idx = layer_idx
|
| 557 |
+
self.activation = config.hidden_act
|
| 558 |
+
self.act = ACT2FN[config.hidden_act]
|
| 559 |
+
self.layer_norm_epsilon = config.rms_norm_eps
|
| 560 |
+
|
| 561 |
+
self.conv_dim = self.key_dim * 2 + self.value_dim
|
| 562 |
+
self.conv1d = nn.Conv1d(
|
| 563 |
+
in_channels=self.conv_dim, out_channels=self.conv_dim, bias=False,
|
| 564 |
+
kernel_size=self.conv_kernel_size, groups=self.conv_dim, padding=self.conv_kernel_size - 1,
|
| 565 |
+
)
|
| 566 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_v_heads))
|
| 567 |
+
self.A_log = nn.Parameter(torch.log(torch.empty(self.num_v_heads).uniform_(0, 16)))
|
| 568 |
+
|
| 569 |
+
if FusedRMSNormGated is None:
|
| 570 |
+
self.norm = AgnesGatedNorm(self.head_v_dim, eps=self.layer_norm_epsilon)
|
| 571 |
+
else:
|
| 572 |
+
self.norm = FusedRMSNormGated(
|
| 573 |
+
self.head_v_dim, eps=self.layer_norm_epsilon, activation=self.activation,
|
| 574 |
+
device=torch.cuda.current_device(),
|
| 575 |
+
dtype=config.dtype if config.dtype is not None else torch.get_default_dtype(),
|
| 576 |
+
)
|
| 577 |
+
self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
|
| 578 |
+
|
| 579 |
+
self.causal_conv1d_fn = causal_conv1d_fn
|
| 580 |
+
self.causal_conv1d_update = causal_conv1d_update or _causal_conv_step
|
| 581 |
+
self.chunk_gated_delta_rule = chunk_gated_delta_rule or _delta_rule_chunked
|
| 582 |
+
self.recurrent_gated_delta_rule = fused_recurrent_gated_delta_rule or _delta_rule_stepwise
|
| 583 |
+
if not _FUSED_DELTA_PATH:
|
| 584 |
+
logger.warning_once(
|
| 585 |
+
"Fused delta-rule kernels not found (flash-linear-attention / causal-conv1d); "
|
| 586 |
+
"using the pure-torch implementation."
|
| 587 |
+
)
|
| 588 |
+
|
| 589 |
+
self.in_proj_qkv = nn.Linear(self.hidden_size, self.key_dim * 2 + self.value_dim, bias=False)
|
| 590 |
+
self.in_proj_z = nn.Linear(self.hidden_size, self.value_dim, bias=False)
|
| 591 |
+
self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
|
| 592 |
+
self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
|
| 593 |
+
|
| 594 |
+
def forward(
|
| 595 |
+
self,
|
| 596 |
+
hidden_states: torch.Tensor,
|
| 597 |
+
cache_params: Cache | None = None,
|
| 598 |
+
attention_mask: torch.Tensor | None = None,
|
| 599 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 600 |
+
):
|
| 601 |
+
hidden_states = _zero_padded_positions(hidden_states, attention_mask)
|
| 602 |
+
bsz, seq, _ = hidden_states.shape
|
| 603 |
+
|
| 604 |
+
resume = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
|
| 605 |
+
if resume:
|
| 606 |
+
conv_state = cache_params.layers[self.layer_idx].conv_states
|
| 607 |
+
rec_state = cache_params.layers[self.layer_idx].recurrent_states
|
| 608 |
+
|
| 609 |
+
qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
|
| 610 |
+
z = self.in_proj_z(hidden_states).reshape(bsz, seq, -1, self.head_v_dim)
|
| 611 |
+
b = self.in_proj_b(hidden_states)
|
| 612 |
+
a = self.in_proj_a(hidden_states)
|
| 613 |
+
|
| 614 |
+
if resume and seq == 1:
|
| 615 |
+
qkv = self.causal_conv1d_update(qkv, conv_state, self.conv1d.weight.squeeze(1), self.conv1d.bias, self.activation)
|
| 616 |
+
else:
|
| 617 |
+
if resume:
|
| 618 |
+
qkv = torch.cat([conv_state, qkv], dim=-1)
|
| 619 |
+
if cache_params is not None:
|
| 620 |
+
cache_params.update_conv_state(F.pad(qkv, (self.conv_kernel_size - qkv.shape[-1], 0)), self.layer_idx)
|
| 621 |
+
if self.causal_conv1d_fn is not None:
|
| 622 |
+
qkv = self.causal_conv1d_fn(
|
| 623 |
+
x=qkv, weight=self.conv1d.weight.squeeze(1), bias=self.conv1d.bias,
|
| 624 |
+
activation=self.activation, seq_idx=kwargs.get("seq_idx"),
|
| 625 |
+
)
|
| 626 |
+
else:
|
| 627 |
+
qkv = F.silu(self.conv1d(qkv)[:, :, : qkv.shape[-1]])
|
| 628 |
+
if resume:
|
| 629 |
+
qkv = qkv[:, :, -seq:]
|
| 630 |
+
|
| 631 |
+
qkv = qkv.transpose(1, 2)
|
| 632 |
+
query, key, value = torch.split(qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
|
| 633 |
+
query = query.reshape(bsz, seq, -1, self.head_k_dim)
|
| 634 |
+
key = key.reshape(bsz, seq, -1, self.head_k_dim)
|
| 635 |
+
value = value.reshape(bsz, seq, -1, self.head_v_dim)
|
| 636 |
+
|
| 637 |
+
beta = b.sigmoid()
|
| 638 |
+
# fp32 keeps exp(A_log) finite under fp16 weights
|
| 639 |
+
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
|
| 640 |
+
groups = self.num_v_heads // self.num_k_heads
|
| 641 |
+
if groups > 1:
|
| 642 |
+
query = query.repeat_interleave(groups, dim=2)
|
| 643 |
+
key = key.repeat_interleave(groups, dim=2)
|
| 644 |
+
|
| 645 |
+
if resume and seq == 1:
|
| 646 |
+
mixed, rec_state = self.recurrent_gated_delta_rule(
|
| 647 |
+
query, key, value, g=g, beta=beta, initial_state=rec_state,
|
| 648 |
+
output_final_state=cache_params is not None, use_qk_l2norm_in_kernel=True,
|
| 649 |
+
)
|
| 650 |
+
else:
|
| 651 |
+
mixed, rec_state = self.chunk_gated_delta_rule(
|
| 652 |
+
query, key, value, g=g, beta=beta,
|
| 653 |
+
initial_state=rec_state if resume else None,
|
| 654 |
+
output_final_state=cache_params is not None, use_qk_l2norm_in_kernel=True,
|
| 655 |
+
cu_seqlens=kwargs.get("cu_seq_lens_q"),
|
| 656 |
+
)
|
| 657 |
+
if cache_params is not None:
|
| 658 |
+
cache_params.update_recurrent_state(rec_state, self.layer_idx)
|
| 659 |
+
|
| 660 |
+
mixed = self.norm(mixed.reshape(-1, self.head_v_dim), z.reshape(-1, self.head_v_dim))
|
| 661 |
+
return self.out_proj(mixed.reshape(bsz, seq, -1))
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
# ---------------------------------------------------------------------------
|
| 665 |
+
# Decoder layer / base class
|
| 666 |
+
# ---------------------------------------------------------------------------
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
class AgnesDecoderLayer(GradientCheckpointingLayer):
|
| 670 |
+
def __init__(self, config: AgnesTextConfig, layer_idx: int):
|
| 671 |
+
super().__init__()
|
| 672 |
+
self.hidden_size = config.hidden_size
|
| 673 |
+
self.layer_type = config.layer_types[layer_idx]
|
| 674 |
+
if self.layer_type == LAYER_DELTA:
|
| 675 |
+
self.delta_attn = AgnesDeltaAttention(config, layer_idx)
|
| 676 |
+
elif self.layer_type == LAYER_GLOBAL:
|
| 677 |
+
self.global_attn = AgnesGlobalAttention(config, layer_idx)
|
| 678 |
+
self.mlp = AgnesMLP(config, config.intermediate_size, getattr(config, "parallel_ffn_intermediate_size", 0) or 0)
|
| 679 |
+
self.input_layernorm = AgnesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 680 |
+
self.post_attention_layernorm = AgnesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 681 |
+
|
| 682 |
+
def forward(
|
| 683 |
+
self,
|
| 684 |
+
hidden_states: torch.Tensor,
|
| 685 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 686 |
+
attention_mask: torch.Tensor | None = None,
|
| 687 |
+
position_ids: torch.LongTensor | None = None,
|
| 688 |
+
past_key_values: Cache | None = None,
|
| 689 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 690 |
+
) -> torch.FloatTensor:
|
| 691 |
+
skip = hidden_states
|
| 692 |
+
h = self.input_layernorm(hidden_states)
|
| 693 |
+
if self.layer_type == LAYER_DELTA:
|
| 694 |
+
h = self.delta_attn(hidden_states=h, cache_params=past_key_values, attention_mask=attention_mask, **kwargs)
|
| 695 |
+
elif self.layer_type == LAYER_GLOBAL:
|
| 696 |
+
h, _ = self.global_attn(
|
| 697 |
+
hidden_states=h, attention_mask=attention_mask, position_ids=position_ids,
|
| 698 |
+
past_key_values=past_key_values, position_embeddings=position_embeddings, **kwargs,
|
| 699 |
+
)
|
| 700 |
+
h = skip + h
|
| 701 |
+
|
| 702 |
+
skip = h
|
| 703 |
+
h = self.mlp(self.post_attention_layernorm(h))
|
| 704 |
+
return skip + h
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
class AgnesPreTrainedModel(PreTrainedModel):
|
| 708 |
+
config: AgnesConfig
|
| 709 |
+
base_model_prefix = "model"
|
| 710 |
+
supports_gradient_checkpointing = True
|
| 711 |
+
_no_split_modules = ["AgnesDecoderLayer", "AgnesVisionBlock"]
|
| 712 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 713 |
+
_supports_flash_attn = True
|
| 714 |
+
_supports_sdpa = True
|
| 715 |
+
_keys_to_ignore_on_load_unexpected = [r"^mtp.*"]
|
| 716 |
+
_can_record_outputs = {
|
| 717 |
+
"hidden_states": AgnesDecoderLayer,
|
| 718 |
+
"attentions": AgnesGlobalAttention,
|
| 719 |
+
}
|
| 720 |
+
_is_stateful = True
|
| 721 |
+
|
| 722 |
+
@torch.no_grad()
|
| 723 |
+
def _init_weights(self, module):
|
| 724 |
+
super()._init_weights(module)
|
| 725 |
+
if isinstance(module, AgnesDeltaAttention):
|
| 726 |
+
init.ones_(module.dt_bias)
|
| 727 |
+
init.copy_(module.A_log, torch.empty_like(module.A_log).uniform_(0, 16).log_())
|
| 728 |
+
elif isinstance(module, AgnesRMSNorm):
|
| 729 |
+
# the norm scales by (1 + weight), so zero is the identity
|
| 730 |
+
init.zeros_(module.weight)
|
| 731 |
+
elif isinstance(module, AgnesVisionRotary):
|
| 732 |
+
inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim))
|
| 733 |
+
init.copy_(module.inv_freq, inv_freq)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
# ---------------------------------------------------------------------------
|
| 737 |
+
# Vision tower
|
| 738 |
+
# ---------------------------------------------------------------------------
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
class AgnesVisionPatchEmbed(nn.Module):
|
| 742 |
+
def __init__(self, config) -> None:
|
| 743 |
+
super().__init__()
|
| 744 |
+
self.patch_size = config.patch_size
|
| 745 |
+
self.temporal_patch_size = config.temporal_patch_size
|
| 746 |
+
self.in_channels = config.in_channels
|
| 747 |
+
self.embed_dim = config.hidden_size
|
| 748 |
+
kernel = [self.temporal_patch_size, self.patch_size, self.patch_size]
|
| 749 |
+
self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel, stride=kernel, bias=True)
|
| 750 |
+
|
| 751 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 752 |
+
dt = self.proj.weight.dtype
|
| 753 |
+
patches = hidden_states.view(-1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size)
|
| 754 |
+
return self.proj(patches.to(dtype=dt)).view(-1, self.embed_dim)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
class AgnesVisionMLP(nn.Module):
|
| 758 |
+
def __init__(self, config):
|
| 759 |
+
super().__init__()
|
| 760 |
+
self.hidden_size = config.hidden_size
|
| 761 |
+
self.intermediate_size = config.intermediate_size
|
| 762 |
+
self.linear_fc1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
|
| 763 |
+
self.linear_fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=True)
|
| 764 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 765 |
+
|
| 766 |
+
def forward(self, hidden_state):
|
| 767 |
+
return self.linear_fc2(self.act_fn(self.linear_fc1(hidden_state)))
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
class AgnesVisionAttention(nn.Module):
|
| 771 |
+
def __init__(self, config: AgnesVisionConfig) -> None:
|
| 772 |
+
super().__init__()
|
| 773 |
+
self.dim = config.hidden_size
|
| 774 |
+
self.num_heads = config.num_heads
|
| 775 |
+
self.head_dim = self.dim // self.num_heads
|
| 776 |
+
self.num_key_value_groups = 1
|
| 777 |
+
self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True)
|
| 778 |
+
self.proj = nn.Linear(self.dim, self.dim)
|
| 779 |
+
self.scaling = self.head_dim**-0.5
|
| 780 |
+
self.config = config
|
| 781 |
+
self.attention_dropout = 0.0
|
| 782 |
+
self.is_causal = False
|
| 783 |
+
|
| 784 |
+
def forward(
|
| 785 |
+
self,
|
| 786 |
+
hidden_states: torch.Tensor,
|
| 787 |
+
cu_seqlens: torch.Tensor,
|
| 788 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 789 |
+
**kwargs,
|
| 790 |
+
) -> torch.Tensor:
|
| 791 |
+
n_tok = hidden_states.shape[0]
|
| 792 |
+
q, k, v = self.qkv(hidden_states).reshape(n_tok, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 793 |
+
cos, sin = position_embeddings
|
| 794 |
+
q, k = _apply_vision_rope(q, k, cos, sin)
|
| 795 |
+
q = q.transpose(0, 1).unsqueeze(0)
|
| 796 |
+
k = k.transpose(0, 1).unsqueeze(0)
|
| 797 |
+
v = v.transpose(0, 1).unsqueeze(0)
|
| 798 |
+
|
| 799 |
+
attend: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, _dense_attention)
|
| 800 |
+
drop = 0.0 if not self.training else self.attention_dropout
|
| 801 |
+
if is_flash_attention_requested(self.config):
|
| 802 |
+
longest = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
|
| 803 |
+
out, _ = attend(
|
| 804 |
+
self, q, k, v, attention_mask=None, scaling=self.scaling, dropout=drop,
|
| 805 |
+
cu_seq_lens_q=cu_seqlens, cu_seq_lens_k=cu_seqlens, max_length_q=longest, max_length_k=longest,
|
| 806 |
+
is_causal=False, **kwargs,
|
| 807 |
+
)
|
| 808 |
+
else:
|
| 809 |
+
spans = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
|
| 810 |
+
pieces = [torch.split(t, spans, dim=2) for t in (q, k, v)]
|
| 811 |
+
out = torch.cat(
|
| 812 |
+
[
|
| 813 |
+
attend(self, qi, ki, vi, attention_mask=None, scaling=self.scaling, dropout=drop, is_causal=False, **kwargs)[0]
|
| 814 |
+
for qi, ki, vi in zip(*pieces)
|
| 815 |
+
],
|
| 816 |
+
dim=1,
|
| 817 |
+
)
|
| 818 |
+
return self.proj(out.reshape(n_tok, -1).contiguous())
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
class AgnesVisionBlock(GradientCheckpointingLayer):
|
| 822 |
+
def __init__(self, config, attn_implementation: str = "sdpa") -> None:
|
| 823 |
+
super().__init__()
|
| 824 |
+
self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6)
|
| 825 |
+
self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6)
|
| 826 |
+
self.attn = AgnesVisionAttention(config=config)
|
| 827 |
+
self.mlp = AgnesVisionMLP(config=config)
|
| 828 |
+
|
| 829 |
+
@auto_docstring
|
| 830 |
+
def forward(
|
| 831 |
+
self,
|
| 832 |
+
hidden_states: torch.Tensor,
|
| 833 |
+
cu_seqlens: torch.Tensor,
|
| 834 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 835 |
+
**kwargs,
|
| 836 |
+
) -> torch.Tensor:
|
| 837 |
+
r"""
|
| 838 |
+
cu_seqlens (`torch.Tensor`):
|
| 839 |
+
Cumulative sequence lengths used for packed variable-length attention.
|
| 840 |
+
"""
|
| 841 |
+
hidden_states = hidden_states + self.attn(
|
| 842 |
+
self.norm1(hidden_states), cu_seqlens=cu_seqlens, position_embeddings=position_embeddings, **kwargs
|
| 843 |
+
)
|
| 844 |
+
return hidden_states + self.mlp(self.norm2(hidden_states))
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
class AgnesVisionMerger(nn.Module):
|
| 848 |
+
def __init__(self, config: AgnesVisionConfig, use_postshuffle_norm=False) -> None:
|
| 849 |
+
super().__init__()
|
| 850 |
+
self.hidden_size = config.hidden_size * (config.spatial_merge_size**2)
|
| 851 |
+
self.use_postshuffle_norm = use_postshuffle_norm
|
| 852 |
+
self.norm = nn.LayerNorm(self.hidden_size if use_postshuffle_norm else config.hidden_size, eps=1e-6)
|
| 853 |
+
self.linear_fc1 = nn.Linear(self.hidden_size, self.hidden_size)
|
| 854 |
+
self.act_fn = nn.GELU()
|
| 855 |
+
self.linear_fc2 = nn.Linear(self.hidden_size, config.out_hidden_size)
|
| 856 |
+
|
| 857 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 858 |
+
x = self.norm(x.view(-1, self.hidden_size) if self.use_postshuffle_norm else x).view(-1, self.hidden_size)
|
| 859 |
+
return self.linear_fc2(self.act_fn(self.linear_fc1(x)))
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
class AgnesVisionModel(AgnesPreTrainedModel):
|
| 863 |
+
config: AgnesVisionConfig
|
| 864 |
+
config_class = AgnesVisionConfig
|
| 865 |
+
input_modalities = ("image", "video")
|
| 866 |
+
_can_record_outputs = {
|
| 867 |
+
"hidden_states": AgnesVisionBlock,
|
| 868 |
+
"attentions": AgnesVisionAttention,
|
| 869 |
+
}
|
| 870 |
+
_no_split_modules = ["AgnesVisionBlock"]
|
| 871 |
+
|
| 872 |
+
def __init__(self, config, *inputs, **kwargs) -> None:
|
| 873 |
+
super().__init__(config, *inputs, **kwargs)
|
| 874 |
+
self.spatial_merge_size = config.spatial_merge_size
|
| 875 |
+
self.patch_size = config.patch_size
|
| 876 |
+
self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size
|
| 877 |
+
self.patch_embed = AgnesVisionPatchEmbed(config=config)
|
| 878 |
+
self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size)
|
| 879 |
+
self.num_grid_per_side = int(config.num_position_embeddings**0.5)
|
| 880 |
+
self.rotary_pos_emb = AgnesVisionRotary((config.hidden_size // config.num_heads) // 2)
|
| 881 |
+
self.blocks = nn.ModuleList([AgnesVisionBlock(config) for _ in range(config.depth)])
|
| 882 |
+
self.merger = AgnesVisionMerger(config=config, use_postshuffle_norm=False)
|
| 883 |
+
self.gradient_checkpointing = False
|
| 884 |
+
self.post_init()
|
| 885 |
+
|
| 886 |
+
@merge_with_config_defaults
|
| 887 |
+
@capture_outputs
|
| 888 |
+
def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor:
|
| 889 |
+
"""
|
| 890 |
+
Args:
|
| 891 |
+
hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`):
|
| 892 |
+
Flattened patches.
|
| 893 |
+
grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`):
|
| 894 |
+
Temporal / height / width extent of every image or video.
|
| 895 |
+
"""
|
| 896 |
+
idx, w = get_vision_bilinear_indices_and_weights(
|
| 897 |
+
grid_thw, num_grid_per_side=self.num_grid_per_side, spatial_merge_size=self.config.spatial_merge_size, kwargs=kwargs
|
| 898 |
+
)
|
| 899 |
+
pos_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
|
| 900 |
+
cu_seqlens = get_vision_cu_seqlens(grid_thw, kwargs=kwargs)
|
| 901 |
+
|
| 902 |
+
tokens = self.patch_embed(hidden_states)
|
| 903 |
+
tokens = tokens + (self.pos_embed(idx) * w[:, :, None]).sum(0).to(tokens.dtype)
|
| 904 |
+
angles = self.rotary_pos_emb(pos_ids)
|
| 905 |
+
|
| 906 |
+
n_tok, _ = tokens.size()
|
| 907 |
+
tokens = tokens.reshape(n_tok, -1)
|
| 908 |
+
angles = angles.reshape(n_tok, -1)
|
| 909 |
+
table = torch.cat((angles, angles), dim=-1)
|
| 910 |
+
rope = (table.cos(), table.sin())
|
| 911 |
+
|
| 912 |
+
for block in self.blocks:
|
| 913 |
+
tokens = block(tokens, cu_seqlens=cu_seqlens, position_embeddings=rope, **kwargs)
|
| 914 |
+
|
| 915 |
+
return BaseModelOutputWithPooling(last_hidden_state=tokens, pooler_output=self.merger(tokens))
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
# ---------------------------------------------------------------------------
|
| 919 |
+
# Outputs
|
| 920 |
+
# ---------------------------------------------------------------------------
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
@auto_docstring
|
| 924 |
+
@dataclass
|
| 925 |
+
class AgnesModelOutput(BaseModelOutputWithPast):
|
| 926 |
+
r"""
|
| 927 |
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
| 928 |
+
Offset between the multimodal rotary positions and plain sequence positions.
|
| 929 |
+
"""
|
| 930 |
+
|
| 931 |
+
rope_deltas: torch.LongTensor | None = None
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
@auto_docstring
|
| 935 |
+
@dataclass
|
| 936 |
+
class AgnesCausalLMOutput(CausalLMOutputWithPast):
|
| 937 |
+
r"""
|
| 938 |
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
| 939 |
+
Offset between the multimodal rotary positions and plain sequence positions.
|
| 940 |
+
"""
|
| 941 |
+
|
| 942 |
+
rope_deltas: torch.LongTensor | None = None
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
# ---------------------------------------------------------------------------
|
| 946 |
+
# Language model
|
| 947 |
+
# ---------------------------------------------------------------------------
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
class AgnesTextModel(AgnesPreTrainedModel):
|
| 951 |
+
config: AgnesTextConfig
|
| 952 |
+
config_class = AgnesTextConfig
|
| 953 |
+
|
| 954 |
+
def __init__(self, config: AgnesTextConfig):
|
| 955 |
+
super().__init__(config)
|
| 956 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
| 957 |
+
self.layers = nn.ModuleList([AgnesDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 958 |
+
self.norm = AgnesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 959 |
+
self.rotary_emb = AgnesRotaryEmbedding(config=config)
|
| 960 |
+
self.gradient_checkpointing = False
|
| 961 |
+
self.post_init()
|
| 962 |
+
|
| 963 |
+
@merge_with_config_defaults
|
| 964 |
+
@capture_outputs
|
| 965 |
+
@auto_docstring
|
| 966 |
+
def forward(
|
| 967 |
+
self,
|
| 968 |
+
input_ids: torch.LongTensor | None = None,
|
| 969 |
+
attention_mask: torch.Tensor | None = None,
|
| 970 |
+
position_ids: torch.LongTensor | None = None,
|
| 971 |
+
past_key_values: Cache | None = None,
|
| 972 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 973 |
+
use_cache: bool | None = None,
|
| 974 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 975 |
+
) -> BaseModelOutputWithPast:
|
| 976 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 977 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 978 |
+
if inputs_embeds is None:
|
| 979 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 980 |
+
if use_cache and past_key_values is None:
|
| 981 |
+
past_key_values = DynamicCache(config=self.config)
|
| 982 |
+
|
| 983 |
+
# position ids carry four rows: plain text positions, then T / H / W
|
| 984 |
+
if position_ids is None:
|
| 985 |
+
offset = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 986 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + offset
|
| 987 |
+
position_ids = position_ids.view(1, 1, -1).expand(4, inputs_embeds.shape[0], -1)
|
| 988 |
+
elif position_ids.ndim == 2:
|
| 989 |
+
position_ids = position_ids[None, ...].expand(4, position_ids.shape[0], -1)
|
| 990 |
+
|
| 991 |
+
if position_ids.ndim == 3 and position_ids.shape[0] == 4:
|
| 992 |
+
text_positions, position_ids = position_ids[0], position_ids[1:]
|
| 993 |
+
else:
|
| 994 |
+
text_positions = None
|
| 995 |
+
|
| 996 |
+
global_mask = create_causal_mask(
|
| 997 |
+
config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask,
|
| 998 |
+
past_key_values=past_key_values, position_ids=text_positions,
|
| 999 |
+
)
|
| 1000 |
+
delta_mask = self._recurrent_mask(attention_mask, past_key_values)
|
| 1001 |
+
|
| 1002 |
+
h = inputs_embeds
|
| 1003 |
+
rope = self.rotary_emb(h, position_ids)
|
| 1004 |
+
for i, layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
| 1005 |
+
mask = delta_mask if self.config.layer_types[i] == LAYER_DELTA else global_mask
|
| 1006 |
+
h = layer(
|
| 1007 |
+
h, position_embeddings=rope, attention_mask=mask, position_ids=text_positions,
|
| 1008 |
+
past_key_values=past_key_values, use_cache=use_cache, **kwargs,
|
| 1009 |
+
)
|
| 1010 |
+
h = self.norm(h)
|
| 1011 |
+
return AgnesModelOutput(last_hidden_state=h, past_key_values=past_key_values)
|
| 1012 |
+
|
| 1013 |
+
@staticmethod
|
| 1014 |
+
def _recurrent_mask(attention_mask, past_key_values):
|
| 1015 |
+
"""Padding mask for the recurrent layers (left padding). Not needed
|
| 1016 |
+
once a cache holds prior state, or when nothing is masked."""
|
| 1017 |
+
if past_key_values is not None and past_key_values.has_previous_state():
|
| 1018 |
+
return None
|
| 1019 |
+
if attention_mask is not None and torch.all(attention_mask == 1):
|
| 1020 |
+
return None
|
| 1021 |
+
return attention_mask
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
@auto_docstring
|
| 1025 |
+
class AgnesModel(AgnesPreTrainedModel):
|
| 1026 |
+
config: AgnesConfig
|
| 1027 |
+
config_class = AgnesConfig
|
| 1028 |
+
base_model_prefix = "model"
|
| 1029 |
+
accepts_loss_kwargs = False
|
| 1030 |
+
_no_split_modules = ["AgnesDecoderLayer", "AgnesVisionBlock"]
|
| 1031 |
+
|
| 1032 |
+
def __init__(self, config):
|
| 1033 |
+
super().__init__(config)
|
| 1034 |
+
self.visual = AgnesVisionModel(config.vision_config)
|
| 1035 |
+
self.language_model = AgnesTextModel(config.text_config)
|
| 1036 |
+
self.rope_deltas = None
|
| 1037 |
+
self.post_init()
|
| 1038 |
+
|
| 1039 |
+
def get_vision_position_ids(
|
| 1040 |
+
self,
|
| 1041 |
+
start_position: int,
|
| 1042 |
+
grid_thw: list[int, int, int] | torch.Tensor,
|
| 1043 |
+
temp_merge_size: int = 1,
|
| 1044 |
+
spatial_merge_size: int = 1,
|
| 1045 |
+
time_interval: int = 1,
|
| 1046 |
+
device: str | torch.device | None = None,
|
| 1047 |
+
):
|
| 1048 |
+
"""Three-axis positions for the tokens of one image / video, offset by `start_position`."""
|
| 1049 |
+
n_t = grid_thw[0].item() // temp_merge_size
|
| 1050 |
+
n_h = grid_thw[1].item() // spatial_merge_size
|
| 1051 |
+
n_w = grid_thw[2].item() // spatial_merge_size
|
| 1052 |
+
|
| 1053 |
+
t_axis = torch.arange(n_t, device=device) * time_interval
|
| 1054 |
+
w_axis = torch.arange(n_w, device=device) + start_position
|
| 1055 |
+
h_axis = torch.arange(n_h, device=device) + start_position
|
| 1056 |
+
|
| 1057 |
+
# repeat patterns define the raster order; keep them as is
|
| 1058 |
+
w_axis = w_axis.repeat(n_h * n_t)
|
| 1059 |
+
h_axis = h_axis.repeat_interleave(n_w).repeat(n_t)
|
| 1060 |
+
t_axis = t_axis.repeat_interleave(n_h * n_w) + start_position
|
| 1061 |
+
return torch.stack([t_axis, h_axis, w_axis], dim=0)
|
| 1062 |
+
|
| 1063 |
+
def get_rope_index(
|
| 1064 |
+
self,
|
| 1065 |
+
input_ids: torch.LongTensor,
|
| 1066 |
+
mm_token_type_ids: torch.IntTensor,
|
| 1067 |
+
image_grid_thw: torch.LongTensor | None = None,
|
| 1068 |
+
video_grid_thw: torch.LongTensor | None = None,
|
| 1069 |
+
attention_mask: torch.Tensor | None = None,
|
| 1070 |
+
**kwargs,
|
| 1071 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1072 |
+
"""Build (3, batch, seq) rotary positions: text runs advance all three
|
| 1073 |
+
axes together, vision runs get grid positions. Videos are split per
|
| 1074 |
+
frame because frames are separated by timestamp tokens."""
|
| 1075 |
+
if video_grid_thw is not None:
|
| 1076 |
+
video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0)
|
| 1077 |
+
video_grid_thw[:, 0] = 1
|
| 1078 |
+
merge = self.config.vision_config.spatial_merge_size
|
| 1079 |
+
|
| 1080 |
+
deltas = []
|
| 1081 |
+
position_ids = torch.zeros(3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device)
|
| 1082 |
+
grids = {
|
| 1083 |
+
1: iter(image_grid_thw) if image_grid_thw is not None else None,
|
| 1084 |
+
2: iter(video_grid_thw) if video_grid_thw is not None else None,
|
| 1085 |
+
}
|
| 1086 |
+
|
| 1087 |
+
for b, ids in enumerate(input_ids):
|
| 1088 |
+
kinds = mm_token_type_ids[b]
|
| 1089 |
+
if attention_mask is not None:
|
| 1090 |
+
keep = attention_mask[b].bool()
|
| 1091 |
+
ids, kinds = ids[keep], kinds[keep]
|
| 1092 |
+
|
| 1093 |
+
runs = []
|
| 1094 |
+
for kind, members in itertools.groupby(enumerate(kinds.tolist()), lambda x: x[1]):
|
| 1095 |
+
members = list(members)
|
| 1096 |
+
runs.append((kind, members[0][0], members[-1][0] + 1))
|
| 1097 |
+
|
| 1098 |
+
cursor = 0
|
| 1099 |
+
pieces = []
|
| 1100 |
+
for kind, lo, hi in runs:
|
| 1101 |
+
if kind == 0:
|
| 1102 |
+
n = hi - lo
|
| 1103 |
+
pieces.append(torch.arange(n, device=input_ids.device).view(1, -1).expand(3, -1) + cursor)
|
| 1104 |
+
cursor += n
|
| 1105 |
+
else:
|
| 1106 |
+
thw = next(grids[kind])
|
| 1107 |
+
pieces.append(self.get_vision_position_ids(cursor, thw, 1, merge, device=input_ids.device))
|
| 1108 |
+
cursor += max(thw[1], thw[2]) // merge
|
| 1109 |
+
pos = torch.cat(pieces, dim=1).reshape(3, -1)
|
| 1110 |
+
if attention_mask is not None:
|
| 1111 |
+
position_ids[:, b, attention_mask[b].bool()] = pos.to(position_ids.device)
|
| 1112 |
+
else:
|
| 1113 |
+
position_ids[:, b] = pos.to(position_ids.device)
|
| 1114 |
+
deltas.append(pos.max() + 1 - len(ids))
|
| 1115 |
+
return position_ids, torch.tensor(deltas, device=input_ids.device).unsqueeze(1)
|
| 1116 |
+
|
| 1117 |
+
@accepts_precomputed_kwargs(modality="video")
|
| 1118 |
+
@can_return_tuple
|
| 1119 |
+
@auto_docstring
|
| 1120 |
+
def get_video_features(
|
| 1121 |
+
self,
|
| 1122 |
+
pixel_values_videos: torch.FloatTensor,
|
| 1123 |
+
video_grid_thw: torch.LongTensor | None = None,
|
| 1124 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1125 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 1126 |
+
r"""
|
| 1127 |
+
pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 1128 |
+
Video frames as patches.
|
| 1129 |
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
| 1130 |
+
Temporal / height / width extent of every video.
|
| 1131 |
+
"""
|
| 1132 |
+
return self.get_image_features(pixel_values_videos, video_grid_thw, **kwargs)
|
| 1133 |
+
|
| 1134 |
+
@accepts_precomputed_kwargs(modality="image")
|
| 1135 |
+
@can_return_tuple
|
| 1136 |
+
@auto_docstring
|
| 1137 |
+
def get_image_features(
|
| 1138 |
+
self,
|
| 1139 |
+
pixel_values: torch.FloatTensor,
|
| 1140 |
+
image_grid_thw: torch.LongTensor | None = None,
|
| 1141 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1142 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 1143 |
+
r"""
|
| 1144 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 1145 |
+
Images as patches.
|
| 1146 |
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
| 1147 |
+
Temporal / height / width extent of every image.
|
| 1148 |
+
"""
|
| 1149 |
+
pixel_values = pixel_values.type(self.visual.dtype)
|
| 1150 |
+
vis: BaseModelOutputWithPooling = self.visual(pixel_values, grid_thw=image_grid_thw, return_dict=True, **kwargs)
|
| 1151 |
+
per_image = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
|
| 1152 |
+
vis.pooler_output = torch.split(vis.pooler_output, per_image)
|
| 1153 |
+
return vis
|
| 1154 |
+
|
| 1155 |
+
def get_placeholder_mask(
|
| 1156 |
+
self,
|
| 1157 |
+
input_ids: torch.LongTensor,
|
| 1158 |
+
inputs_embeds: torch.FloatTensor,
|
| 1159 |
+
image_features: torch.FloatTensor | None = None,
|
| 1160 |
+
video_features: torch.FloatTensor | None = None,
|
| 1161 |
+
):
|
| 1162 |
+
"""Boolean masks over the image / video placeholder tokens, checked
|
| 1163 |
+
against the number of visual features supplied."""
|
| 1164 |
+
if input_ids is None:
|
| 1165 |
+
embed = self.get_input_embeddings()
|
| 1166 |
+
dev = inputs_embeds.device
|
| 1167 |
+
image_mask = (inputs_embeds == embed(torch.tensor(self.config.image_token_id, dtype=torch.long, device=dev))).all(-1)
|
| 1168 |
+
video_mask = (inputs_embeds == embed(torch.tensor(self.config.video_token_id, dtype=torch.long, device=dev))).all(-1)
|
| 1169 |
+
else:
|
| 1170 |
+
image_mask = input_ids == self.config.image_token_id
|
| 1171 |
+
video_mask = input_ids == self.config.video_token_id
|
| 1172 |
+
|
| 1173 |
+
n_img = image_mask.sum()
|
| 1174 |
+
image_mask = image_mask.unsqueeze(-1).to(inputs_embeds.device)
|
| 1175 |
+
if image_features is not None:
|
| 1176 |
+
torch_compilable_check(
|
| 1177 |
+
n_img * inputs_embeds.shape[-1] == image_features.numel(),
|
| 1178 |
+
f"Image features and image tokens do not match, tokens: {n_img}, features: {image_features.shape[0]}",
|
| 1179 |
+
)
|
| 1180 |
+
n_vid = video_mask.sum()
|
| 1181 |
+
video_mask = video_mask.unsqueeze(-1).to(inputs_embeds.device)
|
| 1182 |
+
if video_features is not None:
|
| 1183 |
+
torch_compilable_check(
|
| 1184 |
+
n_vid * inputs_embeds.shape[-1] == video_features.numel(),
|
| 1185 |
+
f"Video features and video tokens do not match, tokens: {n_vid}, features: {video_features.shape[0]}",
|
| 1186 |
+
)
|
| 1187 |
+
return image_mask, video_mask
|
| 1188 |
+
|
| 1189 |
+
def compute_3d_position_ids(
|
| 1190 |
+
self,
|
| 1191 |
+
input_ids: torch.Tensor | None,
|
| 1192 |
+
inputs_embeds: torch.Tensor | None,
|
| 1193 |
+
image_grid_thw: torch.Tensor | None = None,
|
| 1194 |
+
video_grid_thw: torch.Tensor | None = None,
|
| 1195 |
+
attention_mask: torch.Tensor | None = None,
|
| 1196 |
+
past_key_values: torch.Tensor | None = None,
|
| 1197 |
+
mm_token_type_ids: torch.IntTensor | None = None,
|
| 1198 |
+
) -> torch.Tensor | None:
|
| 1199 |
+
past_len = 0 if past_key_values is None else past_key_values.get_seq_length()
|
| 1200 |
+
has_vision = image_grid_thw is not None or video_grid_thw is not None
|
| 1201 |
+
if has_vision and mm_token_type_ids is None and input_ids is not None:
|
| 1202 |
+
raise ValueError(
|
| 1203 |
+
"Multimodal data was passed (via `image_grid_thw` or `video_grid_thw`) but `mm_token_type_ids` is "
|
| 1204 |
+
"missing. Pass `mm_token_type_ids` (returned by the processor) so the 3-D rotary positions can be built."
|
| 1205 |
+
)
|
| 1206 |
+
fresh = input_ids is not None and mm_token_type_ids is not None and has_vision
|
| 1207 |
+
|
| 1208 |
+
if fresh and (self.rope_deltas is None or past_len == 0):
|
| 1209 |
+
position_ids, self.rope_deltas = self.get_rope_index(
|
| 1210 |
+
input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw,
|
| 1211 |
+
attention_mask=attention_mask, mm_token_type_ids=mm_token_type_ids,
|
| 1212 |
+
)
|
| 1213 |
+
return position_ids
|
| 1214 |
+
# continuing generation, or embeds-only input: reuse the stored deltas
|
| 1215 |
+
if self.rope_deltas is not None and (past_len > 0 or input_ids is None):
|
| 1216 |
+
bsz, seq, _ = inputs_embeds.shape
|
| 1217 |
+
if attention_mask is not None:
|
| 1218 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1219 |
+
position_ids = position_ids.masked_fill(attention_mask == 0, 0)
|
| 1220 |
+
position_ids = position_ids.view(1, bsz, -1).repeat(3, 1, 1).to(inputs_embeds.device)
|
| 1221 |
+
else:
|
| 1222 |
+
position_ids = torch.arange(past_len, past_len + seq)
|
| 1223 |
+
position_ids = position_ids.view(1, 1, -1).expand(3, bsz, -1).to(inputs_embeds.device)
|
| 1224 |
+
delta = self.rope_deltas.repeat_interleave(bsz // self.rope_deltas.shape[0], dim=0)
|
| 1225 |
+
return position_ids + delta.to(device=inputs_embeds.device)
|
| 1226 |
+
return None
|
| 1227 |
+
|
| 1228 |
+
@auto_docstring
|
| 1229 |
+
@can_return_tuple
|
| 1230 |
+
def forward(
|
| 1231 |
+
self,
|
| 1232 |
+
input_ids: torch.LongTensor = None,
|
| 1233 |
+
attention_mask: torch.Tensor | None = None,
|
| 1234 |
+
position_ids: torch.LongTensor | None = None,
|
| 1235 |
+
past_key_values: Cache | None = None,
|
| 1236 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1237 |
+
pixel_values: torch.Tensor | None = None,
|
| 1238 |
+
pixel_values_videos: torch.FloatTensor | None = None,
|
| 1239 |
+
image_grid_thw: torch.LongTensor | None = None,
|
| 1240 |
+
video_grid_thw: torch.LongTensor | None = None,
|
| 1241 |
+
mm_token_type_ids: torch.IntTensor | None = None,
|
| 1242 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1243 |
+
) -> tuple | AgnesModelOutput:
|
| 1244 |
+
r"""
|
| 1245 |
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
| 1246 |
+
Temporal / height / width extent of every image.
|
| 1247 |
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
| 1248 |
+
Temporal / height / width extent of every video.
|
| 1249 |
+
"""
|
| 1250 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 1251 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 1252 |
+
if inputs_embeds is None:
|
| 1253 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 1254 |
+
|
| 1255 |
+
if pixel_values is not None:
|
| 1256 |
+
feats = torch.cat(
|
| 1257 |
+
self.get_image_features(pixel_values, image_grid_thw, return_dict=True, **kwargs).pooler_output, dim=0
|
| 1258 |
+
).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 1259 |
+
mask, _ = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds, image_features=feats)
|
| 1260 |
+
inputs_embeds = inputs_embeds.masked_scatter(mask, feats)
|
| 1261 |
+
|
| 1262 |
+
if pixel_values_videos is not None:
|
| 1263 |
+
feats = torch.cat(
|
| 1264 |
+
self.get_video_features(pixel_values_videos, video_grid_thw, return_dict=True, **kwargs).pooler_output, dim=0
|
| 1265 |
+
).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 1266 |
+
_, mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds, video_features=feats)
|
| 1267 |
+
inputs_embeds = inputs_embeds.masked_scatter(mask, feats)
|
| 1268 |
+
|
| 1269 |
+
if position_ids is None:
|
| 1270 |
+
position_ids = self.compute_3d_position_ids(
|
| 1271 |
+
input_ids=input_ids, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw,
|
| 1272 |
+
inputs_embeds=inputs_embeds, attention_mask=attention_mask, past_key_values=past_key_values,
|
| 1273 |
+
mm_token_type_ids=mm_token_type_ids,
|
| 1274 |
+
)
|
| 1275 |
+
|
| 1276 |
+
out = self.language_model(
|
| 1277 |
+
input_ids=None, position_ids=position_ids, attention_mask=attention_mask,
|
| 1278 |
+
past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs,
|
| 1279 |
+
)
|
| 1280 |
+
return AgnesModelOutput(**out, rope_deltas=self.rope_deltas)
|
| 1281 |
+
|
| 1282 |
+
|
| 1283 |
+
@auto_docstring
|
| 1284 |
+
class AgnesForCausalLM(AgnesPreTrainedModel, GenerationMixin):
|
| 1285 |
+
"""Text-only head over `AgnesTextModel`."""
|
| 1286 |
+
|
| 1287 |
+
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 1288 |
+
_tp_plan = {"lm_head": "colwise_gather_output"}
|
| 1289 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 1290 |
+
config: AgnesTextConfig
|
| 1291 |
+
config_class = AgnesTextConfig
|
| 1292 |
+
_keys_to_ignore_on_load_unexpected = [r"^mtp.*", r"^model.visual.*"]
|
| 1293 |
+
|
| 1294 |
+
def __init__(self, config):
|
| 1295 |
+
super().__init__(config)
|
| 1296 |
+
self.model = AgnesTextModel(config)
|
| 1297 |
+
self.vocab_size = config.vocab_size
|
| 1298 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1299 |
+
self.post_init()
|
| 1300 |
+
|
| 1301 |
+
@can_return_tuple
|
| 1302 |
+
@auto_docstring
|
| 1303 |
+
def forward(
|
| 1304 |
+
self,
|
| 1305 |
+
input_ids: torch.LongTensor | None = None,
|
| 1306 |
+
attention_mask: torch.Tensor | None = None,
|
| 1307 |
+
position_ids: torch.LongTensor | None = None,
|
| 1308 |
+
past_key_values: Cache | None = None,
|
| 1309 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1310 |
+
labels: torch.LongTensor | None = None,
|
| 1311 |
+
use_cache: bool | None = None,
|
| 1312 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 1313 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1314 |
+
) -> CausalLMOutputWithPast:
|
| 1315 |
+
r"""
|
| 1316 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1317 |
+
Targets for the language-modelling loss; -100 marks ignored positions.
|
| 1318 |
+
"""
|
| 1319 |
+
out: BaseModelOutputWithPast = self.model(
|
| 1320 |
+
input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids,
|
| 1321 |
+
past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, **kwargs,
|
| 1322 |
+
)
|
| 1323 |
+
keep = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1324 |
+
logits = self.lm_head(out.last_hidden_state[:, keep, :])
|
| 1325 |
+
loss = None
|
| 1326 |
+
if labels is not None:
|
| 1327 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
| 1328 |
+
return CausalLMOutputWithPast(
|
| 1329 |
+
loss=loss, logits=logits, past_key_values=out.past_key_values,
|
| 1330 |
+
hidden_states=out.hidden_states, attentions=out.attentions,
|
| 1331 |
+
)
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
class AgnesForConditionalGeneration(AgnesPreTrainedModel, GenerationMixin):
|
| 1335 |
+
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
|
| 1336 |
+
accepts_loss_kwargs = False
|
| 1337 |
+
config: AgnesConfig
|
| 1338 |
+
config_class = AgnesConfig
|
| 1339 |
+
|
| 1340 |
+
def __init__(self, config):
|
| 1341 |
+
super().__init__(config)
|
| 1342 |
+
self.model = AgnesModel(config)
|
| 1343 |
+
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
|
| 1344 |
+
self.post_init()
|
| 1345 |
+
|
| 1346 |
+
@auto_docstring
|
| 1347 |
+
def get_video_features(
|
| 1348 |
+
self,
|
| 1349 |
+
pixel_values_videos: torch.FloatTensor,
|
| 1350 |
+
video_grid_thw: torch.LongTensor | None = None,
|
| 1351 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1352 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 1353 |
+
r"""
|
| 1354 |
+
pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 1355 |
+
Video frames as patches.
|
| 1356 |
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
| 1357 |
+
Temporal / height / width extent of every video.
|
| 1358 |
+
"""
|
| 1359 |
+
return self.model.get_video_features(pixel_values_videos, video_grid_thw, **kwargs)
|
| 1360 |
+
|
| 1361 |
+
@auto_docstring
|
| 1362 |
+
def get_image_features(
|
| 1363 |
+
self,
|
| 1364 |
+
pixel_values: torch.FloatTensor,
|
| 1365 |
+
image_grid_thw: torch.LongTensor | None = None,
|
| 1366 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1367 |
+
) -> tuple | BaseModelOutputWithPooling:
|
| 1368 |
+
r"""
|
| 1369 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 1370 |
+
Images as patches.
|
| 1371 |
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
| 1372 |
+
Temporal / height / width extent of every image.
|
| 1373 |
+
"""
|
| 1374 |
+
return self.model.get_image_features(pixel_values, image_grid_thw, **kwargs)
|
| 1375 |
+
|
| 1376 |
+
@can_return_tuple
|
| 1377 |
+
def forward(
|
| 1378 |
+
self,
|
| 1379 |
+
input_ids: torch.LongTensor = None,
|
| 1380 |
+
attention_mask: torch.Tensor | None = None,
|
| 1381 |
+
position_ids: torch.LongTensor | None = None,
|
| 1382 |
+
past_key_values: Cache | None = None,
|
| 1383 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1384 |
+
labels: torch.LongTensor | None = None,
|
| 1385 |
+
pixel_values: torch.Tensor | None = None,
|
| 1386 |
+
pixel_values_videos: torch.FloatTensor | None = None,
|
| 1387 |
+
image_grid_thw: torch.LongTensor | None = None,
|
| 1388 |
+
video_grid_thw: torch.LongTensor | None = None,
|
| 1389 |
+
mm_token_type_ids: torch.IntTensor | None = None,
|
| 1390 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 1391 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1392 |
+
) -> tuple | AgnesCausalLMOutput:
|
| 1393 |
+
r"""
|
| 1394 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1395 |
+
Targets for the language-modelling loss; -100 marks ignored positions.
|
| 1396 |
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
| 1397 |
+
Temporal / height / width extent of every image.
|
| 1398 |
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
| 1399 |
+
Temporal / height / width extent of every video.
|
| 1400 |
+
"""
|
| 1401 |
+
out = self.model(
|
| 1402 |
+
input_ids=input_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos,
|
| 1403 |
+
image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, position_ids=position_ids,
|
| 1404 |
+
attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds,
|
| 1405 |
+
mm_token_type_ids=mm_token_type_ids, **kwargs,
|
| 1406 |
+
)
|
| 1407 |
+
keep = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1408 |
+
logits = self.lm_head(out[0][:, keep, :])
|
| 1409 |
+
loss = None
|
| 1410 |
+
if labels is not None:
|
| 1411 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
|
| 1412 |
+
return AgnesCausalLMOutput(
|
| 1413 |
+
loss=loss, logits=logits, past_key_values=out.past_key_values,
|
| 1414 |
+
hidden_states=out.hidden_states, attentions=out.attentions, rope_deltas=out.rope_deltas,
|
| 1415 |
+
)
|
| 1416 |
+
|
| 1417 |
+
def prepare_inputs_for_generation(
|
| 1418 |
+
self,
|
| 1419 |
+
input_ids,
|
| 1420 |
+
past_key_values=None,
|
| 1421 |
+
attention_mask=None,
|
| 1422 |
+
inputs_embeds=None,
|
| 1423 |
+
position_ids=None,
|
| 1424 |
+
use_cache=True,
|
| 1425 |
+
pixel_values=None,
|
| 1426 |
+
pixel_values_videos=None,
|
| 1427 |
+
image_grid_thw=None,
|
| 1428 |
+
video_grid_thw=None,
|
| 1429 |
+
is_first_iteration=False,
|
| 1430 |
+
**kwargs,
|
| 1431 |
+
):
|
| 1432 |
+
# pixels are consumed on the first step only; later steps run on the cache
|
| 1433 |
+
inputs = super().prepare_inputs_for_generation(
|
| 1434 |
+
input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds,
|
| 1435 |
+
position_ids=position_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos,
|
| 1436 |
+
image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, use_cache=use_cache,
|
| 1437 |
+
is_first_iteration=is_first_iteration, **kwargs,
|
| 1438 |
+
)
|
| 1439 |
+
if not is_first_iteration and use_cache:
|
| 1440 |
+
inputs["pixel_values"] = None
|
| 1441 |
+
inputs["pixel_values_videos"] = None
|
| 1442 |
+
return inputs
|
| 1443 |
+
|
| 1444 |
+
def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
|
| 1445 |
+
# four-row positions: text row on top of the three rotary axes
|
| 1446 |
+
text_pos = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
|
| 1447 |
+
|
| 1448 |
+
past_len = 0
|
| 1449 |
+
if (cache := model_kwargs.get("past_key_values")) is not None:
|
| 1450 |
+
past_len = cache.get_seq_length()
|
| 1451 |
+
if past_len != 0 and self.model.rope_deltas is not None:
|
| 1452 |
+
return text_pos[None, ...] + self.model.rope_deltas
|
| 1453 |
+
|
| 1454 |
+
if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
|
| 1455 |
+
inputs_tensor = model_kwargs["input_ids"]
|
| 1456 |
+
is_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
|
| 1457 |
+
has_vision = model_kwargs.get("image_grid_thw") is not None or model_kwargs.get("video_grid_thw") is not None
|
| 1458 |
+
if is_ids and model_kwargs.get("mm_token_type_ids") is not None and has_vision:
|
| 1459 |
+
rest = {k: v for k, v in model_kwargs.items() if k != "input_ids"}
|
| 1460 |
+
axes, self.model.rope_deltas = self.model.get_rope_index(inputs_tensor, **rest)
|
| 1461 |
+
else:
|
| 1462 |
+
axes = text_pos.unsqueeze(0).expand(3, -1, -1)
|
| 1463 |
+
self.model.rope_deltas = torch.zeros(inputs_tensor.shape[0], 1, dtype=torch.long, device=inputs_tensor.device)
|
| 1464 |
+
return torch.cat([text_pos[None, ...], axes], dim=0)
|
| 1465 |
+
|
| 1466 |
+
def _count_images_and_videos(
|
| 1467 |
+
self,
|
| 1468 |
+
input_ids: torch.LongTensor | None,
|
| 1469 |
+
inputs_embeds: torch.Tensor | None = None,
|
| 1470 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1471 |
+
"""Per-sample number of images and of video frames, read off the
|
| 1472 |
+
vision-start / placeholder tokens."""
|
| 1473 |
+
img_id = self.config.image_token_id
|
| 1474 |
+
vid_id = self.config.video_token_id
|
| 1475 |
+
start_id = self.config.vision_start_token_id
|
| 1476 |
+
if inputs_embeds is not None:
|
| 1477 |
+
embed = self.get_input_embeddings()
|
| 1478 |
+
dev = inputs_embeds.device
|
| 1479 |
+
start = (inputs_embeds == embed(torch.tensor(start_id, dtype=torch.long, device=dev)))[..., 0]
|
| 1480 |
+
img = (inputs_embeds == embed(torch.tensor(img_id, dtype=torch.long, device=dev)))[..., 0]
|
| 1481 |
+
vid = (inputs_embeds == embed(torch.tensor(vid_id, dtype=torch.long, device=dev)))[..., 0]
|
| 1482 |
+
else:
|
| 1483 |
+
start = input_ids == start_id
|
| 1484 |
+
img = input_ids == img_id
|
| 1485 |
+
vid = input_ids == vid_id
|
| 1486 |
+
after_start = torch.roll(start, shifts=1, dims=1)
|
| 1487 |
+
return torch.sum(after_start & img, dim=1), torch.sum(after_start & vid, dim=1)
|
| 1488 |
+
|
| 1489 |
+
def _expand_inputs_for_generation(
|
| 1490 |
+
self,
|
| 1491 |
+
expand_size: int = 1,
|
| 1492 |
+
is_encoder_decoder: bool = False,
|
| 1493 |
+
input_ids: torch.LongTensor | None = None,
|
| 1494 |
+
**model_kwargs,
|
| 1495 |
+
) -> tuple[torch.LongTensor, dict[str, Any]]:
|
| 1496 |
+
# visual tensors have no batch axis (they are concatenated over samples),
|
| 1497 |
+
# so they are expanded sample by sample using the per-sample counts
|
| 1498 |
+
if expand_size == 1:
|
| 1499 |
+
return input_ids, model_kwargs
|
| 1500 |
+
|
| 1501 |
+
visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"]
|
| 1502 |
+
|
| 1503 |
+
def expand_visual(d):
|
| 1504 |
+
image_grid_thw = model_kwargs.get("image_grid_thw", None)
|
| 1505 |
+
video_grid_thw = model_kwargs.get("video_grid_thw", None)
|
| 1506 |
+
n_img, n_vid = self._count_images_and_videos(input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None))
|
| 1507 |
+
|
| 1508 |
+
# n_vid counts frames (each frame carries a vision-start token); fold back to videos
|
| 1509 |
+
if video_grid_thw is not None:
|
| 1510 |
+
frame_cum = torch.cumsum(video_grid_thw[:, 0], dim=0)
|
| 1511 |
+
token_cum = torch.cumsum(n_vid, dim=0)
|
| 1512 |
+
edges = torch.searchsorted(frame_cum, token_cum)
|
| 1513 |
+
n_vid = torch.diff(torch.cat([-edges.new_ones(1), edges]))
|
| 1514 |
+
|
| 1515 |
+
def tile(x, lengths, times):
|
| 1516 |
+
parts = torch.split(x, lengths)
|
| 1517 |
+
reps = [times] + [1] * (x.dim() - 1)
|
| 1518 |
+
return torch.cat([p.repeat(*reps) for p in parts], dim=0)
|
| 1519 |
+
|
| 1520 |
+
for key in d:
|
| 1521 |
+
if key == "pixel_values":
|
| 1522 |
+
per = torch.split(image_grid_thw, list(n_img))
|
| 1523 |
+
d[key] = tile(d[key], [torch.prod(s, dim=1).sum() for s in per], expand_size)
|
| 1524 |
+
elif key == "image_grid_thw":
|
| 1525 |
+
d[key] = tile(d[key], list(n_img), expand_size)
|
| 1526 |
+
elif key == "pixel_values_videos":
|
| 1527 |
+
per = torch.split(video_grid_thw, list(n_vid))
|
| 1528 |
+
d[key] = tile(d[key], [torch.prod(s, dim=1).sum() for s in per], expand_size)
|
| 1529 |
+
elif key == "video_grid_thw":
|
| 1530 |
+
d[key] = tile(d[key], list(n_vid), expand_size)
|
| 1531 |
+
return d
|
| 1532 |
+
|
| 1533 |
+
def expand_rest(d):
|
| 1534 |
+
for key in d:
|
| 1535 |
+
if key == "position_ids" and d[key].ndim == 3:
|
| 1536 |
+
d[key] = d[key].repeat_interleave(expand_size, dim=1)
|
| 1537 |
+
elif d[key] is not None and isinstance(d[key], torch.Tensor) and key not in visual_keys:
|
| 1538 |
+
d[key] = d[key].repeat_interleave(expand_size, dim=0)
|
| 1539 |
+
return d
|
| 1540 |
+
|
| 1541 |
+
model_kwargs = expand_visual(model_kwargs)
|
| 1542 |
+
if input_ids is not None:
|
| 1543 |
+
input_ids = input_ids.repeat_interleave(expand_size, dim=0)
|
| 1544 |
+
model_kwargs = expand_rest(model_kwargs)
|
| 1545 |
+
if is_encoder_decoder:
|
| 1546 |
+
if model_kwargs.get("encoder_outputs") is None:
|
| 1547 |
+
raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
|
| 1548 |
+
model_kwargs["encoder_outputs"] = expand_rest(model_kwargs["encoder_outputs"])
|
| 1549 |
+
return input_ids, model_kwargs
|
| 1550 |
+
|
| 1551 |
+
|
| 1552 |
+
__all__ = [
|
| 1553 |
+
"AgnesPreTrainedModel",
|
| 1554 |
+
"AgnesVisionModel",
|
| 1555 |
+
"AgnesTextModel",
|
| 1556 |
+
"AgnesModel",
|
| 1557 |
+
"AgnesForCausalLM",
|
| 1558 |
+
"AgnesForConditionalGeneration",
|
| 1559 |
+
]
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"processor_class": "AgnesProcessor",
|
| 3 |
+
"image_processor_type": "AgnesImageProcessor",
|
| 4 |
+
"auto_map": {
|
| 5 |
+
"AutoProcessor": "processing_agnes.AgnesProcessor",
|
| 6 |
+
"AutoImageProcessor": "image_processing_agnes.AgnesImageProcessor"
|
| 7 |
+
},
|
| 8 |
+
"size": {
|
| 9 |
+
"longest_edge": 16777216,
|
| 10 |
+
"shortest_edge": 65536
|
| 11 |
+
},
|
| 12 |
+
"patch_size": 16,
|
| 13 |
+
"temporal_patch_size": 2,
|
| 14 |
+
"merge_size": 2,
|
| 15 |
+
"image_mean": [
|
| 16 |
+
0.5,
|
| 17 |
+
0.5,
|
| 18 |
+
0.5
|
| 19 |
+
],
|
| 20 |
+
"image_std": [
|
| 21 |
+
0.5,
|
| 22 |
+
0.5,
|
| 23 |
+
0.5
|
| 24 |
+
]
|
| 25 |
+
}
|
processing_agnes.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Agnes AI. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Processor for Agnes 3.0 Flash: tokenizer + image processor + video processor."""
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from transformers.processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin
|
| 19 |
+
from transformers.utils import auto_docstring, logging
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AgnesProcessorKwargs(ProcessingKwargs, total=False):
|
| 26 |
+
_defaults = {
|
| 27 |
+
"text_kwargs": {"padding": False, "return_token_type_ids": False, "return_mm_token_type_ids": True},
|
| 28 |
+
"videos_kwargs": {"return_metadata": True},
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@auto_docstring
|
| 33 |
+
class AgnesProcessor(ProcessorMixin):
|
| 34 |
+
valid_processor_kwargs = AgnesProcessorKwargs
|
| 35 |
+
|
| 36 |
+
def __init__(self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, **kwargs):
|
| 37 |
+
self.image_token = getattr(tokenizer, "image_token", "<|image_pad|>")
|
| 38 |
+
self.video_token = getattr(tokenizer, "video_token", "<|video_pad|>")
|
| 39 |
+
self.image_token_id = getattr(tokenizer, "image_token_id", None) or tokenizer.convert_tokens_to_ids(self.image_token)
|
| 40 |
+
self.video_token_id = getattr(tokenizer, "video_token_id", None) or tokenizer.convert_tokens_to_ids(self.video_token)
|
| 41 |
+
super().__init__(image_processor, tokenizer, video_processor, chat_template=chat_template)
|
| 42 |
+
self.vision_start_token = getattr(tokenizer, "vision_start_token", "<|vision_start|>")
|
| 43 |
+
self.vision_end_token = getattr(tokenizer, "vision_end_token", "<|vision_end|>")
|
| 44 |
+
self.vision_start_token_id = getattr(tokenizer, "vision_start_token_id", None) or tokenizer.convert_tokens_to_ids(
|
| 45 |
+
self.vision_start_token
|
| 46 |
+
)
|
| 47 |
+
self.vision_end_token_id = getattr(tokenizer, "vision_end_token_id", None) or tokenizer.convert_tokens_to_ids(
|
| 48 |
+
self.vision_end_token
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def replace_image_token(self, image_inputs: dict, image_idx: int) -> str:
|
| 52 |
+
per_token = self.image_processor.merge_size**2
|
| 53 |
+
n = image_inputs["image_grid_thw"][image_idx].prod() // per_token
|
| 54 |
+
return self.image_token * n
|
| 55 |
+
|
| 56 |
+
def replace_video_token(self, video_inputs: dict, video_idx: int) -> str:
|
| 57 |
+
per_token = self.video_processor.merge_size**2
|
| 58 |
+
thw = video_inputs["video_grid_thw"][video_idx]
|
| 59 |
+
n_frames = thw[0]
|
| 60 |
+
per_frame = thw[1:].prod() // per_token
|
| 61 |
+
meta = video_inputs["video_metadata"][video_idx]
|
| 62 |
+
if meta.fps is None:
|
| 63 |
+
logger.warning_once(
|
| 64 |
+
"Frame timestamps are needed to build the video prompt but the `fps` of the input video could not be "
|
| 65 |
+
"inferred (no `video_metadata`, pre-sampled frames?). Defaulting to `fps=24`."
|
| 66 |
+
)
|
| 67 |
+
meta.fps = 24 if meta.fps is None else meta.fps
|
| 68 |
+
stamps = self._frame_timestamps(meta.frames_indices, meta.fps, self.video_processor.temporal_patch_size)
|
| 69 |
+
text = ""
|
| 70 |
+
for f in range(n_frames):
|
| 71 |
+
text += f"<{stamps[f]:.1f} seconds>"
|
| 72 |
+
text += self.vision_start_token + self.video_token * per_frame + self.vision_end_token
|
| 73 |
+
return text
|
| 74 |
+
|
| 75 |
+
def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
|
| 76 |
+
"""Placeholder counts for inputs of the given sizes, without running the
|
| 77 |
+
processors on real pixels."""
|
| 78 |
+
data = {}
|
| 79 |
+
if image_sizes is not None:
|
| 80 |
+
ik = AgnesProcessorKwargs._defaults.get("images_kwargs", {})
|
| 81 |
+
ik.update(kwargs)
|
| 82 |
+
merge = ik.get("merge_size", None) or self.image_processor.merge_size
|
| 83 |
+
patches = [self.image_processor.get_number_of_image_patches(*s, ik) for s in image_sizes]
|
| 84 |
+
data.update({"num_image_tokens": [p // merge**2 for p in patches], "num_image_patches": patches})
|
| 85 |
+
if video_sizes is not None:
|
| 86 |
+
vk = AgnesProcessorKwargs._defaults.get("videos_kwargs", {})
|
| 87 |
+
vk.update(kwargs)
|
| 88 |
+
merge = vk.get("merge_size", None) or self.video_processor.merge_size
|
| 89 |
+
patches = [self.video_processor.get_number_of_video_patches(*s, vk) for s in video_sizes]
|
| 90 |
+
data["num_video_tokens"] = [p // merge**2 for p in patches]
|
| 91 |
+
return MultiModalData(**data)
|
| 92 |
+
|
| 93 |
+
def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs):
|
| 94 |
+
"""Decode generated ids to text."""
|
| 95 |
+
return self.tokenizer.batch_decode(
|
| 96 |
+
generated_outputs, skip_special_tokens=skip_special_tokens,
|
| 97 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def model_input_names(self):
|
| 102 |
+
return super().model_input_names + ["mm_token_type_ids"]
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def _frame_timestamps(indices: list[int] | np.ndarray, video_fps: float, merge_size: int = 2):
|
| 106 |
+
"""One timestamp per temporal patch: the mean of the first and last
|
| 107 |
+
frame time inside the patch."""
|
| 108 |
+
if not isinstance(indices, list):
|
| 109 |
+
indices = indices.tolist()
|
| 110 |
+
if len(indices) % merge_size != 0:
|
| 111 |
+
indices.extend(indices[-1] for _ in range(merge_size - len(indices) % merge_size))
|
| 112 |
+
times = [i / video_fps for i in indices]
|
| 113 |
+
return [(times[i] + times[i + merge_size - 1]) / 2 for i in range(0, len(times), merge_size)]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
__all__ = ["AgnesProcessor"]
|
serve.sh
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Serve Agnes 3.0 Flash with a stock sglang image.
|
| 3 |
+
#
|
| 4 |
+
# Tested image: lmsysorg/sglang:nightly-dev-20260908-20ca564b
|
| 5 |
+
#
|
| 6 |
+
# docker run --gpus all --shm-size 64g -p 30001:30002 \
|
| 7 |
+
# -v /path/to/agnes-3.0-flash:/model \
|
| 8 |
+
# lmsysorg/sglang:nightly-dev-20260908-20ca564b \
|
| 9 |
+
# bash /model/serve.sh [extra sglang arguments, e.g. --tp 2]
|
| 10 |
+
#
|
| 11 |
+
# The script overlays three files from sglang_patch/ onto the image's sglang
|
| 12 |
+
# package (a prebuilt variant when one matches the installed version, else
|
| 13 |
+
# apply_patch.py patches the installed files in place) and starts the server
|
| 14 |
+
# on port 30002 inside the container.
|
| 15 |
+
set -euo pipefail
|
| 16 |
+
D="$(cd "$(dirname "$0")" && pwd)"
|
| 17 |
+
PKG="$(python3 -c 'import sglang, os; print(os.path.dirname(sglang.__file__))')"
|
| 18 |
+
VER="$(python3 -c 'import sglang; print(getattr(sglang, "__version__", ""))' 2>/dev/null || true)"
|
| 19 |
+
|
| 20 |
+
case "$VER" in
|
| 21 |
+
*20ca564b*) VARIANT="nightly-dev-20260908-20ca564b" ;;
|
| 22 |
+
0.5.19*) VARIANT="v0.5.19" ;;
|
| 23 |
+
*) VARIANT="" ;;
|
| 24 |
+
esac
|
| 25 |
+
|
| 26 |
+
if [ -n "$VARIANT" ] && [ -d "$D/sglang_patch/$VARIANT/sglang" ]; then
|
| 27 |
+
echo "[serve.sh] sglang $VER -> prebuilt patch $VARIANT"
|
| 28 |
+
cp -r "$D/sglang_patch/$VARIANT/sglang/." "$PKG/"
|
| 29 |
+
else
|
| 30 |
+
echo "[serve.sh] sglang $VER -> patching installed package in place"
|
| 31 |
+
echo "This checkpoint requires the documented pinned SGLang image." >&2
|
| 32 |
+
exit 1
|
| 33 |
+
fi
|
| 34 |
+
|
| 35 |
+
export AGNES_MODEL_PATH="$D"
|
| 36 |
+
exec python3 -m sglang.launch_server --model-path "$D" --trust-remote-code --host 0.0.0.0 --port 8080 "$@"
|
sglang_patch/agnes_sglang_config.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agnes 3.0 Flash configuration for sglang.
|
| 2 |
+
#
|
| 3 |
+
# The HF checkpoint says model_type "agnes", names its layer types
|
| 4 |
+
# agnes_delta_attention / agnes_global_attention and carries a parallel FFN
|
| 5 |
+
# branch per layer. The server runs it on its built-in hybrid
|
| 6 |
+
# (delta-rule + global attention) implementation, so this class maps those
|
| 7 |
+
# onto the fields that implementation reads; the checkpoint's tensor names
|
| 8 |
+
# are translated while loading (see the model file patched by apply_patch.py).
|
| 9 |
+
from sglang.srt.configs.qwen3_5 import Qwen3_5Config
|
| 10 |
+
|
| 11 |
+
AGNES_DELTA = "agnes_delta_attention"
|
| 12 |
+
AGNES_GLOBAL = "agnes_global_attention"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AgnesConfig(Qwen3_5Config):
|
| 16 |
+
model_type = "agnes"
|
| 17 |
+
|
| 18 |
+
def __init__(self, text_config=None, vision_config=None, **kwargs):
|
| 19 |
+
kwargs.pop("auto_map", None) # the transformers remote code is not used in the server
|
| 20 |
+
if isinstance(text_config, dict):
|
| 21 |
+
text_config = dict(text_config)
|
| 22 |
+
text_config["model_type"] = "qwen3_5_text"
|
| 23 |
+
width = int(text_config.pop("parallel_ffn_intermediate_size", 0) or 0)
|
| 24 |
+
plan = text_config.pop("layer_types", None)
|
| 25 |
+
interval = text_config.pop("global_attention_interval", None)
|
| 26 |
+
if interval is None:
|
| 27 |
+
interval = text_config.pop("full_attention_interval", None)
|
| 28 |
+
if interval is None and plan:
|
| 29 |
+
interval = next(i + 1 for i, t in enumerate(plan) if t == AGNES_GLOBAL)
|
| 30 |
+
text_config["full_attention_interval"] = int(interval or 4)
|
| 31 |
+
main = int(text_config["intermediate_size"])
|
| 32 |
+
# the parallel branch is folded into the main MLP at load time
|
| 33 |
+
text_config["intermediate_size"] = main + width
|
| 34 |
+
text_config["agnes_main_intermediate_size"] = main
|
| 35 |
+
text_config["agnes_parallel_ffn_intermediate_size"] = width
|
| 36 |
+
if isinstance(vision_config, dict):
|
| 37 |
+
vision_config = dict(vision_config)
|
| 38 |
+
vision_config["model_type"] = "qwen3_5"
|
| 39 |
+
kwargs["architectures"] = ["Qwen3_5ForConditionalGeneration"]
|
| 40 |
+
super().__init__(text_config=text_config, vision_config=vision_config, **kwargs)
|
| 41 |
+
# every downstream check sees the built-in hybrid architecture
|
| 42 |
+
self.model_type = "qwen3_5"
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
|
| 46 |
+
# The weight loader needs the checkpoint directory to pick up the parallel
|
| 47 |
+
# branch tensors. The path is written into the config *dict* before the
|
| 48 |
+
# object is built: the config reaches the worker processes through a
|
| 49 |
+
# to_dict round trip, which keeps fields that came in through __init__
|
| 50 |
+
# and drops attributes set afterwards (from_pretrained's own kwargs only
|
| 51 |
+
# override known fields, so they cannot carry it either).
|
| 52 |
+
path = str(pretrained_model_name_or_path)
|
| 53 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 54 |
+
config_dict["agnes_model_path"] = path
|
| 55 |
+
if isinstance(config_dict.get("text_config"), dict):
|
| 56 |
+
config_dict["text_config"]["agnes_model_path"] = path
|
| 57 |
+
return cls.from_dict(config_dict, **kwargs)
|
sglang_patch/apply_patch.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Apply the Agnes patch to an sglang python package directory (the one that
|
| 3 |
+
contains `srt/`). Idempotent.
|
| 4 |
+
|
| 5 |
+
1. srt/configs/agnes.py new file
|
| 6 |
+
2. srt/utils/hf_transformers/common.py register AgnesConfig in _CONFIG_REGISTRY
|
| 7 |
+
3. srt/models/qwen3_5.py load_weights: translate the Agnes checkpoint
|
| 8 |
+
(tensor prefixes, parallel-FFN fold)
|
| 9 |
+
|
| 10 |
+
Usage: apply_patch.py <path/to/sglang> e.g. .../site-packages/sglang
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import shutil
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 18 |
+
MARK = "# === agnes ==="
|
| 19 |
+
|
| 20 |
+
TRANSLATE = '''
|
| 21 |
+
# === agnes ===
|
| 22 |
+
# Agnes 3.0 Flash checkpoints (config model_type "agnes") use their own tensor
|
| 23 |
+
# prefixes and carry a parallel FFN branch per layer. This generator sits at
|
| 24 |
+
# the top of the weight stream and turns it into what the implementation below
|
| 25 |
+
# expects: delta_attn -> linear_attn, global_attn -> self_attn, and the branch
|
| 26 |
+
# concatenated onto the main gate / up (dim 0) and down (dim 1) projections,
|
| 27 |
+
# matching the widened intermediate_size set by sglang.srt.configs.agnes.
|
| 28 |
+
import json as _agnes_json
|
| 29 |
+
import os as _agnes_os
|
| 30 |
+
import re as _agnes_re
|
| 31 |
+
|
| 32 |
+
_AGNES_MLP_RE = _agnes_re.compile(r"^(.*\\.layers\\.\\d+\\.mlp\\.)(gate_proj|up_proj|down_proj)\\.weight$")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _AgnesBranchReader:
|
| 36 |
+
def __init__(self, model_path):
|
| 37 |
+
from safetensors import safe_open
|
| 38 |
+
|
| 39 |
+
self._open = safe_open
|
| 40 |
+
self.path = model_path
|
| 41 |
+
index = _agnes_os.path.join(model_path, "model.safetensors.index.json")
|
| 42 |
+
self.weight_map = _agnes_json.load(open(index))["weight_map"]
|
| 43 |
+
self.handles = {}
|
| 44 |
+
|
| 45 |
+
def get(self, key):
|
| 46 |
+
fn = self.weight_map[key]
|
| 47 |
+
if fn not in self.handles:
|
| 48 |
+
self.handles[fn] = self._open(_agnes_os.path.join(self.path, fn), framework="pt", device="cpu")
|
| 49 |
+
return self.handles[fn].get_tensor(key)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _agnes_translate_weights(model, weights):
|
| 53 |
+
cfg = getattr(model.config, "text_config", None) or model.config
|
| 54 |
+
width = int(getattr(cfg, "agnes_parallel_ffn_intermediate_size", 0) or 0)
|
| 55 |
+
if width <= 0:
|
| 56 |
+
yield from weights
|
| 57 |
+
return
|
| 58 |
+
model_path = (
|
| 59 |
+
getattr(cfg, "agnes_model_path", None)
|
| 60 |
+
or getattr(model.config, "agnes_model_path", None)
|
| 61 |
+
or _agnes_os.environ.get("AGNES_MODEL_PATH")
|
| 62 |
+
or getattr(model.config, "_name_or_path", None)
|
| 63 |
+
)
|
| 64 |
+
if not model_path or not _agnes_os.path.isdir(model_path):
|
| 65 |
+
raise RuntimeError(
|
| 66 |
+
f"agnes: cannot locate the checkpoint directory (got {model_path!r}); "
|
| 67 |
+
"set AGNES_MODEL_PATH to the model directory"
|
| 68 |
+
)
|
| 69 |
+
reader = _AgnesBranchReader(model_path)
|
| 70 |
+
for name, w in weights:
|
| 71 |
+
if ".mlp.parallel_ffn." in name:
|
| 72 |
+
continue
|
| 73 |
+
m = _AGNES_MLP_RE.match(name)
|
| 74 |
+
if m and "visual" not in name and not name.startswith("mtp"):
|
| 75 |
+
extra = reader.get(f"{m.group(1)}parallel_ffn.{m.group(2)}.weight")
|
| 76 |
+
dim = 1 if m.group(2) == "down_proj" else 0
|
| 77 |
+
w = torch.cat([w, extra.to(device=w.device, dtype=w.dtype)], dim=dim)
|
| 78 |
+
name = name.replace(".delta_attn.", ".linear_attn.").replace(".global_attn.", ".self_attn.")
|
| 79 |
+
yield name, w
|
| 80 |
+
# === /agnes ===
|
| 81 |
+
|
| 82 |
+
'''
|
| 83 |
+
|
| 84 |
+
REGISTER = '''
|
| 85 |
+
# === agnes ===
|
| 86 |
+
from sglang.srt.configs.agnes import AgnesConfig as _AgnesConfig
|
| 87 |
+
|
| 88 |
+
_CONFIG_REGISTRY[_AgnesConfig.model_type] = _AgnesConfig
|
| 89 |
+
'''
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def patch_file(path, edit):
|
| 93 |
+
src = open(path, encoding="utf-8").read()
|
| 94 |
+
if MARK in src:
|
| 95 |
+
return "already patched"
|
| 96 |
+
out = edit(src)
|
| 97 |
+
if out is None:
|
| 98 |
+
raise SystemExit(f"anchor not found in {path}")
|
| 99 |
+
open(path, "w", encoding="utf-8").write(out)
|
| 100 |
+
return "patched"
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def edit_model_file(src):
|
| 104 |
+
anchor = "QWEN3_5_KV_SCALE_MAPPER = WeightsMapper("
|
| 105 |
+
hook = " weights = QWEN3_5_KV_SCALE_MAPPER.apply(weights)\n"
|
| 106 |
+
if anchor not in src or src.count(hook) < 1:
|
| 107 |
+
return None
|
| 108 |
+
src = src.replace(anchor, TRANSLATE + anchor, 1)
|
| 109 |
+
src = src.replace(hook, " weights = _agnes_translate_weights(self, weights)\n" + hook)
|
| 110 |
+
return src
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def main():
|
| 114 |
+
if len(sys.argv) != 2:
|
| 115 |
+
sys.exit(__doc__)
|
| 116 |
+
pkg = os.path.abspath(sys.argv[1])
|
| 117 |
+
srt = os.path.join(pkg, "srt")
|
| 118 |
+
if not os.path.isdir(srt):
|
| 119 |
+
sys.exit(f"{pkg} does not contain srt/")
|
| 120 |
+
dst = os.path.join(srt, "configs", "agnes.py")
|
| 121 |
+
shutil.copy2(os.path.join(HERE, "agnes_sglang_config.py"), dst)
|
| 122 |
+
print(f"configs/agnes.py: installed")
|
| 123 |
+
print("utils/hf_transformers/common.py:", patch_file(
|
| 124 |
+
os.path.join(srt, "utils", "hf_transformers", "common.py"), lambda s: s.rstrip("\n") + "\n" + REGISTER))
|
| 125 |
+
print("models/qwen3_5.py:", patch_file(os.path.join(srt, "models", "qwen3_5.py"), edit_model_file))
|
| 126 |
+
print("APPLY_PATCH_OK")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
main()
|
sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/configs/agnes.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agnes 3.0 Flash configuration for sglang.
|
| 2 |
+
#
|
| 3 |
+
# The HF checkpoint says model_type "agnes", names its layer types
|
| 4 |
+
# agnes_delta_attention / agnes_global_attention and carries a parallel FFN
|
| 5 |
+
# branch per layer. The server runs it on its built-in hybrid
|
| 6 |
+
# (delta-rule + global attention) implementation, so this class maps those
|
| 7 |
+
# onto the fields that implementation reads; the checkpoint's tensor names
|
| 8 |
+
# are translated while loading (see the model file patched by apply_patch.py).
|
| 9 |
+
from sglang.srt.configs.qwen3_5 import Qwen3_5Config
|
| 10 |
+
|
| 11 |
+
AGNES_DELTA = "agnes_delta_attention"
|
| 12 |
+
AGNES_GLOBAL = "agnes_global_attention"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AgnesConfig(Qwen3_5Config):
|
| 16 |
+
model_type = "agnes"
|
| 17 |
+
|
| 18 |
+
def __init__(self, text_config=None, vision_config=None, **kwargs):
|
| 19 |
+
kwargs.pop("auto_map", None) # the transformers remote code is not used in the server
|
| 20 |
+
if isinstance(text_config, dict):
|
| 21 |
+
text_config = dict(text_config)
|
| 22 |
+
text_config["model_type"] = "qwen3_5_text"
|
| 23 |
+
width = int(text_config.pop("parallel_ffn_intermediate_size", 0) or 0)
|
| 24 |
+
plan = text_config.pop("layer_types", None)
|
| 25 |
+
interval = text_config.pop("global_attention_interval", None)
|
| 26 |
+
if interval is None:
|
| 27 |
+
interval = text_config.pop("full_attention_interval", None)
|
| 28 |
+
if interval is None and plan:
|
| 29 |
+
interval = next(i + 1 for i, t in enumerate(plan) if t == AGNES_GLOBAL)
|
| 30 |
+
text_config["full_attention_interval"] = int(interval or 4)
|
| 31 |
+
main = int(text_config["intermediate_size"])
|
| 32 |
+
# the parallel branch is folded into the main MLP at load time
|
| 33 |
+
text_config["intermediate_size"] = main + width
|
| 34 |
+
text_config["agnes_main_intermediate_size"] = main
|
| 35 |
+
text_config["agnes_parallel_ffn_intermediate_size"] = width
|
| 36 |
+
if isinstance(vision_config, dict):
|
| 37 |
+
vision_config = dict(vision_config)
|
| 38 |
+
vision_config["model_type"] = "qwen3_5"
|
| 39 |
+
kwargs["architectures"] = ["Qwen3_5ForConditionalGeneration"]
|
| 40 |
+
super().__init__(text_config=text_config, vision_config=vision_config, **kwargs)
|
| 41 |
+
# every downstream check sees the built-in hybrid architecture
|
| 42 |
+
self.model_type = "qwen3_5"
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
|
| 46 |
+
# The weight loader needs the checkpoint directory to pick up the parallel
|
| 47 |
+
# branch tensors. The path is written into the config *dict* before the
|
| 48 |
+
# object is built: the config reaches the worker processes through a
|
| 49 |
+
# to_dict round trip, which keeps fields that came in through __init__
|
| 50 |
+
# and drops attributes set afterwards (from_pretrained's own kwargs only
|
| 51 |
+
# override known fields, so they cannot carry it either).
|
| 52 |
+
path = str(pretrained_model_name_or_path)
|
| 53 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 54 |
+
config_dict["agnes_model_path"] = path
|
| 55 |
+
if isinstance(config_dict.get("text_config"), dict):
|
| 56 |
+
config_dict["text_config"]["agnes_model_path"] = path
|
| 57 |
+
return cls.from_dict(config_dict, **kwargs)
|
sglang_patch/nightly-dev-20260908-20ca564b/sglang/srt/models/qwen3_5.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sglang_patch/nightly-dev-20260908-20ca564b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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-2024 SGLang Team
|
| 2 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 3 |
+
# you may not use this file except in compliance with the License.
|
| 4 |
+
# You may obtain a copy of the License at
|
| 5 |
+
#
|
| 6 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
#
|
| 8 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 9 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 10 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 11 |
+
# See the License for the specific language governing permissions and
|
| 12 |
+
# limitations under the License.
|
| 13 |
+
# ==============================================================================
|
| 14 |
+
"""Shared helpers used by config, tokenizer, and processor modules."""
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Dict, Optional, Type, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from huggingface_hub import snapshot_download
|
| 23 |
+
|
| 24 |
+
from sglang.srt.configs import (
|
| 25 |
+
AfmoeConfig,
|
| 26 |
+
BailingHybridConfig,
|
| 27 |
+
ChatGLMConfig,
|
| 28 |
+
Cosmos3Config,
|
| 29 |
+
Cosmos3EdgeConfig,
|
| 30 |
+
Cosmos3EdgeProjectorConfig,
|
| 31 |
+
Cosmos3EdgeTextConfig,
|
| 32 |
+
Cosmos3EdgeVisionConfig,
|
| 33 |
+
DbrxConfig,
|
| 34 |
+
DeepseekVL2Config,
|
| 35 |
+
Dots3Config,
|
| 36 |
+
DotsOCRConfig,
|
| 37 |
+
DotsVLMConfig,
|
| 38 |
+
ExaoneConfig,
|
| 39 |
+
FalconH1Config,
|
| 40 |
+
Glm5NextConfig,
|
| 41 |
+
Glm5NextTextConfig,
|
| 42 |
+
GraniteMoeHybridConfig,
|
| 43 |
+
HYV4Config,
|
| 44 |
+
InklingAudioConfig,
|
| 45 |
+
InklingMMConfig,
|
| 46 |
+
InklingModelConfig,
|
| 47 |
+
InklingVisionConfig,
|
| 48 |
+
InternS2MobiusConfig,
|
| 49 |
+
InternS2MobiusTextConfig,
|
| 50 |
+
InternS2PreviewConfig,
|
| 51 |
+
JetNemotronConfig,
|
| 52 |
+
JetVLMConfig,
|
| 53 |
+
K2HorizonConfig,
|
| 54 |
+
KimiK3Config,
|
| 55 |
+
KimiK25Config,
|
| 56 |
+
KimiLinearConfig,
|
| 57 |
+
KimiVLConfig,
|
| 58 |
+
LagunaConfig,
|
| 59 |
+
LocateAnythingConfig,
|
| 60 |
+
LongcatFlashConfig,
|
| 61 |
+
MiniCPMHybridConfig,
|
| 62 |
+
MiniCPMV4_6Config,
|
| 63 |
+
MiniCPMV4_6VisionConfig,
|
| 64 |
+
MiniMaxM3VLConfig,
|
| 65 |
+
MultiModalityConfig,
|
| 66 |
+
MuseGlimmerAssistantConfig,
|
| 67 |
+
MuseGlimmerConfig,
|
| 68 |
+
NanbeigeConfig,
|
| 69 |
+
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
| 70 |
+
NemotronH_Nano_VL_V2_Config,
|
| 71 |
+
NemotronHConfig,
|
| 72 |
+
NemotronHPuzzleConfig,
|
| 73 |
+
Olmo3Config,
|
| 74 |
+
Qwen3_5Config,
|
| 75 |
+
Qwen3_5MoeConfig,
|
| 76 |
+
Qwen3_5MoeTextConfig,
|
| 77 |
+
Qwen3_5TextConfig,
|
| 78 |
+
Qwen3NextConfig,
|
| 79 |
+
Spark2_5Config,
|
| 80 |
+
Step3p5Config,
|
| 81 |
+
Step3p7Config,
|
| 82 |
+
Step3VLConfig,
|
| 83 |
+
XllmConfig,
|
| 84 |
+
)
|
| 85 |
+
from sglang.srt.configs.deepseek_ocr import DeepseekVLV2Config
|
| 86 |
+
from sglang.srt.configs.internvl import InternVLChatConfig
|
| 87 |
+
from sglang.srt.utils import get_bool_env_var, logger, lru_cache_frozenset
|
| 88 |
+
from sglang.srt.utils.runai_utils import ObjectStorageModel, is_runai_obj_uri
|
| 89 |
+
|
| 90 |
+
from ..hf_transformers_patches import normalize_rope_scaling_compat
|
| 91 |
+
|
| 92 |
+
if get_bool_env_var("SGLANG_USE_MODELSCOPE"):
|
| 93 |
+
from modelscope import AutoConfig, GenerationConfig
|
| 94 |
+
else:
|
| 95 |
+
from transformers import AutoConfig, GenerationConfig
|
| 96 |
+
|
| 97 |
+
from transformers import PretrainedConfig
|
| 98 |
+
|
| 99 |
+
# ---------------------------------------------------------------------------
|
| 100 |
+
# Config registry
|
| 101 |
+
# ---------------------------------------------------------------------------
|
| 102 |
+
|
| 103 |
+
_CONFIG_REGISTRY: Dict[str, Type[PretrainedConfig]] = {
|
| 104 |
+
cls.model_type: cls
|
| 105 |
+
for cls in [
|
| 106 |
+
AfmoeConfig,
|
| 107 |
+
BailingHybridConfig,
|
| 108 |
+
ChatGLMConfig,
|
| 109 |
+
DbrxConfig,
|
| 110 |
+
ExaoneConfig,
|
| 111 |
+
DeepseekVL2Config,
|
| 112 |
+
MultiModalityConfig,
|
| 113 |
+
KimiVLConfig,
|
| 114 |
+
K2HorizonConfig,
|
| 115 |
+
LocateAnythingConfig,
|
| 116 |
+
InternVLChatConfig,
|
| 117 |
+
LagunaConfig,
|
| 118 |
+
Spark2_5Config,
|
| 119 |
+
Step3VLConfig,
|
| 120 |
+
LongcatFlashConfig,
|
| 121 |
+
Olmo3Config,
|
| 122 |
+
MuseGlimmerConfig,
|
| 123 |
+
MuseGlimmerAssistantConfig,
|
| 124 |
+
KimiK3Config,
|
| 125 |
+
Glm5NextConfig,
|
| 126 |
+
Glm5NextTextConfig,
|
| 127 |
+
KimiLinearConfig,
|
| 128 |
+
Qwen3NextConfig,
|
| 129 |
+
FalconH1Config,
|
| 130 |
+
GraniteMoeHybridConfig,
|
| 131 |
+
HYV4Config,
|
| 132 |
+
DotsVLMConfig,
|
| 133 |
+
DotsOCRConfig,
|
| 134 |
+
Dots3Config,
|
| 135 |
+
NemotronH_Nano_VL_V2_Config,
|
| 136 |
+
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
| 137 |
+
NemotronHConfig,
|
| 138 |
+
NemotronHPuzzleConfig,
|
| 139 |
+
NanbeigeConfig,
|
| 140 |
+
DeepseekVLV2Config,
|
| 141 |
+
Qwen3_5Config,
|
| 142 |
+
Qwen3_5MoeConfig,
|
| 143 |
+
Qwen3_5TextConfig,
|
| 144 |
+
Qwen3_5MoeTextConfig,
|
| 145 |
+
InternS2PreviewConfig,
|
| 146 |
+
InternS2MobiusConfig,
|
| 147 |
+
InternS2MobiusTextConfig,
|
| 148 |
+
JetNemotronConfig,
|
| 149 |
+
JetVLMConfig,
|
| 150 |
+
KimiK25Config,
|
| 151 |
+
Step3p5Config,
|
| 152 |
+
Step3p7Config,
|
| 153 |
+
MiniCPMHybridConfig,
|
| 154 |
+
MiniCPMV4_6Config,
|
| 155 |
+
MiniCPMV4_6VisionConfig,
|
| 156 |
+
InklingModelConfig,
|
| 157 |
+
InklingAudioConfig,
|
| 158 |
+
InklingVisionConfig,
|
| 159 |
+
InklingMMConfig,
|
| 160 |
+
MiniMaxM3VLConfig,
|
| 161 |
+
XllmConfig,
|
| 162 |
+
]
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# DeepSeek V3.2 / V4 reuse the V3 config schema. Subclass the upstream
|
| 167 |
+
# transformers class with each model_type so AutoConfig.register passes its
|
| 168 |
+
# consistency check (which requires class.model_type == registered key).
|
| 169 |
+
# Default-value divergences (e.g. V4's topk_group) are handled in
|
| 170 |
+
# model_config.py post-load.
|
| 171 |
+
try:
|
| 172 |
+
from transformers import DeepseekV3Config as _HFDeepseekV3Config
|
| 173 |
+
|
| 174 |
+
class _DeepseekV32ConfigAlias(_HFDeepseekV3Config):
|
| 175 |
+
model_type = "deepseek_v32"
|
| 176 |
+
|
| 177 |
+
class _DeepseekV4ConfigAlias(_HFDeepseekV3Config):
|
| 178 |
+
model_type = "deepseek_v4"
|
| 179 |
+
|
| 180 |
+
_CONFIG_REGISTRY["deepseek_v32"] = _DeepseekV32ConfigAlias
|
| 181 |
+
_CONFIG_REGISTRY["deepseek_v4"] = _DeepseekV4ConfigAlias
|
| 182 |
+
|
| 183 |
+
# For kimi_k25_eagle3
|
| 184 |
+
class _KimiK2ConfigAlias(_HFDeepseekV3Config):
|
| 185 |
+
model_type = "kimi_k2"
|
| 186 |
+
|
| 187 |
+
_CONFIG_REGISTRY["kimi_k2"] = _KimiK2ConfigAlias
|
| 188 |
+
except ImportError:
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
# Newer transformers versions (>=5.10.2) expose MellumConfig directly,
|
| 192 |
+
# but fallback to Qwen3MoeConfig for older versions.
|
| 193 |
+
try:
|
| 194 |
+
import transformers as _hf_transformers
|
| 195 |
+
|
| 196 |
+
_HFMellumConfig = getattr(_hf_transformers, "MellumConfig", None)
|
| 197 |
+
|
| 198 |
+
if _HFMellumConfig is not None:
|
| 199 |
+
_CONFIG_REGISTRY["mellum"] = _HFMellumConfig
|
| 200 |
+
else:
|
| 201 |
+
from transformers import Qwen3MoeConfig as _HFQwen3MoeConfig
|
| 202 |
+
|
| 203 |
+
class _MellumConfigAlias(_HFQwen3MoeConfig):
|
| 204 |
+
model_type = "mellum"
|
| 205 |
+
|
| 206 |
+
def __post_init__(self, **kwargs):
|
| 207 |
+
# Qwen3MoeConfig.__post_init__ wipes sliding_window unless
|
| 208 |
+
# use_sliding_window=True. Mellum gates sliding attention
|
| 209 |
+
# per-layer via layer_types, so preserve sliding_window
|
| 210 |
+
# regardless of the legacy use_sliding_window flag.
|
| 211 |
+
sliding_window = getattr(self, "sliding_window", None)
|
| 212 |
+
super().__post_init__(**kwargs)
|
| 213 |
+
self.sliding_window = sliding_window
|
| 214 |
+
|
| 215 |
+
_CONFIG_REGISTRY["mellum"] = _MellumConfigAlias
|
| 216 |
+
|
| 217 |
+
except ImportError:
|
| 218 |
+
pass
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
try:
|
| 222 |
+
from transformers import Gemma4Config as _HFGemma4Config
|
| 223 |
+
|
| 224 |
+
class _Gemma4UnifiedConfigAlias(_HFGemma4Config):
|
| 225 |
+
model_type = "gemma4_unified"
|
| 226 |
+
|
| 227 |
+
_CONFIG_REGISTRY["gemma4_unified"] = _Gemma4UnifiedConfigAlias
|
| 228 |
+
except ImportError:
|
| 229 |
+
pass
|
| 230 |
+
|
| 231 |
+
for name, cls in _CONFIG_REGISTRY.items():
|
| 232 |
+
try:
|
| 233 |
+
AutoConfig.register(name, cls)
|
| 234 |
+
except ValueError as e:
|
| 235 |
+
err = str(e).lower()
|
| 236 |
+
if "already registered" not in err and "already used" not in err:
|
| 237 |
+
logger.warning("Failed to register config %s: %s", name, e)
|
| 238 |
+
|
| 239 |
+
# Cosmos3 (understanding tower) reuses the Qwen3-VL config schema. Register it
|
| 240 |
+
# with AutoConfig only (not `_CONFIG_REGISTRY`), so the nested `text_config` is
|
| 241 |
+
# flattened onto the top-level config in `get_config` — the same path the base
|
| 242 |
+
# Qwen3-VL config relies on. Adding it to `_CONFIG_REGISTRY` would trigger a
|
| 243 |
+
# `from_pretrained` reload that drops that flattening.
|
| 244 |
+
try:
|
| 245 |
+
AutoConfig.register(Cosmos3Config.model_type, Cosmos3Config)
|
| 246 |
+
except ValueError as e:
|
| 247 |
+
err = str(e).lower()
|
| 248 |
+
if "already registered" not in err and "already used" not in err:
|
| 249 |
+
logger.warning("Failed to register config %s: %s", Cosmos3Config.model_type, e)
|
| 250 |
+
|
| 251 |
+
# Cosmos3-Edge native text support starts from the checkpoint root config, then
|
| 252 |
+
# consumes ``text_config`` in ``sglang.srt.models.cosmos3_edge``. Keep it out of
|
| 253 |
+
# `_CONFIG_REGISTRY` so the generic parser can flatten text attributes onto the
|
| 254 |
+
# root config after `AutoConfig.from_pretrained`, matching other multimodal
|
| 255 |
+
# configs that use a text sub-config.
|
| 256 |
+
for _cosmos3_edge_config_cls in (
|
| 257 |
+
Cosmos3EdgeTextConfig,
|
| 258 |
+
Cosmos3EdgeVisionConfig,
|
| 259 |
+
Cosmos3EdgeProjectorConfig,
|
| 260 |
+
Cosmos3EdgeConfig,
|
| 261 |
+
):
|
| 262 |
+
try:
|
| 263 |
+
AutoConfig.register(
|
| 264 |
+
_cosmos3_edge_config_cls.model_type, _cosmos3_edge_config_cls
|
| 265 |
+
)
|
| 266 |
+
except ValueError as e:
|
| 267 |
+
err = str(e).lower()
|
| 268 |
+
if "already registered" not in err and "already used" not in err:
|
| 269 |
+
logger.warning(
|
| 270 |
+
"Failed to register config %s: %s",
|
| 271 |
+
_cosmos3_edge_config_cls.model_type,
|
| 272 |
+
e,
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ---------------------------------------------------------------------------
|
| 277 |
+
# Download / path helpers
|
| 278 |
+
# ---------------------------------------------------------------------------
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def download_from_hf(
|
| 282 |
+
model_path: str,
|
| 283 |
+
allow_patterns: Optional[Union[str, list]] = None,
|
| 284 |
+
):
|
| 285 |
+
if os.path.exists(model_path):
|
| 286 |
+
return model_path
|
| 287 |
+
|
| 288 |
+
if not allow_patterns:
|
| 289 |
+
allow_patterns = ["*.json", "*.bin", "*.model"]
|
| 290 |
+
|
| 291 |
+
return snapshot_download(model_path, allow_patterns=allow_patterns)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def resolve_runai_obj_uri(model_name_or_path: str) -> str:
|
| 295 |
+
if is_runai_obj_uri(model_name_or_path):
|
| 296 |
+
return ObjectStorageModel.get_path(model_name_or_path)
|
| 297 |
+
return model_name_or_path
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _resolve_local_or_cached_file(model_name_or_path, filename, revision=None):
|
| 301 |
+
"""Resolve a file from a local directory or HF hub cache (no network)."""
|
| 302 |
+
local_path = Path(model_name_or_path) / filename
|
| 303 |
+
if local_path.is_file():
|
| 304 |
+
return str(local_path)
|
| 305 |
+
from huggingface_hub import hf_hub_download
|
| 306 |
+
|
| 307 |
+
return hf_hub_download(
|
| 308 |
+
model_name_or_path, filename, revision=revision, local_files_only=True
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _cached_file_exists(model_name_or_path, filename, revision=None) -> bool:
|
| 313 |
+
"""Whether *filename* is available locally or in the HF cache (no network)."""
|
| 314 |
+
try:
|
| 315 |
+
_resolve_local_or_cached_file(model_name_or_path, filename, revision)
|
| 316 |
+
return True
|
| 317 |
+
except Exception:
|
| 318 |
+
return False
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _remote_file_exists(repo_id, filename, revision=None) -> bool:
|
| 322 |
+
"""Whether *filename* exists on the HF hub (HEAD request only, no download).
|
| 323 |
+
|
| 324 |
+
Returns False on any error (offline, gated, network, invalid id) so callers
|
| 325 |
+
fall back to their default path instead of crashing.
|
| 326 |
+
"""
|
| 327 |
+
from huggingface_hub.constants import HF_HUB_OFFLINE
|
| 328 |
+
|
| 329 |
+
if HF_HUB_OFFLINE:
|
| 330 |
+
return False
|
| 331 |
+
try:
|
| 332 |
+
from huggingface_hub import HfApi
|
| 333 |
+
|
| 334 |
+
return HfApi().file_exists(repo_id, filename, revision=revision)
|
| 335 |
+
except Exception:
|
| 336 |
+
return False
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def check_gguf_file(model: Union[str, os.PathLike]) -> bool:
|
| 340 |
+
model = Path(model)
|
| 341 |
+
if not model.is_file():
|
| 342 |
+
return False
|
| 343 |
+
elif model.suffix == ".gguf":
|
| 344 |
+
return True
|
| 345 |
+
|
| 346 |
+
with open(model, "rb") as f:
|
| 347 |
+
header = f.read(4)
|
| 348 |
+
return header == b"GGUF"
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def resolve_hf_gguf_reference(
|
| 352 |
+
model: str, revision: Optional[str] = None
|
| 353 |
+
) -> Optional[str]:
|
| 354 |
+
"""Download a .gguf named by Hub reference and return its local path.
|
| 355 |
+
|
| 356 |
+
owner/repo/path/inside/repo.gguf -> exactly that file
|
| 357 |
+
owner/repo:QUANT_TYPE -> the only matching quantization
|
| 358 |
+
owner/repo -> the only .gguf in the repo
|
| 359 |
+
"""
|
| 360 |
+
from sglang.srt.utils import is_remote_url
|
| 361 |
+
|
| 362 |
+
if not model or os.path.exists(model) or is_remote_url(model):
|
| 363 |
+
return None
|
| 364 |
+
|
| 365 |
+
from huggingface_hub import hf_hub_download
|
| 366 |
+
|
| 367 |
+
if ":" in model:
|
| 368 |
+
repo_id, _, quant_type = model.rpartition(":")
|
| 369 |
+
if repo_id.count("/") != 1 or not quant_type:
|
| 370 |
+
return None
|
| 371 |
+
|
| 372 |
+
from huggingface_hub import HfApi
|
| 373 |
+
|
| 374 |
+
files = [
|
| 375 |
+
sibling.rfilename
|
| 376 |
+
for sibling in HfApi().repo_info(repo_id, revision=revision).siblings
|
| 377 |
+
]
|
| 378 |
+
suffix = f"-{quant_type}.gguf"
|
| 379 |
+
candidates = [filename for filename in files if filename.endswith(suffix)]
|
| 380 |
+
if not candidates:
|
| 381 |
+
available = sorted(
|
| 382 |
+
filename for filename in files if filename.endswith(".gguf")
|
| 383 |
+
)
|
| 384 |
+
raise ValueError(
|
| 385 |
+
f"No file matching quant type {quant_type!r} in {repo_id}. "
|
| 386 |
+
f"Available GGUF files: {available}"
|
| 387 |
+
)
|
| 388 |
+
if len(candidates) > 1:
|
| 389 |
+
raise ValueError(
|
| 390 |
+
f"Quant type {quant_type!r} is ambiguous in {repo_id}: "
|
| 391 |
+
f"{sorted(candidates)}. Pass the full owner/repo/path/file.gguf "
|
| 392 |
+
"reference instead."
|
| 393 |
+
)
|
| 394 |
+
return hf_hub_download(repo_id, candidates[0], revision=revision)
|
| 395 |
+
|
| 396 |
+
parts = model.strip("/").split("/")
|
| 397 |
+
if len(parts) < 2:
|
| 398 |
+
return None
|
| 399 |
+
|
| 400 |
+
if len(parts) > 2 and model.endswith(".gguf"):
|
| 401 |
+
repo_id = "/".join(parts[:2])
|
| 402 |
+
filename = "/".join(parts[2:])
|
| 403 |
+
return hf_hub_download(repo_id, filename, revision=revision)
|
| 404 |
+
|
| 405 |
+
if len(parts) != 2:
|
| 406 |
+
return None
|
| 407 |
+
|
| 408 |
+
from huggingface_hub import HfApi
|
| 409 |
+
|
| 410 |
+
try:
|
| 411 |
+
files = [
|
| 412 |
+
s.rfilename for s in HfApi().repo_info(model, revision=revision).siblings
|
| 413 |
+
]
|
| 414 |
+
except Exception:
|
| 415 |
+
return None
|
| 416 |
+
if any(f == "config.json" for f in files):
|
| 417 |
+
return None
|
| 418 |
+
|
| 419 |
+
candidates = [f for f in files if f.endswith(".gguf")]
|
| 420 |
+
if not candidates:
|
| 421 |
+
return None
|
| 422 |
+
if len(candidates) > 1:
|
| 423 |
+
listing = "\n ".join(f"{model}/{f}" for f in sorted(candidates))
|
| 424 |
+
raise ValueError(
|
| 425 |
+
f"{model} contains {len(candidates)} .gguf files; name the one to "
|
| 426 |
+
f"serve:\n {listing}"
|
| 427 |
+
)
|
| 428 |
+
return hf_hub_download(model, candidates[0], revision=revision)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def gguf_sidecar_dir(
|
| 432 |
+
gguf_path: Union[str, os.PathLike], sentinel: str
|
| 433 |
+
) -> Optional[Path]:
|
| 434 |
+
"""Directory containing *sentinel* next to a .gguf file, if there is one."""
|
| 435 |
+
directory = Path(gguf_path).parent
|
| 436 |
+
return directory if (directory / sentinel).is_file() else None
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# ---------------------------------------------------------------------------
|
| 440 |
+
# Rope / text config helpers
|
| 441 |
+
# ---------------------------------------------------------------------------
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def get_rope_config(config):
|
| 445 |
+
"""Get (rope_theta, rope_params) from config, supporting both v4 and v5.
|
| 446 |
+
|
| 447 |
+
Trust-remote-code configs or parent configs passed to sub-models may not
|
| 448 |
+
have the v5 ``rope_parameters`` property, so we fall back to the v4-style
|
| 449 |
+
``config.rope_theta`` / ``config.rope_scaling`` attributes.
|
| 450 |
+
|
| 451 |
+
Returns:
|
| 452 |
+
(rope_theta, rope_params): In v5, rope_params is the full
|
| 453 |
+
rope_parameters dict (which subsumes rope_scaling and includes
|
| 454 |
+
rope_theta). In v4, rope_params is the rope_scaling dict or None.
|
| 455 |
+
"""
|
| 456 |
+
rope_params = getattr(config, "rope_parameters", None)
|
| 457 |
+
if rope_params is not None:
|
| 458 |
+
rope_theta = rope_params.get("rope_theta", getattr(config, "rope_theta", 10000))
|
| 459 |
+
return rope_theta, rope_params
|
| 460 |
+
return getattr(config, "rope_theta", 10000), getattr(config, "rope_scaling", None)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def _patch_text_config(parent_config: PretrainedConfig, text_config):
|
| 464 |
+
"""Synchronize standard attributes between parent config and text sub-config.
|
| 465 |
+
|
| 466 |
+
In transformers v5, the "untangle config" refactor removed automatic
|
| 467 |
+
inheritance of top-level PretrainedConfig attributes (pad_token_id,
|
| 468 |
+
tie_word_embeddings, etc.) from sub-configs. Downstream code expects
|
| 469 |
+
these attributes to be present on both configs (some models pass the
|
| 470 |
+
parent directly to the language model, others pass the text sub-config),
|
| 471 |
+
so we propagate in both directions when an attribute is missing.
|
| 472 |
+
(See https://github.com/huggingface/transformers/pull/41541)
|
| 473 |
+
"""
|
| 474 |
+
_ATTRS_TO_PROPAGATE = [
|
| 475 |
+
"pad_token_id",
|
| 476 |
+
"bos_token_id",
|
| 477 |
+
"eos_token_id",
|
| 478 |
+
"tie_word_embeddings",
|
| 479 |
+
]
|
| 480 |
+
for attr in _ATTRS_TO_PROPAGATE:
|
| 481 |
+
parent_has = hasattr(parent_config, attr)
|
| 482 |
+
text_has = hasattr(text_config, attr)
|
| 483 |
+
if parent_has and not text_has:
|
| 484 |
+
setattr(text_config, attr, getattr(parent_config, attr))
|
| 485 |
+
elif text_has and not parent_has:
|
| 486 |
+
setattr(parent_config, attr, getattr(text_config, attr))
|
| 487 |
+
return text_config
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def get_hf_text_config(config: PretrainedConfig):
|
| 491 |
+
"""Get the "sub" config relevant to llm for multi modal models.
|
| 492 |
+
No op for pure text models.
|
| 493 |
+
"""
|
| 494 |
+
if config.architectures is not None:
|
| 495 |
+
class_name = config.architectures[0]
|
| 496 |
+
if class_name.startswith("Llava") and class_name.endswith("ForCausalLM"):
|
| 497 |
+
# We support non-hf version of llava models, so we do not want to
|
| 498 |
+
# read the wrong values from the unused default text_config.
|
| 499 |
+
# NOTE(HandH1998): We set `torch_dtype` of config to `torch.float16` for the weights, as
|
| 500 |
+
# `torch.float16` is default used for image features in `python/sglang/srt/models/llava.py`.
|
| 501 |
+
setattr(config, "dtype", torch.float16)
|
| 502 |
+
return config
|
| 503 |
+
|
| 504 |
+
text_config = None
|
| 505 |
+
|
| 506 |
+
# Some models (e.g. DeepSeek-OCR) store sub-configs as plain dicts.
|
| 507 |
+
# Convert to PretrainedConfig early so hasattr() checks and asserts work.
|
| 508 |
+
parent_dtype = getattr(config, "dtype", None)
|
| 509 |
+
for _attr in ("text_config", "llm_config", "language_config", "thinker_config"):
|
| 510 |
+
_sub = getattr(config, _attr, None)
|
| 511 |
+
if isinstance(_sub, dict):
|
| 512 |
+
_converted = PretrainedConfig(**_sub)
|
| 513 |
+
if getattr(_converted, "dtype", None) is None and parent_dtype is not None:
|
| 514 |
+
_converted.dtype = parent_dtype
|
| 515 |
+
setattr(config, _attr, _converted)
|
| 516 |
+
elif _sub is not None and parent_dtype is not None:
|
| 517 |
+
# transformers v5 multimodal configs (e.g. Mistral3Config) carry
|
| 518 |
+
# `dtype` only on the top-level config, leaving the sub-configs at
|
| 519 |
+
# None. Without this, _get_and_verify_dtype falls back to float32
|
| 520 |
+
# and then "auto" downcasts to float16, which overflows the Pixtral
|
| 521 |
+
# vision tower on real images and produces NaN features.
|
| 522 |
+
if getattr(_sub, "dtype", None) is None:
|
| 523 |
+
_sub.dtype = parent_dtype
|
| 524 |
+
|
| 525 |
+
# Priority: thinker_config > llm_config > language_config > text_config
|
| 526 |
+
if hasattr(config, "thinker_config"):
|
| 527 |
+
# qwen2.5 omni
|
| 528 |
+
thinker_config = config.thinker_config
|
| 529 |
+
if hasattr(thinker_config, "text_config"):
|
| 530 |
+
setattr(
|
| 531 |
+
thinker_config.text_config,
|
| 532 |
+
"dtype",
|
| 533 |
+
getattr(thinker_config, "dtype", None),
|
| 534 |
+
)
|
| 535 |
+
text_config = thinker_config.text_config
|
| 536 |
+
else:
|
| 537 |
+
text_config = thinker_config
|
| 538 |
+
elif hasattr(config, "llm_config"):
|
| 539 |
+
# PointsV1.5 Chat Model
|
| 540 |
+
assert hasattr(config.llm_config, "num_attention_heads")
|
| 541 |
+
text_config = config.llm_config
|
| 542 |
+
elif hasattr(config, "language_config"):
|
| 543 |
+
text_config = config.language_config
|
| 544 |
+
elif hasattr(config, "text_config"):
|
| 545 |
+
# The code operates under the assumption that text_config should have
|
| 546 |
+
# `num_attention_heads` (among others). Assert here to fail early
|
| 547 |
+
# if transformers config doesn't align with this assumption.
|
| 548 |
+
assert hasattr(config.text_config, "num_attention_heads")
|
| 549 |
+
text_config = config.text_config
|
| 550 |
+
|
| 551 |
+
# Ensure rope_scaling dicts have "type" for remote-code compat (v5).
|
| 552 |
+
normalize_rope_scaling_compat(config)
|
| 553 |
+
|
| 554 |
+
if text_config is not None:
|
| 555 |
+
return _patch_text_config(config, text_config)
|
| 556 |
+
return config
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
# ---------------------------------------------------------------------------
|
| 560 |
+
# Model-specific helpers
|
| 561 |
+
# ---------------------------------------------------------------------------
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def _ensure_sub_configs(config: PretrainedConfig, *attr_names: str) -> None:
|
| 565 |
+
"""Convert dict-valued sub-configs to proper AutoConfig objects in-place."""
|
| 566 |
+
for attr in attr_names:
|
| 567 |
+
sub = getattr(config, attr, None)
|
| 568 |
+
if sub is not None and isinstance(sub, dict):
|
| 569 |
+
setattr(config, attr, AutoConfig.for_model(**sub))
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def _is_deepseek_ocr_model(config: PretrainedConfig) -> bool:
|
| 573 |
+
# TODO: Remove this workaround once AutoConfig correctly identifies deepseek-ocr.
|
| 574 |
+
# Hugging Face's AutoConfig currently misidentifies it as deepseekvl2.
|
| 575 |
+
auto_map = getattr(config, "auto_map", None) or {}
|
| 576 |
+
return auto_map.get("AutoModel") == "modeling_deepseekocr.DeepseekOCRForCausalLM"
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def _is_deepseek_ocr2_model(config: PretrainedConfig) -> bool:
|
| 580 |
+
auto_map = getattr(config, "auto_map", None) or {}
|
| 581 |
+
return auto_map.get("AutoModel") == "modeling_deepseekocr2.DeepseekOCR2ForCausalLM"
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def _override_v_head_dim_if_zero(config: PretrainedConfig, patch: int = 128) -> None:
|
| 585 |
+
patched = False
|
| 586 |
+
for attr in ("text_config", "language_config"):
|
| 587 |
+
sub = getattr(config, attr, None)
|
| 588 |
+
if sub is None:
|
| 589 |
+
continue
|
| 590 |
+
if isinstance(sub, dict):
|
| 591 |
+
if sub.get("v_head_dim") == 0:
|
| 592 |
+
sub["v_head_dim"] = patch
|
| 593 |
+
patched = True
|
| 594 |
+
elif getattr(sub, "v_head_dim", None) == 0:
|
| 595 |
+
sub.v_head_dim = patch
|
| 596 |
+
patched = True
|
| 597 |
+
if patched:
|
| 598 |
+
logger.warning(
|
| 599 |
+
f"Overriding v_head_dim from 0 to {patch} to avoid potential issues."
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
# ---------------------------------------------------------------------------
|
| 604 |
+
# Context length / generation config / sparse attention
|
| 605 |
+
# ---------------------------------------------------------------------------
|
| 606 |
+
|
| 607 |
+
# Models don't use the same configuration key for determining the maximum
|
| 608 |
+
# context length. Store them here so we can sanely check them.
|
| 609 |
+
# NOTE: The ordering here is important. Some models have two of these and we
|
| 610 |
+
# have a preference for which value gets used.
|
| 611 |
+
CONTEXT_LENGTH_KEYS = [
|
| 612 |
+
"max_sequence_length",
|
| 613 |
+
"seq_length",
|
| 614 |
+
"max_seq_len",
|
| 615 |
+
"model_max_length",
|
| 616 |
+
"max_position_embeddings",
|
| 617 |
+
]
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def get_context_length(config):
|
| 621 |
+
"""Get the context length of a model from a huggingface model configs."""
|
| 622 |
+
text_config = config
|
| 623 |
+
rope_scaling = getattr(text_config, "rope_scaling", None)
|
| 624 |
+
if rope_scaling:
|
| 625 |
+
rope_scaling_factor = rope_scaling.get("factor", 1)
|
| 626 |
+
if "original_max_position_embeddings" in rope_scaling:
|
| 627 |
+
rope_scaling_factor = 1
|
| 628 |
+
if rope_scaling.get("rope_type", None) == "llama3":
|
| 629 |
+
rope_scaling_factor = 1
|
| 630 |
+
else:
|
| 631 |
+
rope_scaling_factor = 1
|
| 632 |
+
|
| 633 |
+
for key in CONTEXT_LENGTH_KEYS:
|
| 634 |
+
val = getattr(text_config, key, None)
|
| 635 |
+
if val is not None:
|
| 636 |
+
return int(rope_scaling_factor * val)
|
| 637 |
+
return 2048
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
@lru_cache_frozenset(maxsize=32)
|
| 641 |
+
def get_generation_config(
|
| 642 |
+
model: str,
|
| 643 |
+
trust_remote_code: bool,
|
| 644 |
+
revision: Optional[str] = None,
|
| 645 |
+
**kwargs,
|
| 646 |
+
):
|
| 647 |
+
if check_gguf_file(model):
|
| 648 |
+
sidecar = gguf_sidecar_dir(model, "generation_config.json")
|
| 649 |
+
if sidecar is not None:
|
| 650 |
+
model = str(sidecar)
|
| 651 |
+
else:
|
| 652 |
+
from .gguf_native import (
|
| 653 |
+
build_gguf_generation_config,
|
| 654 |
+
has_native_gguf_support,
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
if has_native_gguf_support(model):
|
| 658 |
+
return build_gguf_generation_config(model)
|
| 659 |
+
|
| 660 |
+
try:
|
| 661 |
+
return GenerationConfig.from_pretrained(
|
| 662 |
+
model, trust_remote_code=trust_remote_code, revision=revision, **kwargs
|
| 663 |
+
)
|
| 664 |
+
except (FileNotFoundError, OSError) as e:
|
| 665 |
+
# A missing generation_config.json is normal for many checkpoints and
|
| 666 |
+
# is surfaced by HF as a generic OSError (not FileNotFoundError). Treat
|
| 667 |
+
# it as benign — proceed without a generation config, at DEBUG level so
|
| 668 |
+
# normal startup logs stay quiet.
|
| 669 |
+
logger.debug(
|
| 670 |
+
"No generation config for %s: %s. Proceeding without it.",
|
| 671 |
+
model,
|
| 672 |
+
e,
|
| 673 |
+
)
|
| 674 |
+
return None
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
# Qwen-1M related
|
| 678 |
+
def get_sparse_attention_config(
|
| 679 |
+
model: str,
|
| 680 |
+
sparse_attention_config_filename: str = "sparse_attention_config.json",
|
| 681 |
+
) -> Dict[str, Any]:
|
| 682 |
+
is_local = os.path.isdir(model)
|
| 683 |
+
if not is_local:
|
| 684 |
+
model = download_from_hf(model, allow_patterns=["*.json"])
|
| 685 |
+
|
| 686 |
+
config_file = os.path.join(model, sparse_attention_config_filename)
|
| 687 |
+
if not os.path.exists(config_file):
|
| 688 |
+
return {}
|
| 689 |
+
|
| 690 |
+
with open(config_file) as f:
|
| 691 |
+
config = json.load(f)
|
| 692 |
+
return config
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
# ---------------------------------------------------------------------------
|
| 696 |
+
# Tokenizer / processor helpers
|
| 697 |
+
# ---------------------------------------------------------------------------
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
# Some models don't have an available processor, e.g.: InternVL
|
| 701 |
+
def get_tokenizer_from_processor(processor):
|
| 702 |
+
from transformers import PreTrainedTokenizerBase
|
| 703 |
+
|
| 704 |
+
if isinstance(processor, PreTrainedTokenizerBase):
|
| 705 |
+
return processor
|
| 706 |
+
return processor.tokenizer
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
# Turn-final markers that some checkpoints ship without EOS metadata:
|
| 710 |
+
# <|eom_id|> (Llama-3 tool use), <|content_model_end_sampling|> (Inkling,
|
| 711 |
+
# whose bundled tokenizer config leaves eos_token unset), and
|
| 712 |
+
# <|ifm|im_end|> (some K2 Horizon checkpoints, notably 0.9B, name only
|
| 713 |
+
# <|endoftext|> as EOS).
|
| 714 |
+
_ADDITIONAL_STOP_TOKEN_TEXTS = (
|
| 715 |
+
"<|eom_id|>",
|
| 716 |
+
"<|content_model_end_sampling|>",
|
| 717 |
+
"<|ifm|im_end|>",
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def attach_additional_stop_token_ids(tokenizer):
|
| 722 |
+
added = tokenizer.get_added_vocab()
|
| 723 |
+
stop_ids = {added[text] for text in _ADDITIONAL_STOP_TOKEN_TEXTS if text in added}
|
| 724 |
+
tokenizer.additional_stop_token_ids = stop_ids or None
|
| 725 |
+
|
| 726 |
+
# === agnes ===
|
| 727 |
+
from sglang.srt.configs.agnes import AgnesConfig as _AgnesConfig
|
| 728 |
+
|
| 729 |
+
_CONFIG_REGISTRY[_AgnesConfig.model_type] = _AgnesConfig
|
sglang_patch/v0.5.19/sglang/srt/configs/agnes.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agnes 3.0 Flash configuration for sglang.
|
| 2 |
+
#
|
| 3 |
+
# The HF checkpoint says model_type "agnes", names its layer types
|
| 4 |
+
# agnes_delta_attention / agnes_global_attention and carries a parallel FFN
|
| 5 |
+
# branch per layer. The server runs it on its built-in hybrid
|
| 6 |
+
# (delta-rule + global attention) implementation, so this class maps those
|
| 7 |
+
# onto the fields that implementation reads; the checkpoint's tensor names
|
| 8 |
+
# are translated while loading (see the model file patched by apply_patch.py).
|
| 9 |
+
from sglang.srt.configs.qwen3_5 import Qwen3_5Config
|
| 10 |
+
|
| 11 |
+
AGNES_DELTA = "agnes_delta_attention"
|
| 12 |
+
AGNES_GLOBAL = "agnes_global_attention"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AgnesConfig(Qwen3_5Config):
|
| 16 |
+
model_type = "agnes"
|
| 17 |
+
|
| 18 |
+
def __init__(self, text_config=None, vision_config=None, **kwargs):
|
| 19 |
+
kwargs.pop("auto_map", None) # the transformers remote code is not used in the server
|
| 20 |
+
if isinstance(text_config, dict):
|
| 21 |
+
text_config = dict(text_config)
|
| 22 |
+
text_config["model_type"] = "qwen3_5_text"
|
| 23 |
+
width = int(text_config.pop("parallel_ffn_intermediate_size", 0) or 0)
|
| 24 |
+
plan = text_config.pop("layer_types", None)
|
| 25 |
+
interval = text_config.pop("global_attention_interval", None)
|
| 26 |
+
if interval is None:
|
| 27 |
+
interval = text_config.pop("full_attention_interval", None)
|
| 28 |
+
if interval is None and plan:
|
| 29 |
+
interval = next(i + 1 for i, t in enumerate(plan) if t == AGNES_GLOBAL)
|
| 30 |
+
text_config["full_attention_interval"] = int(interval or 4)
|
| 31 |
+
main = int(text_config["intermediate_size"])
|
| 32 |
+
# the parallel branch is folded into the main MLP at load time
|
| 33 |
+
text_config["intermediate_size"] = main + width
|
| 34 |
+
text_config["agnes_main_intermediate_size"] = main
|
| 35 |
+
text_config["agnes_parallel_ffn_intermediate_size"] = width
|
| 36 |
+
if isinstance(vision_config, dict):
|
| 37 |
+
vision_config = dict(vision_config)
|
| 38 |
+
vision_config["model_type"] = "qwen3_5"
|
| 39 |
+
kwargs["architectures"] = ["Qwen3_5ForConditionalGeneration"]
|
| 40 |
+
super().__init__(text_config=text_config, vision_config=vision_config, **kwargs)
|
| 41 |
+
# every downstream check sees the built-in hybrid architecture
|
| 42 |
+
self.model_type = "qwen3_5"
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
|
| 46 |
+
# The weight loader needs the checkpoint directory to pick up the parallel
|
| 47 |
+
# branch tensors. The path is written into the config *dict* before the
|
| 48 |
+
# object is built: the config reaches the worker processes through a
|
| 49 |
+
# to_dict round trip, which keeps fields that came in through __init__
|
| 50 |
+
# and drops attributes set afterwards (from_pretrained's own kwargs only
|
| 51 |
+
# override known fields, so they cannot carry it either).
|
| 52 |
+
path = str(pretrained_model_name_or_path)
|
| 53 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
| 54 |
+
config_dict["agnes_model_path"] = path
|
| 55 |
+
if isinstance(config_dict.get("text_config"), dict):
|
| 56 |
+
config_dict["text_config"]["agnes_model_path"] = path
|
| 57 |
+
return cls.from_dict(config_dict, **kwargs)
|
sglang_patch/v0.5.19/sglang/srt/models/qwen3_5.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sglang_patch/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2024 SGLang Team
|
| 2 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 3 |
+
# you may not use this file except in compliance with the License.
|
| 4 |
+
# You may obtain a copy of the License at
|
| 5 |
+
#
|
| 6 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
#
|
| 8 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 9 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 10 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 11 |
+
# See the License for the specific language governing permissions and
|
| 12 |
+
# limitations under the License.
|
| 13 |
+
# ==============================================================================
|
| 14 |
+
"""Shared helpers used by config, tokenizer, and processor modules."""
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Dict, Optional, Type, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from huggingface_hub import snapshot_download
|
| 23 |
+
|
| 24 |
+
from sglang.srt.configs import (
|
| 25 |
+
AfmoeConfig,
|
| 26 |
+
BailingHybridConfig,
|
| 27 |
+
ChatGLMConfig,
|
| 28 |
+
DbrxConfig,
|
| 29 |
+
DeepseekVL2Config,
|
| 30 |
+
Dots3Config,
|
| 31 |
+
DotsOCRConfig,
|
| 32 |
+
DotsVLMConfig,
|
| 33 |
+
ExaoneConfig,
|
| 34 |
+
FalconH1Config,
|
| 35 |
+
GraniteMoeHybridConfig,
|
| 36 |
+
InklingAudioConfig,
|
| 37 |
+
InklingMMConfig,
|
| 38 |
+
InklingModelConfig,
|
| 39 |
+
InklingVisionConfig,
|
| 40 |
+
InternS2MobiusConfig,
|
| 41 |
+
InternS2MobiusTextConfig,
|
| 42 |
+
InternS2PreviewConfig,
|
| 43 |
+
JetNemotronConfig,
|
| 44 |
+
JetVLMConfig,
|
| 45 |
+
KimiK3Config,
|
| 46 |
+
KimiK25Config,
|
| 47 |
+
KimiLinearConfig,
|
| 48 |
+
KimiVLConfig,
|
| 49 |
+
LagunaConfig,
|
| 50 |
+
LocateAnythingConfig,
|
| 51 |
+
LongcatFlashConfig,
|
| 52 |
+
MiniCPMHybridConfig,
|
| 53 |
+
MiniCPMV4_6Config,
|
| 54 |
+
MiniCPMV4_6VisionConfig,
|
| 55 |
+
MiniMaxM3VLConfig,
|
| 56 |
+
MultiModalityConfig,
|
| 57 |
+
MuseGlimmerAssistantConfig,
|
| 58 |
+
MuseGlimmerConfig,
|
| 59 |
+
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
| 60 |
+
NemotronH_Nano_VL_V2_Config,
|
| 61 |
+
NemotronHConfig,
|
| 62 |
+
NemotronHPuzzleConfig,
|
| 63 |
+
Olmo3Config,
|
| 64 |
+
Qwen3_5Config,
|
| 65 |
+
Qwen3_5MoeConfig,
|
| 66 |
+
Qwen3_5MoeTextConfig,
|
| 67 |
+
Qwen3_5TextConfig,
|
| 68 |
+
Qwen3NextConfig,
|
| 69 |
+
Spark2_5Config,
|
| 70 |
+
Step3p5Config,
|
| 71 |
+
Step3p7Config,
|
| 72 |
+
Step3VLConfig,
|
| 73 |
+
)
|
| 74 |
+
from sglang.srt.configs.deepseek_ocr import DeepseekVLV2Config
|
| 75 |
+
from sglang.srt.configs.internvl import InternVLChatConfig
|
| 76 |
+
from sglang.srt.utils import get_bool_env_var, logger, lru_cache_frozenset
|
| 77 |
+
from sglang.srt.utils.runai_utils import ObjectStorageModel, is_runai_obj_uri
|
| 78 |
+
|
| 79 |
+
from ..hf_transformers_patches import normalize_rope_scaling_compat
|
| 80 |
+
|
| 81 |
+
if get_bool_env_var("SGLANG_USE_MODELSCOPE"):
|
| 82 |
+
from modelscope import AutoConfig, GenerationConfig
|
| 83 |
+
else:
|
| 84 |
+
from transformers import AutoConfig, GenerationConfig
|
| 85 |
+
|
| 86 |
+
from transformers import PretrainedConfig
|
| 87 |
+
|
| 88 |
+
# ---------------------------------------------------------------------------
|
| 89 |
+
# Config registry
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
|
| 92 |
+
_CONFIG_REGISTRY: Dict[str, Type[PretrainedConfig]] = {
|
| 93 |
+
cls.model_type: cls
|
| 94 |
+
for cls in [
|
| 95 |
+
AfmoeConfig,
|
| 96 |
+
BailingHybridConfig,
|
| 97 |
+
ChatGLMConfig,
|
| 98 |
+
DbrxConfig,
|
| 99 |
+
ExaoneConfig,
|
| 100 |
+
DeepseekVL2Config,
|
| 101 |
+
MultiModalityConfig,
|
| 102 |
+
KimiVLConfig,
|
| 103 |
+
LocateAnythingConfig,
|
| 104 |
+
InternVLChatConfig,
|
| 105 |
+
LagunaConfig,
|
| 106 |
+
Spark2_5Config,
|
| 107 |
+
Step3VLConfig,
|
| 108 |
+
LongcatFlashConfig,
|
| 109 |
+
Olmo3Config,
|
| 110 |
+
MuseGlimmerConfig,
|
| 111 |
+
MuseGlimmerAssistantConfig,
|
| 112 |
+
KimiK3Config,
|
| 113 |
+
KimiLinearConfig,
|
| 114 |
+
Qwen3NextConfig,
|
| 115 |
+
FalconH1Config,
|
| 116 |
+
GraniteMoeHybridConfig,
|
| 117 |
+
DotsVLMConfig,
|
| 118 |
+
DotsOCRConfig,
|
| 119 |
+
Dots3Config,
|
| 120 |
+
NemotronH_Nano_VL_V2_Config,
|
| 121 |
+
NemotronH_Nano_Omni_Reasoning_V3_Config,
|
| 122 |
+
NemotronHConfig,
|
| 123 |
+
NemotronHPuzzleConfig,
|
| 124 |
+
DeepseekVLV2Config,
|
| 125 |
+
Qwen3_5Config,
|
| 126 |
+
Qwen3_5MoeConfig,
|
| 127 |
+
Qwen3_5TextConfig,
|
| 128 |
+
Qwen3_5MoeTextConfig,
|
| 129 |
+
InternS2PreviewConfig,
|
| 130 |
+
InternS2MobiusConfig,
|
| 131 |
+
InternS2MobiusTextConfig,
|
| 132 |
+
JetNemotronConfig,
|
| 133 |
+
JetVLMConfig,
|
| 134 |
+
KimiK25Config,
|
| 135 |
+
Step3p5Config,
|
| 136 |
+
Step3p7Config,
|
| 137 |
+
MiniCPMHybridConfig,
|
| 138 |
+
MiniCPMV4_6Config,
|
| 139 |
+
MiniCPMV4_6VisionConfig,
|
| 140 |
+
InklingModelConfig,
|
| 141 |
+
InklingAudioConfig,
|
| 142 |
+
InklingVisionConfig,
|
| 143 |
+
InklingMMConfig,
|
| 144 |
+
MiniMaxM3VLConfig,
|
| 145 |
+
]
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# DeepSeek V3.2 / V4 reuse the V3 config schema. Subclass the upstream
|
| 150 |
+
# transformers class with each model_type so AutoConfig.register passes its
|
| 151 |
+
# consistency check (which requires class.model_type == registered key).
|
| 152 |
+
# Default-value divergences (e.g. V4's topk_group) are handled in
|
| 153 |
+
# model_config.py post-load.
|
| 154 |
+
try:
|
| 155 |
+
from transformers import DeepseekV3Config as _HFDeepseekV3Config
|
| 156 |
+
|
| 157 |
+
class _DeepseekV32ConfigAlias(_HFDeepseekV3Config):
|
| 158 |
+
model_type = "deepseek_v32"
|
| 159 |
+
|
| 160 |
+
class _DeepseekV4ConfigAlias(_HFDeepseekV3Config):
|
| 161 |
+
model_type = "deepseek_v4"
|
| 162 |
+
|
| 163 |
+
_CONFIG_REGISTRY["deepseek_v32"] = _DeepseekV32ConfigAlias
|
| 164 |
+
_CONFIG_REGISTRY["deepseek_v4"] = _DeepseekV4ConfigAlias
|
| 165 |
+
|
| 166 |
+
# For kimi_k25_eagle3
|
| 167 |
+
class _KimiK2ConfigAlias(_HFDeepseekV3Config):
|
| 168 |
+
model_type = "kimi_k2"
|
| 169 |
+
|
| 170 |
+
_CONFIG_REGISTRY["kimi_k2"] = _KimiK2ConfigAlias
|
| 171 |
+
except ImportError:
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
# Newer transformers versions (>=5.10.2) expose MellumConfig directly,
|
| 175 |
+
# but fallback to Qwen3MoeConfig for older versions.
|
| 176 |
+
try:
|
| 177 |
+
import transformers as _hf_transformers
|
| 178 |
+
|
| 179 |
+
_HFMellumConfig = getattr(_hf_transformers, "MellumConfig", None)
|
| 180 |
+
|
| 181 |
+
if _HFMellumConfig is not None:
|
| 182 |
+
_CONFIG_REGISTRY["mellum"] = _HFMellumConfig
|
| 183 |
+
else:
|
| 184 |
+
from transformers import Qwen3MoeConfig as _HFQwen3MoeConfig
|
| 185 |
+
|
| 186 |
+
class _MellumConfigAlias(_HFQwen3MoeConfig):
|
| 187 |
+
model_type = "mellum"
|
| 188 |
+
|
| 189 |
+
def __post_init__(self, **kwargs):
|
| 190 |
+
# Qwen3MoeConfig.__post_init__ wipes sliding_window unless
|
| 191 |
+
# use_sliding_window=True. Mellum gates sliding attention
|
| 192 |
+
# per-layer via layer_types, so preserve sliding_window
|
| 193 |
+
# regardless of the legacy use_sliding_window flag.
|
| 194 |
+
sliding_window = getattr(self, "sliding_window", None)
|
| 195 |
+
super().__post_init__(**kwargs)
|
| 196 |
+
self.sliding_window = sliding_window
|
| 197 |
+
|
| 198 |
+
_CONFIG_REGISTRY["mellum"] = _MellumConfigAlias
|
| 199 |
+
|
| 200 |
+
except ImportError:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
try:
|
| 205 |
+
from transformers import Gemma4Config as _HFGemma4Config
|
| 206 |
+
|
| 207 |
+
class _Gemma4UnifiedConfigAlias(_HFGemma4Config):
|
| 208 |
+
model_type = "gemma4_unified"
|
| 209 |
+
|
| 210 |
+
_CONFIG_REGISTRY["gemma4_unified"] = _Gemma4UnifiedConfigAlias
|
| 211 |
+
except ImportError:
|
| 212 |
+
pass
|
| 213 |
+
|
| 214 |
+
for name, cls in _CONFIG_REGISTRY.items():
|
| 215 |
+
try:
|
| 216 |
+
AutoConfig.register(name, cls)
|
| 217 |
+
except ValueError as e:
|
| 218 |
+
err = str(e).lower()
|
| 219 |
+
if "already registered" not in err and "already used" not in err:
|
| 220 |
+
logger.warning("Failed to register config %s: %s", name, e)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# ---------------------------------------------------------------------------
|
| 224 |
+
# Download / path helpers
|
| 225 |
+
# ---------------------------------------------------------------------------
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def download_from_hf(
|
| 229 |
+
model_path: str,
|
| 230 |
+
allow_patterns: Optional[Union[str, list]] = None,
|
| 231 |
+
):
|
| 232 |
+
if os.path.exists(model_path):
|
| 233 |
+
return model_path
|
| 234 |
+
|
| 235 |
+
if not allow_patterns:
|
| 236 |
+
allow_patterns = ["*.json", "*.bin", "*.model"]
|
| 237 |
+
|
| 238 |
+
return snapshot_download(model_path, allow_patterns=allow_patterns)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def resolve_runai_obj_uri(model_name_or_path: str) -> str:
|
| 242 |
+
if is_runai_obj_uri(model_name_or_path):
|
| 243 |
+
return ObjectStorageModel.get_path(model_name_or_path)
|
| 244 |
+
return model_name_or_path
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _resolve_local_or_cached_file(model_name_or_path, filename, revision=None):
|
| 248 |
+
"""Resolve a file from a local directory or HF hub cache (no network)."""
|
| 249 |
+
local_path = Path(model_name_or_path) / filename
|
| 250 |
+
if local_path.is_file():
|
| 251 |
+
return str(local_path)
|
| 252 |
+
from huggingface_hub import hf_hub_download
|
| 253 |
+
|
| 254 |
+
return hf_hub_download(
|
| 255 |
+
model_name_or_path, filename, revision=revision, local_files_only=True
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def _cached_file_exists(model_name_or_path, filename, revision=None) -> bool:
|
| 260 |
+
"""Whether *filename* is available locally or in the HF cache (no network)."""
|
| 261 |
+
try:
|
| 262 |
+
_resolve_local_or_cached_file(model_name_or_path, filename, revision)
|
| 263 |
+
return True
|
| 264 |
+
except Exception:
|
| 265 |
+
return False
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _remote_file_exists(repo_id, filename, revision=None) -> bool:
|
| 269 |
+
"""Whether *filename* exists on the HF hub (HEAD request only, no download).
|
| 270 |
+
|
| 271 |
+
Returns False on any error (offline, gated, network, invalid id) so callers
|
| 272 |
+
fall back to their default path instead of crashing.
|
| 273 |
+
"""
|
| 274 |
+
from huggingface_hub.constants import HF_HUB_OFFLINE
|
| 275 |
+
|
| 276 |
+
if HF_HUB_OFFLINE:
|
| 277 |
+
return False
|
| 278 |
+
try:
|
| 279 |
+
from huggingface_hub import HfApi
|
| 280 |
+
|
| 281 |
+
return HfApi().file_exists(repo_id, filename, revision=revision)
|
| 282 |
+
except Exception:
|
| 283 |
+
return False
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def check_gguf_file(model: Union[str, os.PathLike]) -> bool:
|
| 287 |
+
model = Path(model)
|
| 288 |
+
if not model.is_file():
|
| 289 |
+
return False
|
| 290 |
+
elif model.suffix == ".gguf":
|
| 291 |
+
return True
|
| 292 |
+
|
| 293 |
+
with open(model, "rb") as f:
|
| 294 |
+
header = f.read(4)
|
| 295 |
+
return header == b"GGUF"
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def resolve_hf_gguf_reference(
|
| 299 |
+
model: str, revision: Optional[str] = None
|
| 300 |
+
) -> Optional[str]:
|
| 301 |
+
"""Download a .gguf named by Hub reference and return its local path.
|
| 302 |
+
|
| 303 |
+
owner/repo/path/inside/repo.gguf -> exactly that file
|
| 304 |
+
owner/repo:QUANT_TYPE -> the only matching quantization
|
| 305 |
+
owner/repo -> the only .gguf in the repo
|
| 306 |
+
"""
|
| 307 |
+
from sglang.srt.utils import is_remote_url
|
| 308 |
+
|
| 309 |
+
if not model or os.path.exists(model) or is_remote_url(model):
|
| 310 |
+
return None
|
| 311 |
+
|
| 312 |
+
from huggingface_hub import hf_hub_download
|
| 313 |
+
|
| 314 |
+
if ":" in model:
|
| 315 |
+
repo_id, _, quant_type = model.rpartition(":")
|
| 316 |
+
if repo_id.count("/") != 1 or not quant_type:
|
| 317 |
+
return None
|
| 318 |
+
|
| 319 |
+
from huggingface_hub import HfApi
|
| 320 |
+
|
| 321 |
+
files = [
|
| 322 |
+
sibling.rfilename
|
| 323 |
+
for sibling in HfApi().repo_info(repo_id, revision=revision).siblings
|
| 324 |
+
]
|
| 325 |
+
suffix = f"-{quant_type}.gguf"
|
| 326 |
+
candidates = [filename for filename in files if filename.endswith(suffix)]
|
| 327 |
+
if not candidates:
|
| 328 |
+
available = sorted(
|
| 329 |
+
filename for filename in files if filename.endswith(".gguf")
|
| 330 |
+
)
|
| 331 |
+
raise ValueError(
|
| 332 |
+
f"No file matching quant type {quant_type!r} in {repo_id}. "
|
| 333 |
+
f"Available GGUF files: {available}"
|
| 334 |
+
)
|
| 335 |
+
if len(candidates) > 1:
|
| 336 |
+
raise ValueError(
|
| 337 |
+
f"Quant type {quant_type!r} is ambiguous in {repo_id}: "
|
| 338 |
+
f"{sorted(candidates)}. Pass the full owner/repo/path/file.gguf "
|
| 339 |
+
"reference instead."
|
| 340 |
+
)
|
| 341 |
+
return hf_hub_download(repo_id, candidates[0], revision=revision)
|
| 342 |
+
|
| 343 |
+
parts = model.strip("/").split("/")
|
| 344 |
+
if len(parts) < 2:
|
| 345 |
+
return None
|
| 346 |
+
|
| 347 |
+
if len(parts) > 2 and model.endswith(".gguf"):
|
| 348 |
+
repo_id = "/".join(parts[:2])
|
| 349 |
+
filename = "/".join(parts[2:])
|
| 350 |
+
return hf_hub_download(repo_id, filename, revision=revision)
|
| 351 |
+
|
| 352 |
+
if len(parts) != 2:
|
| 353 |
+
return None
|
| 354 |
+
|
| 355 |
+
from huggingface_hub import HfApi
|
| 356 |
+
|
| 357 |
+
try:
|
| 358 |
+
files = [
|
| 359 |
+
s.rfilename for s in HfApi().repo_info(model, revision=revision).siblings
|
| 360 |
+
]
|
| 361 |
+
except Exception:
|
| 362 |
+
return None
|
| 363 |
+
if any(f == "config.json" for f in files):
|
| 364 |
+
return None
|
| 365 |
+
|
| 366 |
+
candidates = [f for f in files if f.endswith(".gguf")]
|
| 367 |
+
if not candidates:
|
| 368 |
+
return None
|
| 369 |
+
if len(candidates) > 1:
|
| 370 |
+
listing = "\n ".join(f"{model}/{f}" for f in sorted(candidates))
|
| 371 |
+
raise ValueError(
|
| 372 |
+
f"{model} contains {len(candidates)} .gguf files; name the one to "
|
| 373 |
+
f"serve:\n {listing}"
|
| 374 |
+
)
|
| 375 |
+
return hf_hub_download(model, candidates[0], revision=revision)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def gguf_sidecar_dir(
|
| 379 |
+
gguf_path: Union[str, os.PathLike], sentinel: str
|
| 380 |
+
) -> Optional[Path]:
|
| 381 |
+
"""Directory containing *sentinel* next to a .gguf file, if there is one."""
|
| 382 |
+
directory = Path(gguf_path).parent
|
| 383 |
+
return directory if (directory / sentinel).is_file() else None
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
# ---------------------------------------------------------------------------
|
| 387 |
+
# Rope / text config helpers
|
| 388 |
+
# ---------------------------------------------------------------------------
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def get_rope_config(config):
|
| 392 |
+
"""Get (rope_theta, rope_params) from config, supporting both v4 and v5.
|
| 393 |
+
|
| 394 |
+
Trust-remote-code configs or parent configs passed to sub-models may not
|
| 395 |
+
have the v5 ``rope_parameters`` property, so we fall back to the v4-style
|
| 396 |
+
``config.rope_theta`` / ``config.rope_scaling`` attributes.
|
| 397 |
+
|
| 398 |
+
Returns:
|
| 399 |
+
(rope_theta, rope_params): In v5, rope_params is the full
|
| 400 |
+
rope_parameters dict (which subsumes rope_scaling and includes
|
| 401 |
+
rope_theta). In v4, rope_params is the rope_scaling dict or None.
|
| 402 |
+
"""
|
| 403 |
+
rope_params = getattr(config, "rope_parameters", None)
|
| 404 |
+
if rope_params is not None:
|
| 405 |
+
rope_theta = rope_params.get("rope_theta", getattr(config, "rope_theta", 10000))
|
| 406 |
+
return rope_theta, rope_params
|
| 407 |
+
return getattr(config, "rope_theta", 10000), getattr(config, "rope_scaling", None)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def _patch_text_config(parent_config: PretrainedConfig, text_config):
|
| 411 |
+
"""Synchronize standard attributes between parent config and text sub-config.
|
| 412 |
+
|
| 413 |
+
In transformers v5, the "untangle config" refactor removed automatic
|
| 414 |
+
inheritance of top-level PretrainedConfig attributes (pad_token_id,
|
| 415 |
+
tie_word_embeddings, etc.) from sub-configs. Downstream code expects
|
| 416 |
+
these attributes to be present on both configs (some models pass the
|
| 417 |
+
parent directly to the language model, others pass the text sub-config),
|
| 418 |
+
so we propagate in both directions when an attribute is missing.
|
| 419 |
+
(See https://github.com/huggingface/transformers/pull/41541)
|
| 420 |
+
"""
|
| 421 |
+
_ATTRS_TO_PROPAGATE = [
|
| 422 |
+
"pad_token_id",
|
| 423 |
+
"bos_token_id",
|
| 424 |
+
"eos_token_id",
|
| 425 |
+
"tie_word_embeddings",
|
| 426 |
+
]
|
| 427 |
+
for attr in _ATTRS_TO_PROPAGATE:
|
| 428 |
+
parent_has = hasattr(parent_config, attr)
|
| 429 |
+
text_has = hasattr(text_config, attr)
|
| 430 |
+
if parent_has and not text_has:
|
| 431 |
+
setattr(text_config, attr, getattr(parent_config, attr))
|
| 432 |
+
elif text_has and not parent_has:
|
| 433 |
+
setattr(parent_config, attr, getattr(text_config, attr))
|
| 434 |
+
return text_config
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def get_hf_text_config(config: PretrainedConfig):
|
| 438 |
+
"""Get the "sub" config relevant to llm for multi modal models.
|
| 439 |
+
No op for pure text models.
|
| 440 |
+
"""
|
| 441 |
+
if config.architectures is not None:
|
| 442 |
+
class_name = config.architectures[0]
|
| 443 |
+
if class_name.startswith("Llava") and class_name.endswith("ForCausalLM"):
|
| 444 |
+
# We support non-hf version of llava models, so we do not want to
|
| 445 |
+
# read the wrong values from the unused default text_config.
|
| 446 |
+
# NOTE(HandH1998): We set `torch_dtype` of config to `torch.float16` for the weights, as
|
| 447 |
+
# `torch.float16` is default used for image features in `python/sglang/srt/models/llava.py`.
|
| 448 |
+
setattr(config, "dtype", torch.float16)
|
| 449 |
+
return config
|
| 450 |
+
|
| 451 |
+
text_config = None
|
| 452 |
+
|
| 453 |
+
# Some models (e.g. DeepSeek-OCR) store sub-configs as plain dicts.
|
| 454 |
+
# Convert to PretrainedConfig early so hasattr() checks and asserts work.
|
| 455 |
+
parent_dtype = getattr(config, "dtype", None)
|
| 456 |
+
for _attr in ("text_config", "llm_config", "language_config", "thinker_config"):
|
| 457 |
+
_sub = getattr(config, _attr, None)
|
| 458 |
+
if isinstance(_sub, dict):
|
| 459 |
+
_converted = PretrainedConfig(**_sub)
|
| 460 |
+
if getattr(_converted, "dtype", None) is None and parent_dtype is not None:
|
| 461 |
+
_converted.dtype = parent_dtype
|
| 462 |
+
setattr(config, _attr, _converted)
|
| 463 |
+
elif _sub is not None and parent_dtype is not None:
|
| 464 |
+
# transformers v5 multimodal configs (e.g. Mistral3Config) carry
|
| 465 |
+
# `dtype` only on the top-level config, leaving the sub-configs at
|
| 466 |
+
# None. Without this, _get_and_verify_dtype falls back to float32
|
| 467 |
+
# and then "auto" downcasts to float16, which overflows the Pixtral
|
| 468 |
+
# vision tower on real images and produces NaN features.
|
| 469 |
+
if getattr(_sub, "dtype", None) is None:
|
| 470 |
+
_sub.dtype = parent_dtype
|
| 471 |
+
|
| 472 |
+
# Priority: thinker_config > llm_config > language_config > text_config
|
| 473 |
+
if hasattr(config, "thinker_config"):
|
| 474 |
+
# qwen2.5 omni
|
| 475 |
+
thinker_config = config.thinker_config
|
| 476 |
+
if hasattr(thinker_config, "text_config"):
|
| 477 |
+
setattr(
|
| 478 |
+
thinker_config.text_config,
|
| 479 |
+
"dtype",
|
| 480 |
+
getattr(thinker_config, "dtype", None),
|
| 481 |
+
)
|
| 482 |
+
text_config = thinker_config.text_config
|
| 483 |
+
else:
|
| 484 |
+
text_config = thinker_config
|
| 485 |
+
elif hasattr(config, "llm_config"):
|
| 486 |
+
# PointsV1.5 Chat Model
|
| 487 |
+
assert hasattr(config.llm_config, "num_attention_heads")
|
| 488 |
+
text_config = config.llm_config
|
| 489 |
+
elif hasattr(config, "language_config"):
|
| 490 |
+
text_config = config.language_config
|
| 491 |
+
elif hasattr(config, "text_config"):
|
| 492 |
+
# The code operates under the assumption that text_config should have
|
| 493 |
+
# `num_attention_heads` (among others). Assert here to fail early
|
| 494 |
+
# if transformers config doesn't align with this assumption.
|
| 495 |
+
assert hasattr(config.text_config, "num_attention_heads")
|
| 496 |
+
text_config = config.text_config
|
| 497 |
+
|
| 498 |
+
# Ensure rope_scaling dicts have "type" for remote-code compat (v5).
|
| 499 |
+
normalize_rope_scaling_compat(config)
|
| 500 |
+
|
| 501 |
+
if text_config is not None:
|
| 502 |
+
return _patch_text_config(config, text_config)
|
| 503 |
+
return config
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
# ---------------------------------------------------------------------------
|
| 507 |
+
# Model-specific helpers
|
| 508 |
+
# ---------------------------------------------------------------------------
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _ensure_sub_configs(config: PretrainedConfig, *attr_names: str) -> None:
|
| 512 |
+
"""Convert dict-valued sub-configs to proper AutoConfig objects in-place."""
|
| 513 |
+
for attr in attr_names:
|
| 514 |
+
sub = getattr(config, attr, None)
|
| 515 |
+
if sub is not None and isinstance(sub, dict):
|
| 516 |
+
setattr(config, attr, AutoConfig.for_model(**sub))
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _is_deepseek_ocr_model(config: PretrainedConfig) -> bool:
|
| 520 |
+
# TODO: Remove this workaround once AutoConfig correctly identifies deepseek-ocr.
|
| 521 |
+
# Hugging Face's AutoConfig currently misidentifies it as deepseekvl2.
|
| 522 |
+
auto_map = getattr(config, "auto_map", None) or {}
|
| 523 |
+
return auto_map.get("AutoModel") == "modeling_deepseekocr.DeepseekOCRForCausalLM"
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _is_deepseek_ocr2_model(config: PretrainedConfig) -> bool:
|
| 527 |
+
auto_map = getattr(config, "auto_map", None) or {}
|
| 528 |
+
return auto_map.get("AutoModel") == "modeling_deepseekocr2.DeepseekOCR2ForCausalLM"
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def _override_v_head_dim_if_zero(config: PretrainedConfig, patch: int = 128) -> None:
|
| 532 |
+
patched = False
|
| 533 |
+
for attr in ("text_config", "language_config"):
|
| 534 |
+
sub = getattr(config, attr, None)
|
| 535 |
+
if sub is None:
|
| 536 |
+
continue
|
| 537 |
+
if isinstance(sub, dict):
|
| 538 |
+
if sub.get("v_head_dim") == 0:
|
| 539 |
+
sub["v_head_dim"] = patch
|
| 540 |
+
patched = True
|
| 541 |
+
elif getattr(sub, "v_head_dim", None) == 0:
|
| 542 |
+
sub.v_head_dim = patch
|
| 543 |
+
patched = True
|
| 544 |
+
if patched:
|
| 545 |
+
logger.warning(
|
| 546 |
+
f"Overriding v_head_dim from 0 to {patch} to avoid potential issues."
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
# ---------------------------------------------------------------------------
|
| 551 |
+
# Context length / generation config / sparse attention
|
| 552 |
+
# ---------------------------------------------------------------------------
|
| 553 |
+
|
| 554 |
+
# Models don't use the same configuration key for determining the maximum
|
| 555 |
+
# context length. Store them here so we can sanely check them.
|
| 556 |
+
# NOTE: The ordering here is important. Some models have two of these and we
|
| 557 |
+
# have a preference for which value gets used.
|
| 558 |
+
CONTEXT_LENGTH_KEYS = [
|
| 559 |
+
"max_sequence_length",
|
| 560 |
+
"seq_length",
|
| 561 |
+
"max_seq_len",
|
| 562 |
+
"model_max_length",
|
| 563 |
+
"max_position_embeddings",
|
| 564 |
+
]
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def get_context_length(config):
|
| 568 |
+
"""Get the context length of a model from a huggingface model configs."""
|
| 569 |
+
text_config = config
|
| 570 |
+
rope_scaling = getattr(text_config, "rope_scaling", None)
|
| 571 |
+
if rope_scaling:
|
| 572 |
+
rope_scaling_factor = rope_scaling.get("factor", 1)
|
| 573 |
+
if "original_max_position_embeddings" in rope_scaling:
|
| 574 |
+
rope_scaling_factor = 1
|
| 575 |
+
if rope_scaling.get("rope_type", None) == "llama3":
|
| 576 |
+
rope_scaling_factor = 1
|
| 577 |
+
else:
|
| 578 |
+
rope_scaling_factor = 1
|
| 579 |
+
|
| 580 |
+
for key in CONTEXT_LENGTH_KEYS:
|
| 581 |
+
val = getattr(text_config, key, None)
|
| 582 |
+
if val is not None:
|
| 583 |
+
return int(rope_scaling_factor * val)
|
| 584 |
+
return 2048
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
@lru_cache_frozenset(maxsize=32)
|
| 588 |
+
def get_generation_config(
|
| 589 |
+
model: str,
|
| 590 |
+
trust_remote_code: bool,
|
| 591 |
+
revision: Optional[str] = None,
|
| 592 |
+
**kwargs,
|
| 593 |
+
):
|
| 594 |
+
if check_gguf_file(model):
|
| 595 |
+
sidecar = gguf_sidecar_dir(model, "generation_config.json")
|
| 596 |
+
if sidecar is not None:
|
| 597 |
+
model = str(sidecar)
|
| 598 |
+
else:
|
| 599 |
+
from .gguf_native import (
|
| 600 |
+
build_gguf_generation_config,
|
| 601 |
+
has_native_gguf_support,
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
if has_native_gguf_support(model):
|
| 605 |
+
return build_gguf_generation_config(model)
|
| 606 |
+
|
| 607 |
+
try:
|
| 608 |
+
return GenerationConfig.from_pretrained(
|
| 609 |
+
model, trust_remote_code=trust_remote_code, revision=revision, **kwargs
|
| 610 |
+
)
|
| 611 |
+
except (FileNotFoundError, OSError) as e:
|
| 612 |
+
# A missing generation_config.json is normal for many checkpoints and
|
| 613 |
+
# is surfaced by HF as a generic OSError (not FileNotFoundError). Treat
|
| 614 |
+
# it as benign — proceed without a generation config, at DEBUG level so
|
| 615 |
+
# normal startup logs stay quiet.
|
| 616 |
+
logger.debug(
|
| 617 |
+
"No generation config for %s: %s. Proceeding without it.",
|
| 618 |
+
model,
|
| 619 |
+
e,
|
| 620 |
+
)
|
| 621 |
+
return None
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
# Qwen-1M related
|
| 625 |
+
def get_sparse_attention_config(
|
| 626 |
+
model: str,
|
| 627 |
+
sparse_attention_config_filename: str = "sparse_attention_config.json",
|
| 628 |
+
) -> Dict[str, Any]:
|
| 629 |
+
is_local = os.path.isdir(model)
|
| 630 |
+
if not is_local:
|
| 631 |
+
model = download_from_hf(model, allow_patterns=["*.json"])
|
| 632 |
+
|
| 633 |
+
config_file = os.path.join(model, sparse_attention_config_filename)
|
| 634 |
+
if not os.path.exists(config_file):
|
| 635 |
+
return {}
|
| 636 |
+
|
| 637 |
+
with open(config_file) as f:
|
| 638 |
+
config = json.load(f)
|
| 639 |
+
return config
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
# ---------------------------------------------------------------------------
|
| 643 |
+
# Tokenizer / processor helpers
|
| 644 |
+
# ---------------------------------------------------------------------------
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
# Some models don't have an available processor, e.g.: InternVL
|
| 648 |
+
def get_tokenizer_from_processor(processor):
|
| 649 |
+
from transformers import PreTrainedTokenizerBase
|
| 650 |
+
|
| 651 |
+
if isinstance(processor, PreTrainedTokenizerBase):
|
| 652 |
+
return processor
|
| 653 |
+
return processor.tokenizer
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
# Turn-final markers that some checkpoints ship without EOS metadata:
|
| 657 |
+
# <|eom_id|> (Llama-3 tool use) and <|content_model_end_sampling|> (Inkling,
|
| 658 |
+
# whose bundled tokenizer config leaves eos_token unset).
|
| 659 |
+
_ADDITIONAL_STOP_TOKEN_TEXTS = ("<|eom_id|>", "<|content_model_end_sampling|>")
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def attach_additional_stop_token_ids(tokenizer):
|
| 663 |
+
added = tokenizer.get_added_vocab()
|
| 664 |
+
stop_ids = {added[text] for text in _ADDITIONAL_STOP_TOKEN_TEXTS if text in added}
|
| 665 |
+
tokenizer.additional_stop_token_ids = stop_ids or None
|
| 666 |
+
|
| 667 |
+
# === agnes ===
|
| 668 |
+
from sglang.srt.configs.agnes import AgnesConfig as _AgnesConfig
|
| 669 |
+
|
| 670 |
+
_CONFIG_REGISTRY[_AgnesConfig.model_type] = _AgnesConfig
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"added_tokens_decoder": {
|
| 4 |
+
"248044": {
|
| 5 |
+
"content": "<|endoftext|>",
|
| 6 |
+
"lstrip": false,
|
| 7 |
+
"normalized": false,
|
| 8 |
+
"rstrip": false,
|
| 9 |
+
"single_word": false,
|
| 10 |
+
"special": true
|
| 11 |
+
},
|
| 12 |
+
"248045": {
|
| 13 |
+
"content": "<|im_start|>",
|
| 14 |
+
"lstrip": false,
|
| 15 |
+
"normalized": false,
|
| 16 |
+
"rstrip": false,
|
| 17 |
+
"single_word": false,
|
| 18 |
+
"special": true
|
| 19 |
+
},
|
| 20 |
+
"248046": {
|
| 21 |
+
"content": "<|im_end|>",
|
| 22 |
+
"lstrip": false,
|
| 23 |
+
"normalized": false,
|
| 24 |
+
"rstrip": false,
|
| 25 |
+
"single_word": false,
|
| 26 |
+
"special": true
|
| 27 |
+
},
|
| 28 |
+
"248047": {
|
| 29 |
+
"content": "<|object_ref_start|>",
|
| 30 |
+
"lstrip": false,
|
| 31 |
+
"normalized": false,
|
| 32 |
+
"rstrip": false,
|
| 33 |
+
"single_word": false,
|
| 34 |
+
"special": true
|
| 35 |
+
},
|
| 36 |
+
"248048": {
|
| 37 |
+
"content": "<|object_ref_end|>",
|
| 38 |
+
"lstrip": false,
|
| 39 |
+
"normalized": false,
|
| 40 |
+
"rstrip": false,
|
| 41 |
+
"single_word": false,
|
| 42 |
+
"special": true
|
| 43 |
+
},
|
| 44 |
+
"248049": {
|
| 45 |
+
"content": "<|box_start|>",
|
| 46 |
+
"lstrip": false,
|
| 47 |
+
"normalized": false,
|
| 48 |
+
"rstrip": false,
|
| 49 |
+
"single_word": false,
|
| 50 |
+
"special": true
|
| 51 |
+
},
|
| 52 |
+
"248050": {
|
| 53 |
+
"content": "<|box_end|>",
|
| 54 |
+
"lstrip": false,
|
| 55 |
+
"normalized": false,
|
| 56 |
+
"rstrip": false,
|
| 57 |
+
"single_word": false,
|
| 58 |
+
"special": true
|
| 59 |
+
},
|
| 60 |
+
"248051": {
|
| 61 |
+
"content": "<|quad_start|>",
|
| 62 |
+
"lstrip": false,
|
| 63 |
+
"normalized": false,
|
| 64 |
+
"rstrip": false,
|
| 65 |
+
"single_word": false,
|
| 66 |
+
"special": true
|
| 67 |
+
},
|
| 68 |
+
"248052": {
|
| 69 |
+
"content": "<|quad_end|>",
|
| 70 |
+
"lstrip": false,
|
| 71 |
+
"normalized": false,
|
| 72 |
+
"rstrip": false,
|
| 73 |
+
"single_word": false,
|
| 74 |
+
"special": true
|
| 75 |
+
},
|
| 76 |
+
"248053": {
|
| 77 |
+
"content": "<|vision_start|>",
|
| 78 |
+
"lstrip": false,
|
| 79 |
+
"normalized": false,
|
| 80 |
+
"rstrip": false,
|
| 81 |
+
"single_word": false,
|
| 82 |
+
"special": true
|
| 83 |
+
},
|
| 84 |
+
"248054": {
|
| 85 |
+
"content": "<|vision_end|>",
|
| 86 |
+
"lstrip": false,
|
| 87 |
+
"normalized": false,
|
| 88 |
+
"rstrip": false,
|
| 89 |
+
"single_word": false,
|
| 90 |
+
"special": true
|
| 91 |
+
},
|
| 92 |
+
"248055": {
|
| 93 |
+
"content": "<|vision_pad|>",
|
| 94 |
+
"lstrip": false,
|
| 95 |
+
"normalized": false,
|
| 96 |
+
"rstrip": false,
|
| 97 |
+
"single_word": false,
|
| 98 |
+
"special": true
|
| 99 |
+
},
|
| 100 |
+
"248056": {
|
| 101 |
+
"content": "<|image_pad|>",
|
| 102 |
+
"lstrip": false,
|
| 103 |
+
"normalized": false,
|
| 104 |
+
"rstrip": false,
|
| 105 |
+
"single_word": false,
|
| 106 |
+
"special": true
|
| 107 |
+
},
|
| 108 |
+
"248057": {
|
| 109 |
+
"content": "<|video_pad|>",
|
| 110 |
+
"lstrip": false,
|
| 111 |
+
"normalized": false,
|
| 112 |
+
"rstrip": false,
|
| 113 |
+
"single_word": false,
|
| 114 |
+
"special": true
|
| 115 |
+
},
|
| 116 |
+
"248058": {
|
| 117 |
+
"content": "<tool_call>",
|
| 118 |
+
"lstrip": false,
|
| 119 |
+
"normalized": false,
|
| 120 |
+
"rstrip": false,
|
| 121 |
+
"single_word": false,
|
| 122 |
+
"special": false
|
| 123 |
+
},
|
| 124 |
+
"248059": {
|
| 125 |
+
"content": "</tool_call>",
|
| 126 |
+
"lstrip": false,
|
| 127 |
+
"normalized": false,
|
| 128 |
+
"rstrip": false,
|
| 129 |
+
"single_word": false,
|
| 130 |
+
"special": false
|
| 131 |
+
},
|
| 132 |
+
"248060": {
|
| 133 |
+
"content": "<|fim_prefix|>",
|
| 134 |
+
"lstrip": false,
|
| 135 |
+
"normalized": false,
|
| 136 |
+
"rstrip": false,
|
| 137 |
+
"single_word": false,
|
| 138 |
+
"special": false
|
| 139 |
+
},
|
| 140 |
+
"248061": {
|
| 141 |
+
"content": "<|fim_middle|>",
|
| 142 |
+
"lstrip": false,
|
| 143 |
+
"normalized": false,
|
| 144 |
+
"rstrip": false,
|
| 145 |
+
"single_word": false,
|
| 146 |
+
"special": false
|
| 147 |
+
},
|
| 148 |
+
"248062": {
|
| 149 |
+
"content": "<|fim_suffix|>",
|
| 150 |
+
"lstrip": false,
|
| 151 |
+
"normalized": false,
|
| 152 |
+
"rstrip": false,
|
| 153 |
+
"single_word": false,
|
| 154 |
+
"special": false
|
| 155 |
+
},
|
| 156 |
+
"248063": {
|
| 157 |
+
"content": "<|fim_pad|>",
|
| 158 |
+
"lstrip": false,
|
| 159 |
+
"normalized": false,
|
| 160 |
+
"rstrip": false,
|
| 161 |
+
"single_word": false,
|
| 162 |
+
"special": false
|
| 163 |
+
},
|
| 164 |
+
"248064": {
|
| 165 |
+
"content": "<|repo_name|>",
|
| 166 |
+
"lstrip": false,
|
| 167 |
+
"normalized": false,
|
| 168 |
+
"rstrip": false,
|
| 169 |
+
"single_word": false,
|
| 170 |
+
"special": false
|
| 171 |
+
},
|
| 172 |
+
"248065": {
|
| 173 |
+
"content": "<|file_sep|>",
|
| 174 |
+
"lstrip": false,
|
| 175 |
+
"normalized": false,
|
| 176 |
+
"rstrip": false,
|
| 177 |
+
"single_word": false,
|
| 178 |
+
"special": false
|
| 179 |
+
},
|
| 180 |
+
"248066": {
|
| 181 |
+
"content": "<tool_response>",
|
| 182 |
+
"lstrip": false,
|
| 183 |
+
"normalized": false,
|
| 184 |
+
"rstrip": false,
|
| 185 |
+
"single_word": false,
|
| 186 |
+
"special": false
|
| 187 |
+
},
|
| 188 |
+
"248067": {
|
| 189 |
+
"content": "</tool_response>",
|
| 190 |
+
"lstrip": false,
|
| 191 |
+
"normalized": false,
|
| 192 |
+
"rstrip": false,
|
| 193 |
+
"single_word": false,
|
| 194 |
+
"special": false
|
| 195 |
+
},
|
| 196 |
+
"248068": {
|
| 197 |
+
"content": "<think>",
|
| 198 |
+
"lstrip": false,
|
| 199 |
+
"normalized": false,
|
| 200 |
+
"rstrip": false,
|
| 201 |
+
"single_word": false,
|
| 202 |
+
"special": false
|
| 203 |
+
},
|
| 204 |
+
"248069": {
|
| 205 |
+
"content": "</think>",
|
| 206 |
+
"lstrip": false,
|
| 207 |
+
"normalized": false,
|
| 208 |
+
"rstrip": false,
|
| 209 |
+
"single_word": false,
|
| 210 |
+
"special": false
|
| 211 |
+
},
|
| 212 |
+
"248070": {
|
| 213 |
+
"content": "<|audio_start|>",
|
| 214 |
+
"lstrip": false,
|
| 215 |
+
"normalized": false,
|
| 216 |
+
"rstrip": false,
|
| 217 |
+
"single_word": false,
|
| 218 |
+
"special": true
|
| 219 |
+
},
|
| 220 |
+
"248071": {
|
| 221 |
+
"content": "<|audio_end|>",
|
| 222 |
+
"lstrip": false,
|
| 223 |
+
"normalized": false,
|
| 224 |
+
"rstrip": false,
|
| 225 |
+
"single_word": false,
|
| 226 |
+
"special": true
|
| 227 |
+
},
|
| 228 |
+
"248072": {
|
| 229 |
+
"content": "<tts_pad>",
|
| 230 |
+
"lstrip": false,
|
| 231 |
+
"normalized": false,
|
| 232 |
+
"rstrip": false,
|
| 233 |
+
"single_word": false,
|
| 234 |
+
"special": true
|
| 235 |
+
},
|
| 236 |
+
"248073": {
|
| 237 |
+
"content": "<tts_text_bos>",
|
| 238 |
+
"lstrip": false,
|
| 239 |
+
"normalized": false,
|
| 240 |
+
"rstrip": false,
|
| 241 |
+
"single_word": false,
|
| 242 |
+
"special": true
|
| 243 |
+
},
|
| 244 |
+
"248074": {
|
| 245 |
+
"content": "<tts_text_eod>",
|
| 246 |
+
"lstrip": false,
|
| 247 |
+
"normalized": false,
|
| 248 |
+
"rstrip": false,
|
| 249 |
+
"single_word": false,
|
| 250 |
+
"special": true
|
| 251 |
+
},
|
| 252 |
+
"248075": {
|
| 253 |
+
"content": "<tts_text_bos_single>",
|
| 254 |
+
"lstrip": false,
|
| 255 |
+
"normalized": false,
|
| 256 |
+
"rstrip": false,
|
| 257 |
+
"single_word": false,
|
| 258 |
+
"special": true
|
| 259 |
+
},
|
| 260 |
+
"248076": {
|
| 261 |
+
"content": "<|audio_pad|>",
|
| 262 |
+
"lstrip": false,
|
| 263 |
+
"normalized": false,
|
| 264 |
+
"rstrip": false,
|
| 265 |
+
"single_word": false,
|
| 266 |
+
"special": true
|
| 267 |
+
},
|
| 268 |
+
"248077": {
|
| 269 |
+
"content": "<|agnes_bos|>",
|
| 270 |
+
"single_word": false,
|
| 271 |
+
"lstrip": false,
|
| 272 |
+
"rstrip": false,
|
| 273 |
+
"normalized": false,
|
| 274 |
+
"special": true
|
| 275 |
+
},
|
| 276 |
+
"248078": {
|
| 277 |
+
"content": "<|agnes_eos|>",
|
| 278 |
+
"single_word": false,
|
| 279 |
+
"lstrip": false,
|
| 280 |
+
"rstrip": false,
|
| 281 |
+
"normalized": false,
|
| 282 |
+
"special": true
|
| 283 |
+
},
|
| 284 |
+
"248079": {
|
| 285 |
+
"content": "<|agnes_system|>",
|
| 286 |
+
"single_word": false,
|
| 287 |
+
"lstrip": false,
|
| 288 |
+
"rstrip": false,
|
| 289 |
+
"normalized": false,
|
| 290 |
+
"special": true
|
| 291 |
+
},
|
| 292 |
+
"248080": {
|
| 293 |
+
"content": "<|agnes_user|>",
|
| 294 |
+
"single_word": false,
|
| 295 |
+
"lstrip": false,
|
| 296 |
+
"rstrip": false,
|
| 297 |
+
"normalized": false,
|
| 298 |
+
"special": true
|
| 299 |
+
},
|
| 300 |
+
"248081": {
|
| 301 |
+
"content": "<|agnes_assistant|>",
|
| 302 |
+
"single_word": false,
|
| 303 |
+
"lstrip": false,
|
| 304 |
+
"rstrip": false,
|
| 305 |
+
"normalized": false,
|
| 306 |
+
"special": true
|
| 307 |
+
},
|
| 308 |
+
"248082": {
|
| 309 |
+
"content": "<|agnes_tool|>",
|
| 310 |
+
"single_word": false,
|
| 311 |
+
"lstrip": false,
|
| 312 |
+
"rstrip": false,
|
| 313 |
+
"normalized": false,
|
| 314 |
+
"special": true
|
| 315 |
+
},
|
| 316 |
+
"248083": {
|
| 317 |
+
"content": "<|agnes_think_start|>",
|
| 318 |
+
"single_word": false,
|
| 319 |
+
"lstrip": false,
|
| 320 |
+
"rstrip": false,
|
| 321 |
+
"normalized": false,
|
| 322 |
+
"special": true
|
| 323 |
+
},
|
| 324 |
+
"248084": {
|
| 325 |
+
"content": "<|agnes_think_end|>",
|
| 326 |
+
"single_word": false,
|
| 327 |
+
"lstrip": false,
|
| 328 |
+
"rstrip": false,
|
| 329 |
+
"normalized": false,
|
| 330 |
+
"special": true
|
| 331 |
+
},
|
| 332 |
+
"248085": {
|
| 333 |
+
"content": "<|agnes_reserved_0|>",
|
| 334 |
+
"single_word": false,
|
| 335 |
+
"lstrip": false,
|
| 336 |
+
"rstrip": false,
|
| 337 |
+
"normalized": false,
|
| 338 |
+
"special": true
|
| 339 |
+
},
|
| 340 |
+
"248086": {
|
| 341 |
+
"content": "<|agnes_reserved_1|>",
|
| 342 |
+
"single_word": false,
|
| 343 |
+
"lstrip": false,
|
| 344 |
+
"rstrip": false,
|
| 345 |
+
"normalized": false,
|
| 346 |
+
"special": true
|
| 347 |
+
},
|
| 348 |
+
"248087": {
|
| 349 |
+
"content": "<|agnes_reserved_2|>",
|
| 350 |
+
"single_word": false,
|
| 351 |
+
"lstrip": false,
|
| 352 |
+
"rstrip": false,
|
| 353 |
+
"normalized": false,
|
| 354 |
+
"special": true
|
| 355 |
+
},
|
| 356 |
+
"248088": {
|
| 357 |
+
"content": "<|agnes_reserved_3|>",
|
| 358 |
+
"single_word": false,
|
| 359 |
+
"lstrip": false,
|
| 360 |
+
"rstrip": false,
|
| 361 |
+
"normalized": false,
|
| 362 |
+
"special": true
|
| 363 |
+
}
|
| 364 |
+
},
|
| 365 |
+
"additional_special_tokens": [
|
| 366 |
+
"<|im_start|>",
|
| 367 |
+
"<|im_end|>",
|
| 368 |
+
"<|object_ref_start|>",
|
| 369 |
+
"<|object_ref_end|>",
|
| 370 |
+
"<|box_start|>",
|
| 371 |
+
"<|box_end|>",
|
| 372 |
+
"<|quad_start|>",
|
| 373 |
+
"<|quad_end|>",
|
| 374 |
+
"<|vision_start|>",
|
| 375 |
+
"<|vision_end|>",
|
| 376 |
+
"<|vision_pad|>",
|
| 377 |
+
"<|image_pad|>",
|
| 378 |
+
"<|video_pad|>",
|
| 379 |
+
"<|agnes_bos|>",
|
| 380 |
+
"<|agnes_eos|>",
|
| 381 |
+
"<|agnes_system|>",
|
| 382 |
+
"<|agnes_user|>",
|
| 383 |
+
"<|agnes_assistant|>",
|
| 384 |
+
"<|agnes_tool|>",
|
| 385 |
+
"<|agnes_think_start|>",
|
| 386 |
+
"<|agnes_think_end|>",
|
| 387 |
+
"<|agnes_reserved_0|>",
|
| 388 |
+
"<|agnes_reserved_1|>",
|
| 389 |
+
"<|agnes_reserved_2|>",
|
| 390 |
+
"<|agnes_reserved_3|>"
|
| 391 |
+
],
|
| 392 |
+
"bos_token": null,
|
| 393 |
+
"chat_template": "{%- set image_count = namespace(value=0) %}\n{%- set video_count = namespace(value=0) %}\n{%- macro render_content(content, do_vision_count, is_system_content=false) %}\n {%- if content is string %}\n {{- content }}\n {%- elif content is iterable and content is not mapping %}\n {%- for item in content %}\n {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain images.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set image_count.value = image_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Picture ' ~ image_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|image_pad|><|vision_end|>' }}\n {%- elif 'video' in item or item.type == 'video' %}\n {%- if is_system_content %}\n {{- raise_exception('System message cannot contain videos.') }}\n {%- endif %}\n {%- if do_vision_count %}\n {%- set video_count.value = video_count.value + 1 %}\n {%- endif %}\n {%- if add_vision_id %}\n {{- 'Video ' ~ video_count.value ~ ': ' }}\n {%- endif %}\n {{- '<|vision_start|><|video_pad|><|vision_end|>' }}\n {%- elif 'text' in item %}\n {{- item.text }}\n {%- else %}\n {{- raise_exception('Unexpected item type in content.') }}\n {%- endif %}\n {%- endfor %}\n {%- elif content is none or content is undefined %}\n {{- '' }}\n {%- else %}\n {{- raise_exception('Unexpected content type.') }}\n {%- endif %}\n{%- endmacro %}\n{%- if not messages %}\n {{- raise_exception('No messages provided.') }}\n{%- endif %}\n{%- set reasoning_instructions = '' %}\n{%- if enable_thinking is undefined or enable_thinking is true %}\n {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}\n {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}\n {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}\n {%- endif %}\n {%- if resolved_reasoning_effort == 'xhigh' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}\n {%- elif resolved_reasoning_effort == 'low' %}\n {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}\n {%- endif %}\n{%- endif %}\n{%- if tools and tools is iterable and tools is not mapping %}\n {{- '<|im_start|>system\\n' }}\n {%- if reasoning_instructions %}\n {{- reasoning_instructions + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n<tool_call>\\n<function=example_function_name>\\n<parameter=example_parameter_1>\\nvalue_1\\n</parameter>\\n<parameter=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter>\\n</function>\\n</tool_call>\\n\\n<IMPORTANT>\\nReminder:\\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n</IMPORTANT>' }}\n {%- if messages[0].role == 'system' %}\n {%- set content = render_content(messages[0].content, false, true)|trim %}\n {%- if content %}\n {{- '\\n\\n' + content }}\n {%- endif %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {%- set content = render_content(messages[0].content, false, true)|trim %}\n {%- if content %}\n {{- '<|im_start|>system\\n' + (reasoning_instructions + '\\n\\n' if reasoning_instructions else '') + content + '<|im_end|>\\n' }}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n {%- elif reasoning_instructions %}\n {{- '<|im_start|>system\\n' + reasoning_instructions + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" %}\n {%- set content = render_content(message.content, false)|trim %}\n {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if ns.multi_step_tool %}\n {{- raise_exception('No user query found in messages.') }}\n{%- endif %}\n{%- for message in messages %}\n {%- set content = render_content(message.content, true)|trim %}\n {%- if message.role == \"system\" %}\n {%- if not loop.first %}\n {{- raise_exception('System message must be at the beginning.') }}\n {%- endif %}\n {%- elif message.role == \"user\" %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- endif %}\n {%- set reasoning_content = reasoning_content|trim %}\n {%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content + '\\n</think>\\n\\n' + content }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {%- if loop.first %}\n {%- if content|trim %}\n {{- '\\n\\n<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- else %}\n {{- '<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- endif %}\n {%- else %}\n {{- '\\n<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- endif %}\n {%- if tool_call.arguments is defined and tool_call.arguments != '' %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '<parameter=' + args_name + '>\\n' }}\n {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n</parameter>\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '</function>\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Unexpected message role.') }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- else %}\n {{- '<think>\\n' }}\n {%- endif %}\n{%- endif %}",
|
| 394 |
+
"clean_up_tokenization_spaces": false,
|
| 395 |
+
"eos_token": "<|im_end|>",
|
| 396 |
+
"errors": "replace",
|
| 397 |
+
"model_max_length": 262144,
|
| 398 |
+
"pad_token": "<|endoftext|>",
|
| 399 |
+
"split_special_tokens": false,
|
| 400 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 401 |
+
"unk_token": null,
|
| 402 |
+
"add_bos_token": false,
|
| 403 |
+
"pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
|
| 404 |
+
"extra_special_tokens": {
|
| 405 |
+
"audio_bos_token": "<|audio_start|>",
|
| 406 |
+
"audio_eos_token": "<|audio_end|>",
|
| 407 |
+
"audio_token": "<|audio_pad|>",
|
| 408 |
+
"image_token": "<|image_pad|>",
|
| 409 |
+
"video_token": "<|video_pad|>",
|
| 410 |
+
"vision_bos_token": "<|vision_start|>",
|
| 411 |
+
"vision_eos_token": "<|vision_end|>"
|
| 412 |
+
}
|
| 413 |
+
}
|
video_preprocessor_config.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"video_processor_type": "AgnesVideoProcessor",
|
| 3 |
+
"auto_map": {
|
| 4 |
+
"AutoVideoProcessor": "video_processing_agnes.AgnesVideoProcessor"
|
| 5 |
+
},
|
| 6 |
+
"size": {
|
| 7 |
+
"shortest_edge": 131072,
|
| 8 |
+
"longest_edge": 786432
|
| 9 |
+
},
|
| 10 |
+
"patch_size": 16,
|
| 11 |
+
"temporal_patch_size": 2,
|
| 12 |
+
"merge_size": 2,
|
| 13 |
+
"image_mean": [
|
| 14 |
+
0.5,
|
| 15 |
+
0.5,
|
| 16 |
+
0.5
|
| 17 |
+
],
|
| 18 |
+
"image_std": [
|
| 19 |
+
0.5,
|
| 20 |
+
0.5,
|
| 21 |
+
0.5
|
| 22 |
+
],
|
| 23 |
+
"fps": 2,
|
| 24 |
+
"min_frames": 4,
|
| 25 |
+
"max_frames": 768,
|
| 26 |
+
"do_sample_frames": true
|
| 27 |
+
}
|
video_processing_agnes.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Agnes AI. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Video processor for Agnes 3.0 Flash: frame sampling and dynamic-resolution patching."""
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 22 |
+
from transformers.image_utils import ChannelDimension, PILImageResampling, SizeDict, get_image_size
|
| 23 |
+
from transformers.processing_utils import Unpack, VideosKwargs
|
| 24 |
+
from transformers.utils import TensorType, add_start_docstrings, is_torchvision_available, logging
|
| 25 |
+
from transformers.video_processing_utils import BASE_VIDEO_PROCESSOR_DOCSTRING, BaseVideoProcessor
|
| 26 |
+
from transformers.video_utils import VideoMetadata, group_videos_by_shape, reorder_videos
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torchvision_available():
|
| 30 |
+
from torchvision.transforms.v2 import functional as tvF
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def fit_video_to_grid(
|
| 36 |
+
num_frames: int,
|
| 37 |
+
height: int,
|
| 38 |
+
width: int,
|
| 39 |
+
temporal_factor: int = 2,
|
| 40 |
+
factor: int = 32,
|
| 41 |
+
min_pixels: int = 128 * 128,
|
| 42 |
+
max_pixels: int = 16 * 16 * 2 * 2 * 2 * 6144,
|
| 43 |
+
):
|
| 44 |
+
"""Spatial size for a clip: multiples of `factor`, with the frame count
|
| 45 |
+
rounded up to `temporal_factor` and the total voxel count kept inside
|
| 46 |
+
[min_pixels, max_pixels]."""
|
| 47 |
+
if height < factor or width < factor:
|
| 48 |
+
raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
|
| 49 |
+
elif max(height, width) / min(height, width) > 200:
|
| 50 |
+
raise ValueError(f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}")
|
| 51 |
+
h = round(height / factor) * factor
|
| 52 |
+
w = round(width / factor) * factor
|
| 53 |
+
t = math.ceil(num_frames / temporal_factor) * temporal_factor
|
| 54 |
+
if t * h * w > max_pixels:
|
| 55 |
+
scale = math.sqrt((num_frames * height * width) / max_pixels)
|
| 56 |
+
h = max(factor, math.floor(height / scale / factor) * factor)
|
| 57 |
+
w = max(factor, math.floor(width / scale / factor) * factor)
|
| 58 |
+
elif t * h * w < min_pixels:
|
| 59 |
+
scale = math.sqrt(min_pixels / (num_frames * height * width))
|
| 60 |
+
h = math.ceil(height * scale / factor) * factor
|
| 61 |
+
w = math.ceil(width * scale / factor) * factor
|
| 62 |
+
return h, w
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class AgnesVideoProcessorInitKwargs(VideosKwargs, total=False):
|
| 66 |
+
patch_size: int
|
| 67 |
+
temporal_patch_size: int
|
| 68 |
+
merge_size: int
|
| 69 |
+
min_frames: int
|
| 70 |
+
max_frames: int
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@add_start_docstrings(
|
| 74 |
+
"Video processor for Agnes 3.0 Flash; resizes each clip to a patch grid that fits its own resolution.",
|
| 75 |
+
BASE_VIDEO_PROCESSOR_DOCSTRING,
|
| 76 |
+
"""
|
| 77 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 78 |
+
Spatial patch size of the vision tower.
|
| 79 |
+
temporal_patch_size (`int`, *optional*, defaults to 2):
|
| 80 |
+
Temporal patch size of the vision tower.
|
| 81 |
+
merge_size (`int`, *optional*, defaults to 2):
|
| 82 |
+
Side of the patch square merged into one language-model token.
|
| 83 |
+
""",
|
| 84 |
+
)
|
| 85 |
+
class AgnesVideoProcessor(BaseVideoProcessor):
|
| 86 |
+
resample = PILImageResampling.BICUBIC
|
| 87 |
+
size = {"shortest_edge": 128 * 32 * 32, "longest_edge": 32 * 32 * 768}
|
| 88 |
+
image_mean = [0.5, 0.5, 0.5]
|
| 89 |
+
image_std = [0.5, 0.5, 0.5]
|
| 90 |
+
do_resize = True
|
| 91 |
+
do_rescale = True
|
| 92 |
+
do_normalize = True
|
| 93 |
+
do_convert_rgb = True
|
| 94 |
+
patch_size = 16
|
| 95 |
+
temporal_patch_size = 2
|
| 96 |
+
merge_size = 2
|
| 97 |
+
fps = 2
|
| 98 |
+
min_frames = 4
|
| 99 |
+
max_frames = 768
|
| 100 |
+
do_sample_frames = True
|
| 101 |
+
valid_kwargs = AgnesVideoProcessorInitKwargs
|
| 102 |
+
model_input_names = ["pixel_values_videos", "video_grid_thw"]
|
| 103 |
+
|
| 104 |
+
def __init__(self, **kwargs: Unpack[AgnesVideoProcessorInitKwargs]):
|
| 105 |
+
super().__init__(**kwargs)
|
| 106 |
+
|
| 107 |
+
def _standardize_kwargs(self, **kwargs) -> dict:
|
| 108 |
+
kwargs = super()._standardize_kwargs(**kwargs)
|
| 109 |
+
size = kwargs.get("size", self.size)
|
| 110 |
+
if not size.shortest_edge or not size.longest_edge:
|
| 111 |
+
raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
|
| 112 |
+
return kwargs
|
| 113 |
+
|
| 114 |
+
def sample_frames(self, metadata: VideoMetadata, num_frames: int | None = None, fps: int | float | None = None, **kwargs):
|
| 115 |
+
"""Frame indices to keep: `fps` frames per second of source video when
|
| 116 |
+
metadata is available, clamped to [min_frames, max_frames]; `num_frames`
|
| 117 |
+
overrides that. Indices are spread uniformly over the clip."""
|
| 118 |
+
if fps is not None and num_frames is not None:
|
| 119 |
+
raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")
|
| 120 |
+
total = metadata.total_num_frames
|
| 121 |
+
fps = fps if fps is not None else self.fps
|
| 122 |
+
if num_frames is None and fps is not None:
|
| 123 |
+
if metadata.fps is None:
|
| 124 |
+
metadata.fps = 24
|
| 125 |
+
logger.warning_once(
|
| 126 |
+
"Asked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. "
|
| 127 |
+
"Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
|
| 128 |
+
)
|
| 129 |
+
num_frames = int(total / metadata.fps * fps)
|
| 130 |
+
num_frames = min(max(num_frames, self.min_frames), self.max_frames, total)
|
| 131 |
+
if num_frames is None:
|
| 132 |
+
num_frames = min(max(total, self.min_frames), self.max_frames)
|
| 133 |
+
return np.linspace(0, total - 1, num_frames).round().astype(int)
|
| 134 |
+
|
| 135 |
+
def _preprocess(
|
| 136 |
+
self,
|
| 137 |
+
videos: list[torch.Tensor],
|
| 138 |
+
do_convert_rgb: bool = True,
|
| 139 |
+
do_resize: bool = True,
|
| 140 |
+
size: SizeDict | None = None,
|
| 141 |
+
resample: "PILImageResampling | tvF.InterpolationMode | int | None" = PILImageResampling.BICUBIC,
|
| 142 |
+
do_rescale: bool = True,
|
| 143 |
+
rescale_factor: float = 1 / 255.0,
|
| 144 |
+
do_normalize: bool = True,
|
| 145 |
+
image_mean: float | list[float] | None = None,
|
| 146 |
+
image_std: float | list[float] | None = None,
|
| 147 |
+
patch_size: int | None = None,
|
| 148 |
+
temporal_patch_size: int | None = None,
|
| 149 |
+
merge_size: int | None = None,
|
| 150 |
+
return_tensors: str | TensorType | None = None,
|
| 151 |
+
**kwargs,
|
| 152 |
+
):
|
| 153 |
+
# 1. resize, batched per input shape
|
| 154 |
+
by_shape, order = group_videos_by_shape(videos)
|
| 155 |
+
resized = {}
|
| 156 |
+
for shape, batch in by_shape.items():
|
| 157 |
+
if do_convert_rgb:
|
| 158 |
+
batch = self.convert_to_rgb(batch)
|
| 159 |
+
n, t, c, h, w = batch.shape
|
| 160 |
+
if do_resize:
|
| 161 |
+
new_h, new_w = fit_video_to_grid(
|
| 162 |
+
num_frames=t, height=h, width=w, temporal_factor=temporal_patch_size,
|
| 163 |
+
factor=patch_size * merge_size, min_pixels=size.shortest_edge, max_pixels=size.longest_edge,
|
| 164 |
+
)
|
| 165 |
+
batch = self.resize(batch.view(n * t, c, h, w), size=SizeDict(height=new_h, width=new_w), resample=resample)
|
| 166 |
+
batch = batch.view(n, t, c, new_h, new_w)
|
| 167 |
+
resized[shape] = batch
|
| 168 |
+
videos = reorder_videos(resized, order)
|
| 169 |
+
|
| 170 |
+
# 2. normalise, pad the frame count to the temporal patch, cut into patches
|
| 171 |
+
by_shape, order = group_videos_by_shape(videos)
|
| 172 |
+
flat = {}
|
| 173 |
+
grids = {}
|
| 174 |
+
for shape, batch in by_shape.items():
|
| 175 |
+
new_h, new_w = get_image_size(batch[0], channel_dim=ChannelDimension.FIRST)
|
| 176 |
+
px = self.rescale_and_normalize(batch, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
|
| 177 |
+
t = px.shape[1]
|
| 178 |
+
if pad := -t % temporal_patch_size:
|
| 179 |
+
px = torch.cat((px, px[:, -1:].expand(-1, pad, -1, -1, -1)), dim=1)
|
| 180 |
+
n, gt, c = px.shape[:3]
|
| 181 |
+
gt = gt // temporal_patch_size
|
| 182 |
+
gh, gw = new_h // patch_size, new_w // patch_size
|
| 183 |
+
px = px.view(
|
| 184 |
+
n, gt, temporal_patch_size, c, gh // merge_size, merge_size, patch_size, gw // merge_size, merge_size, patch_size
|
| 185 |
+
)
|
| 186 |
+
px = px.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
|
| 187 |
+
flat[shape] = px.reshape(n, gt * gh * gw, c * temporal_patch_size * patch_size * patch_size)
|
| 188 |
+
grids[shape] = [[gt, gh, gw]] * n
|
| 189 |
+
|
| 190 |
+
pixel_values_videos = torch.cat(reorder_videos(flat, order), dim=0)
|
| 191 |
+
video_grid_thw = torch.tensor(reorder_videos(grids, order))
|
| 192 |
+
return BatchFeature(
|
| 193 |
+
data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw}, tensor_type=return_tensors
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
__all__ = ["AgnesVideoProcessor"]
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|