yongqiang
commited on
Commit
·
6602891
1
Parent(s):
ae88b2f
support python api
Browse files- .gitignore +2 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/.gitattributes +35 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/LICENSE +202 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/README.md +108 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/config.json +51 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/generation_config.json +14 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/merges.txt +0 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/tokenizer.json +0 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/tokenizer_config.json +207 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/vocab.json +0 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/model.embed_tokens.weight.npy +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l0_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l10_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l11_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l12_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l13_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l14_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l15_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l16_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l17_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l18_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l19_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l1_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l20_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l21_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l22_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l23_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l24_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l25_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l26_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l27_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l2_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l3_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l4_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l5_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l6_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l7_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l8_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l9_together.axmodel +3 -0
- python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_post.axmodel +3 -0
- python/README.md +66 -0
- python/chat.py +148 -0
- python/infer.py +293 -0
- python/infer_torch.py +33 -0
- python/utils/infer_func.py +383 -0
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
kvcache/
|
2 |
+
__pycache__/
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/LICENSE
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
Apache License
|
3 |
+
Version 2.0, January 2004
|
4 |
+
http://www.apache.org/licenses/
|
5 |
+
|
6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
7 |
+
|
8 |
+
1. Definitions.
|
9 |
+
|
10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
12 |
+
|
13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
14 |
+
the copyright owner that is granting the License.
|
15 |
+
|
16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
17 |
+
other entities that control, are controlled by, or are under common
|
18 |
+
control with that entity. For the purposes of this definition,
|
19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
20 |
+
direction or management of such entity, whether by contract or
|
21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
23 |
+
|
24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
25 |
+
exercising permissions granted by this License.
|
26 |
+
|
27 |
+
"Source" form shall mean the preferred form for making modifications,
|
28 |
+
including but not limited to software source code, documentation
|
29 |
+
source, and configuration files.
|
30 |
+
|
31 |
+
"Object" form shall mean any form resulting from mechanical
|
32 |
+
transformation or translation of a Source form, including but
|
33 |
+
not limited to compiled object code, generated documentation,
|
34 |
+
and conversions to other media types.
|
35 |
+
|
36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
37 |
+
Object form, made available under the License, as indicated by a
|
38 |
+
copyright notice that is included in or attached to the work
|
39 |
+
(an example is provided in the Appendix below).
|
40 |
+
|
41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
42 |
+
form, that is based on (or derived from) the Work and for which the
|
43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
45 |
+
of this License, Derivative Works shall not include works that remain
|
46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
47 |
+
the Work and Derivative Works thereof.
|
48 |
+
|
49 |
+
"Contribution" shall mean any work of authorship, including
|
50 |
+
the original version of the Work and any modifications or additions
|
51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
55 |
+
means any form of electronic, verbal, or written communication sent
|
56 |
+
to the Licensor or its representatives, including but not limited to
|
57 |
+
communication on electronic mailing lists, source code control systems,
|
58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
60 |
+
excluding communication that is conspicuously marked or otherwise
|
61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
62 |
+
|
63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
65 |
+
subsequently incorporated within the Work.
|
66 |
+
|
67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
72 |
+
Work and such Derivative Works in Source or Object form.
|
73 |
+
|
74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
77 |
+
(except as stated in this section) patent license to make, have made,
|
78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
79 |
+
where such license applies only to those patent claims licensable
|
80 |
+
by such Contributor that are necessarily infringed by their
|
81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
83 |
+
institute patent litigation against any entity (including a
|
84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
85 |
+
or a Contribution incorporated within the Work constitutes direct
|
86 |
+
or contributory patent infringement, then any patent licenses
|
87 |
+
granted to You under this License for that Work shall terminate
|
88 |
+
as of the date such litigation is filed.
|
89 |
+
|
90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
91 |
+
Work or Derivative Works thereof in any medium, with or without
|
92 |
+
modifications, and in Source or Object form, provided that You
|
93 |
+
meet the following conditions:
|
94 |
+
|
95 |
+
(a) You must give any other recipients of the Work or
|
96 |
+
Derivative Works a copy of this License; and
|
97 |
+
|
98 |
+
(b) You must cause any modified files to carry prominent notices
|
99 |
+
stating that You changed the files; and
|
100 |
+
|
101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
102 |
+
that You distribute, all copyright, patent, trademark, and
|
103 |
+
attribution notices from the Source form of the Work,
|
104 |
+
excluding those notices that do not pertain to any part of
|
105 |
+
the Derivative Works; and
|
106 |
+
|
107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
108 |
+
distribution, then any Derivative Works that You distribute must
|
109 |
+
include a readable copy of the attribution notices contained
|
110 |
+
within such NOTICE file, excluding those notices that do not
|
111 |
+
pertain to any part of the Derivative Works, in at least one
|
112 |
+
of the following places: within a NOTICE text file distributed
|
113 |
+
as part of the Derivative Works; within the Source form or
|
114 |
+
documentation, if provided along with the Derivative Works; or,
|
115 |
+
within a display generated by the Derivative Works, if and
|
116 |
+
wherever such third-party notices normally appear. The contents
|
117 |
+
of the NOTICE file are for informational purposes only and
|
118 |
+
do not modify the License. You may add Your own attribution
|
119 |
+
notices within Derivative Works that You distribute, alongside
|
120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
121 |
+
that such additional attribution notices cannot be construed
|
122 |
+
as modifying the License.
|
123 |
+
|
124 |
+
You may add Your own copyright statement to Your modifications and
|
125 |
+
may provide additional or different license terms and conditions
|
126 |
+
for use, reproduction, or distribution of Your modifications, or
|
127 |
+
for any such Derivative Works as a whole, provided Your use,
|
128 |
+
reproduction, and distribution of the Work otherwise complies with
|
129 |
+
the conditions stated in this License.
|
130 |
+
|
131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
133 |
+
by You to the Licensor shall be under the terms and conditions of
|
134 |
+
this License, without any additional terms or conditions.
|
135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
136 |
+
the terms of any separate license agreement you may have executed
|
137 |
+
with Licensor regarding such Contributions.
|
138 |
+
|
139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
141 |
+
except as required for reasonable and customary use in describing the
|
142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
143 |
+
|
144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
145 |
+
agreed to in writing, Licensor provides the Work (and each
|
146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
148 |
+
implied, including, without limitation, any warranties or conditions
|
149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
151 |
+
appropriateness of using or redistributing the Work and assume any
|
152 |
+
risks associated with Your exercise of permissions under this License.
|
153 |
+
|
154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
155 |
+
whether in tort (including negligence), contract, or otherwise,
|
156 |
+
unless required by applicable law (such as deliberate and grossly
|
157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
158 |
+
liable to You for damages, including any direct, indirect, special,
|
159 |
+
incidental, or consequential damages of any character arising as a
|
160 |
+
result of this License or out of the use or inability to use the
|
161 |
+
Work (including but not limited to damages for loss of goodwill,
|
162 |
+
work stoppage, computer failure or malfunction, or any and all
|
163 |
+
other commercial damages or losses), even if such Contributor
|
164 |
+
has been advised of the possibility of such damages.
|
165 |
+
|
166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
169 |
+
or other liability obligations and/or rights consistent with this
|
170 |
+
License. However, in accepting such obligations, You may act only
|
171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
172 |
+
of any other Contributor, and only if You agree to indemnify,
|
173 |
+
defend, and hold each Contributor harmless for any liability
|
174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
175 |
+
of your accepting any such warranty or additional liability.
|
176 |
+
|
177 |
+
END OF TERMS AND CONDITIONS
|
178 |
+
|
179 |
+
APPENDIX: How to apply the Apache License to your work.
|
180 |
+
|
181 |
+
To apply the Apache License to your work, attach the following
|
182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
183 |
+
replaced with your own identifying information. (Don't include
|
184 |
+
the brackets!) The text should be enclosed in the appropriate
|
185 |
+
comment syntax for the file format. We also recommend that a
|
186 |
+
file or class name and description of purpose be included on the
|
187 |
+
same "printed page" as the copyright notice for easier
|
188 |
+
identification within third-party archives.
|
189 |
+
|
190 |
+
Copyright 2024 Alibaba Cloud
|
191 |
+
|
192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
193 |
+
you may not use this file except in compliance with the License.
|
194 |
+
You may obtain a copy of the License at
|
195 |
+
|
196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
197 |
+
|
198 |
+
Unless required by applicable law or agreed to in writing, software
|
199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
201 |
+
See the License for the specific language governing permissions and
|
202 |
+
limitations under the License.
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/README.md
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
base_model: Qwen/Qwen2.5-1.5B-Instruct
|
3 |
+
language:
|
4 |
+
- en
|
5 |
+
library_name: transformers
|
6 |
+
license: apache-2.0
|
7 |
+
license_link: https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GPTQ-Int8/blob/main/LICENSE
|
8 |
+
pipeline_tag: text-generation
|
9 |
+
tags:
|
10 |
+
- chat
|
11 |
+
---
|
12 |
+
# Qwen2.5-1.5B-Instruct-GPTQ-Int8
|
13 |
+
|
14 |
+
## Introduction
|
15 |
+
|
16 |
+
Qwen2.5 is the latest series of Qwen large language models. For Qwen2.5, we release a number of base language models and instruction-tuned language models ranging from 0.5 to 72 billion parameters. Qwen2.5 brings the following improvements upon Qwen2:
|
17 |
+
|
18 |
+
- Significantly **more knowledge** and has greatly improved capabilities in **coding** and **mathematics**, thanks to our specialized expert models in these domains.
|
19 |
+
- Significant improvements in **instruction following**, **generating long texts** (over 8K tokens), **understanding structured data** (e.g, tables), and **generating structured outputs** especially JSON. **More resilient to the diversity of system prompts**, enhancing role-play implementation and condition-setting for chatbots.
|
20 |
+
- **Long-context Support** up to 128K tokens and can generate up to 8K tokens.
|
21 |
+
- **Multilingual support** for over 29 languages, including Chinese, English, French, Spanish, Portuguese, German, Italian, Russian, Japanese, Korean, Vietnamese, Thai, Arabic, and more.
|
22 |
+
|
23 |
+
**This repo contains the GPTQ-quantized 8-bit instruction-tuned 1.5B Qwen2.5 model**, which has the following features:
|
24 |
+
- Type: Causal Language Models
|
25 |
+
- Training Stage: Pretraining & Post-training
|
26 |
+
- Architecture: transformers with RoPE, SwiGLU, RMSNorm, Attention QKV bias and tied word embeddings
|
27 |
+
- Number of Parameters: 1.54B
|
28 |
+
- Number of Paramaters (Non-Embedding): 1.31B
|
29 |
+
- Number of Layers: 28
|
30 |
+
- Number of Attention Heads (GQA): 12 for Q and 2 for KV
|
31 |
+
- Context Length: Full 32,768 tokens and generation 8192 tokens
|
32 |
+
- Quantization: GPTQ 8-bit
|
33 |
+
|
34 |
+
For more details, please refer to our [blog](https://qwenlm.github.io/blog/qwen2.5/), [GitHub](https://github.com/QwenLM/Qwen2.5), and [Documentation](https://qwen.readthedocs.io/en/latest/).
|
35 |
+
|
36 |
+
## Requirements
|
37 |
+
|
38 |
+
The code of Qwen2.5 has been in the latest Hugging face `transformers` and we advise you to use the latest version of `transformers`.
|
39 |
+
|
40 |
+
With `transformers<4.37.0`, you will encounter the following error:
|
41 |
+
```
|
42 |
+
KeyError: 'qwen2'
|
43 |
+
```
|
44 |
+
|
45 |
+
Also check out our [GPTQ documentation](https://qwen.readthedocs.io/en/latest/quantization/gptq.html) for more usage guide.
|
46 |
+
|
47 |
+
## Quickstart
|
48 |
+
|
49 |
+
Here provides a code snippet with `apply_chat_template` to show you how to load the tokenizer and model and how to generate contents.
|
50 |
+
|
51 |
+
```python
|
52 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
53 |
+
model_name = "Qwen/Qwen2.5-1.5B-Instruct-GPTQ-Int8"
|
54 |
+
model = AutoModelForCausalLM.from_pretrained(
|
55 |
+
model_name,
|
56 |
+
torch_dtype="auto",
|
57 |
+
device_map="auto"
|
58 |
+
)
|
59 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
60 |
+
prompt = "Give me a short introduction to large language model."
|
61 |
+
messages = [
|
62 |
+
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
|
63 |
+
{"role": "user", "content": prompt}
|
64 |
+
]
|
65 |
+
text = tokenizer.apply_chat_template(
|
66 |
+
messages,
|
67 |
+
tokenize=False,
|
68 |
+
add_generation_prompt=True
|
69 |
+
)
|
70 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
71 |
+
generated_ids = model.generate(
|
72 |
+
**model_inputs,
|
73 |
+
max_new_tokens=512
|
74 |
+
)
|
75 |
+
generated_ids = [
|
76 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
77 |
+
]
|
78 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
79 |
+
```
|
80 |
+
|
81 |
+
|
82 |
+
## Evaluation & Performance
|
83 |
+
|
84 |
+
Detailed evaluation results are reported in this [📑 blog](https://qwenlm.github.io/blog/qwen2.5/).
|
85 |
+
|
86 |
+
For quantized models, the benchmark results against the original bfloat16 models can be found [here](https://qwen.readthedocs.io/en/latest/benchmark/quantization_benchmark.html)
|
87 |
+
|
88 |
+
For requirements on GPU memory and the respective throughput, see results [here](https://qwen.readthedocs.io/en/latest/benchmark/speed_benchmark.html).
|
89 |
+
|
90 |
+
## Citation
|
91 |
+
|
92 |
+
If you find our work helpful, feel free to give us a cite.
|
93 |
+
|
94 |
+
```
|
95 |
+
@misc{qwen2.5,
|
96 |
+
title = {Qwen2.5: A Party of Foundation Models},
|
97 |
+
url = {https://qwenlm.github.io/blog/qwen2.5/},
|
98 |
+
author = {Qwen Team},
|
99 |
+
month = {September},
|
100 |
+
year = {2024}
|
101 |
+
}
|
102 |
+
@article{qwen2,
|
103 |
+
title={Qwen2 Technical Report},
|
104 |
+
author={An Yang and Baosong Yang and Binyuan Hui and Bo Zheng and Bowen Yu and Chang Zhou and Chengpeng Li and Chengyuan Li and Dayiheng Liu and Fei Huang and Guanting Dong and Haoran Wei and Huan Lin and Jialong Tang and Jialin Wang and Jian Yang and Jianhong Tu and Jianwei Zhang and Jianxin Ma and Jin Xu and Jingren Zhou and Jinze Bai and Jinzheng He and Junyang Lin and Kai Dang and Keming Lu and Keqin Chen and Kexin Yang and Mei Li and Mingfeng Xue and Na Ni and Pei Zhang and Peng Wang and Ru Peng and Rui Men and Ruize Gao and Runji Lin and Shijie Wang and Shuai Bai and Sinan Tan and Tianhang Zhu and Tianhao Li and Tianyu Liu and Wenbin Ge and Xiaodong Deng and Xiaohuan Zhou and Xingzhang Ren and Xinyu Zhang and Xipin Wei and Xuancheng Ren and Yang Fan and Yang Yao and Yichang Zhang and Yu Wan and Yunfei Chu and Yuqiong Liu and Zeyu Cui and Zhenru Zhang and Zhihao Fan},
|
105 |
+
journal={arXiv preprint arXiv:2407.10671},
|
106 |
+
year={2024}
|
107 |
+
}
|
108 |
+
```
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/config.json
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Qwen2ForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_dropout": 0.0,
|
6 |
+
"bos_token_id": 151643,
|
7 |
+
"eos_token_id": 151645,
|
8 |
+
"hidden_act": "silu",
|
9 |
+
"hidden_size": 1536,
|
10 |
+
"initializer_range": 0.02,
|
11 |
+
"intermediate_size": 8960,
|
12 |
+
"max_position_embeddings": 32768,
|
13 |
+
"max_window_layers": 21,
|
14 |
+
"model_type": "qwen2",
|
15 |
+
"num_attention_heads": 12,
|
16 |
+
"num_hidden_layers": 28,
|
17 |
+
"num_key_value_heads": 2,
|
18 |
+
"quantization_config": {
|
19 |
+
"batch_size": 1,
|
20 |
+
"bits": 8,
|
21 |
+
"block_name_to_quantize": null,
|
22 |
+
"cache_block_outputs": true,
|
23 |
+
"damp_percent": 0.01,
|
24 |
+
"dataset": null,
|
25 |
+
"desc_act": false,
|
26 |
+
"exllama_config": {
|
27 |
+
"version": 1
|
28 |
+
},
|
29 |
+
"group_size": 128,
|
30 |
+
"max_input_length": null,
|
31 |
+
"model_seqlen": null,
|
32 |
+
"module_name_preceding_first_block": null,
|
33 |
+
"modules_in_block_to_quantize": null,
|
34 |
+
"pad_token_id": null,
|
35 |
+
"quant_method": "gptq",
|
36 |
+
"sym": true,
|
37 |
+
"tokenizer": null,
|
38 |
+
"true_sequential": true,
|
39 |
+
"use_cuda_fp16": false,
|
40 |
+
"use_exllama": true
|
41 |
+
},
|
42 |
+
"rms_norm_eps": 1e-06,
|
43 |
+
"rope_theta": 1000000.0,
|
44 |
+
"sliding_window": 32768,
|
45 |
+
"tie_word_embeddings": true,
|
46 |
+
"torch_dtype": "float16",
|
47 |
+
"transformers_version": "4.39.3",
|
48 |
+
"use_cache": true,
|
49 |
+
"use_sliding_window": false,
|
50 |
+
"vocab_size": 151936
|
51 |
+
}
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/generation_config.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": [
|
5 |
+
151645,
|
6 |
+
151643
|
7 |
+
],
|
8 |
+
"pad_token_id": 151643,
|
9 |
+
"repetition_penalty": 1.1,
|
10 |
+
"temperature": 0.7,
|
11 |
+
"top_k": 20,
|
12 |
+
"top_p": 0.8,
|
13 |
+
"transformers_version": "4.39.3"
|
14 |
+
}
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/tokenizer_config.json
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"151643": {
|
6 |
+
"content": "<|endoftext|>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"151644": {
|
14 |
+
"content": "<|im_start|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"151645": {
|
22 |
+
"content": "<|im_end|>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"151646": {
|
30 |
+
"content": "<|object_ref_start|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"151647": {
|
38 |
+
"content": "<|object_ref_end|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"151648": {
|
46 |
+
"content": "<|box_start|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"151649": {
|
54 |
+
"content": "<|box_end|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"151650": {
|
62 |
+
"content": "<|quad_start|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"151651": {
|
70 |
+
"content": "<|quad_end|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"151652": {
|
78 |
+
"content": "<|vision_start|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
},
|
85 |
+
"151653": {
|
86 |
+
"content": "<|vision_end|>",
|
87 |
+
"lstrip": false,
|
88 |
+
"normalized": false,
|
89 |
+
"rstrip": false,
|
90 |
+
"single_word": false,
|
91 |
+
"special": true
|
92 |
+
},
|
93 |
+
"151654": {
|
94 |
+
"content": "<|vision_pad|>",
|
95 |
+
"lstrip": false,
|
96 |
+
"normalized": false,
|
97 |
+
"rstrip": false,
|
98 |
+
"single_word": false,
|
99 |
+
"special": true
|
100 |
+
},
|
101 |
+
"151655": {
|
102 |
+
"content": "<|image_pad|>",
|
103 |
+
"lstrip": false,
|
104 |
+
"normalized": false,
|
105 |
+
"rstrip": false,
|
106 |
+
"single_word": false,
|
107 |
+
"special": true
|
108 |
+
},
|
109 |
+
"151656": {
|
110 |
+
"content": "<|video_pad|>",
|
111 |
+
"lstrip": false,
|
112 |
+
"normalized": false,
|
113 |
+
"rstrip": false,
|
114 |
+
"single_word": false,
|
115 |
+
"special": true
|
116 |
+
},
|
117 |
+
"151657": {
|
118 |
+
"content": "<tool_call>",
|
119 |
+
"lstrip": false,
|
120 |
+
"normalized": false,
|
121 |
+
"rstrip": false,
|
122 |
+
"single_word": false,
|
123 |
+
"special": false
|
124 |
+
},
|
125 |
+
"151658": {
|
126 |
+
"content": "</tool_call>",
|
127 |
+
"lstrip": false,
|
128 |
+
"normalized": false,
|
129 |
+
"rstrip": false,
|
130 |
+
"single_word": false,
|
131 |
+
"special": false
|
132 |
+
},
|
133 |
+
"151659": {
|
134 |
+
"content": "<|fim_prefix|>",
|
135 |
+
"lstrip": false,
|
136 |
+
"normalized": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"single_word": false,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
"151660": {
|
142 |
+
"content": "<|fim_middle|>",
|
143 |
+
"lstrip": false,
|
144 |
+
"normalized": false,
|
145 |
+
"rstrip": false,
|
146 |
+
"single_word": false,
|
147 |
+
"special": false
|
148 |
+
},
|
149 |
+
"151661": {
|
150 |
+
"content": "<|fim_suffix|>",
|
151 |
+
"lstrip": false,
|
152 |
+
"normalized": false,
|
153 |
+
"rstrip": false,
|
154 |
+
"single_word": false,
|
155 |
+
"special": false
|
156 |
+
},
|
157 |
+
"151662": {
|
158 |
+
"content": "<|fim_pad|>",
|
159 |
+
"lstrip": false,
|
160 |
+
"normalized": false,
|
161 |
+
"rstrip": false,
|
162 |
+
"single_word": false,
|
163 |
+
"special": false
|
164 |
+
},
|
165 |
+
"151663": {
|
166 |
+
"content": "<|repo_name|>",
|
167 |
+
"lstrip": false,
|
168 |
+
"normalized": false,
|
169 |
+
"rstrip": false,
|
170 |
+
"single_word": false,
|
171 |
+
"special": false
|
172 |
+
},
|
173 |
+
"151664": {
|
174 |
+
"content": "<|file_sep|>",
|
175 |
+
"lstrip": false,
|
176 |
+
"normalized": false,
|
177 |
+
"rstrip": false,
|
178 |
+
"single_word": false,
|
179 |
+
"special": false
|
180 |
+
}
|
181 |
+
},
|
182 |
+
"additional_special_tokens": [
|
183 |
+
"<|im_start|>",
|
184 |
+
"<|im_end|>",
|
185 |
+
"<|object_ref_start|>",
|
186 |
+
"<|object_ref_end|>",
|
187 |
+
"<|box_start|>",
|
188 |
+
"<|box_end|>",
|
189 |
+
"<|quad_start|>",
|
190 |
+
"<|quad_end|>",
|
191 |
+
"<|vision_start|>",
|
192 |
+
"<|vision_end|>",
|
193 |
+
"<|vision_pad|>",
|
194 |
+
"<|image_pad|>",
|
195 |
+
"<|video_pad|>"
|
196 |
+
],
|
197 |
+
"bos_token": null,
|
198 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\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 {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
|
199 |
+
"clean_up_tokenization_spaces": false,
|
200 |
+
"eos_token": "<|im_end|>",
|
201 |
+
"errors": "replace",
|
202 |
+
"model_max_length": 131072,
|
203 |
+
"pad_token": "<|endoftext|>",
|
204 |
+
"split_special_tokens": false,
|
205 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
206 |
+
"unk_token": null
|
207 |
+
}
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8/vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/model.embed_tokens.weight.npy
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ed88f4777c1c2833acf5856969c6a1addd3c864f1a559cd9126bf41abae738d8
|
3 |
+
size 933494912
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l0_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e81fa679403fae5fd9133688a0d3743778c9e894b49a5fd7b83c935d0d6bd401
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l10_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:44170306131f3963a6882b76e2719b2c8721d1e9d5e7a35f6d0c20ca0fb64246
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l11_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0240f5d11a461d35557df63de9493304c3381b58644e8813536ad1b3bc3b6168
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l12_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:76619b6d5d4a6b0f42ed84ef16b0b27aee8628556eaeecc31effcf6c8b41e331
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l13_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ebbe60eb839ac5585ca2a8759c49bbc5ee774184a5ee29a2b5d914174110d3a2
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l14_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e71042e3052119526c4ae3042ebc5dbbc7d6100f95cf388dc5ca32dd53b3d3e7
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l15_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:181bda9a623e1baa67f9e10b2030914e6358d1e04d01b18bcdd18b4112d5a803
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l16_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:17e06df70da8d754b43424498c31e41145d2bb1d2bca197d4ee1cf9b097482ed
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l17_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9beab8e6d5307368c11006f24bb48b3f3676913409a098f4cc45adb9d9481e06
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l18_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8f9c085e9a540d8f8c39bd2572d79c468ae19b70e2ca7dff1b844e982d96bdaa
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l19_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b7b290a434654a439efdc5691bfcfe0257cc095a7e26c03c4a416772f0724256
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l1_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5b626984808bdfa2c3b627dd47928a11ad2ee8f0aeb80a2f70963a7b9e7c46eb
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l20_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:82026614086a56dff0fff03fb64b50838fb7f03013eb035060537bcfd4f4bfcf
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l21_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:71031f6c51ceb4364a8595255decce5ecdb5f151507ee1dd38496db08526fa96
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l22_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8eceb8bb8111c2bb6214452e1624077ad6e9e33f75f921ad38f45a8073322532
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l23_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e47264e1859b0180de836aaf4878f553680e79923e3f3a801ab20231493436c
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l24_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c71c41353a74a2bc80ac453f5be777c020f032c557388057b6e84a3841faa1cb
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l25_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6162ccecef02151a53f167dfdfc05e066d8f6c218b47fc203c59b640b173b033
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l26_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:984cf40d35fd51c746a51e6cf2038d7258a2efc726fa70453f396c02330f388a
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l27_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:02c14a06311b03bd758cf65791ee246bbd863cf3a7190bbd72e7053dc0dd5474
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l2_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:37f118ede5bc95656bc92870bbd8f98e618cc52b2e5b2fbbcc235fbe6bf3756c
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l3_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1272b0b851cd3d1b3b0f48dab3a8b81d51a0807af5e98223c3a381e70262b158
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l4_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7d317275c5ec06f8a595260b4b0da68cdd9177378ae09c3288a70863a9be18b7
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l5_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d8917ba65810c8bd3443487c3d54620c26dde710d8085030ac282a4a0cfc623a
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l6_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:38d52da0b14e893a8c8ef49a1c2c6b3971a96374fb071877b47c12f816c54383
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l7_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ddabded897444e9134436bef06f952ff93c470aa5842e402872aa0be2faad5a3
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l8_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:bc97d91c2ac7722f5a20bb2eac311b03cd7bdec5cf0a276efb5e55fe971a4bcf
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_p128_l9_together.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0adfa01ebda693d6e7d2223fbf5f3b4bc4388e26c9c4a62caab4b13964e58c3b
|
3 |
+
size 56668628
|
python/Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/qwen2_post.axmodel
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b4e804fe1247c2297dd610e1016a66e830add3fa2fd44f21224f4c3a563500e4
|
3 |
+
size 254449571
|
python/README.md
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
在 `AXERA 650N` 开发板上使用 `python api` 进行模型推理.
|
2 |
+
|
3 |
+
在当前目录执行以下命令:
|
4 |
+
|
5 |
+
```sh
|
6 |
+
$ python3 chat.py
|
7 |
+
```
|
8 |
+
|
9 |
+
当出现 `prompt (输入 q 退出对话) >>` 提示时输入文字, 等待模型输出, 具体示例如下:
|
10 |
+
|
11 |
+
```bash
|
12 |
+
$ python3 chat.py
|
13 |
+
...
|
14 |
+
The models have been loaded!
|
15 |
+
2025-07-21 14:23:46.137 | DEBUG | __main__:<module>:143 - >>> 创建 LlamaChatSession >>>
|
16 |
+
>>> 系统提示: 你的名字叫小智(allen), 你是一个人畜无害的 AI 助手. 深圳市今天(4月1日)阴天, 愚人节, 气温在 14°C 至 19°C
|
17 |
+
之间, 微风.
|
18 |
+
2025-07-21 14:23:46.137 | INFO | __main__:chat_loop:69 - Type 'q' to exit, Ctrl+c to stop current generation
|
19 |
+
|
20 |
+
prompt (输入 q 退出对话) >> 定义函数y=3x^3+2x+1,求解它的导数.
|
21 |
+
answer: >> 要找到函数 \( y = 3x^3 + 2x + 1 \) 的导数,我们需要对每个项分别求导,然后将它们相加起来。
|
22 |
+
|
23 |
+
1. 对 \( 3x^3 \) ���导,结果是 \( 3 \cdot 3x^{3-1} = 9x^2 \)。
|
24 |
+
2. 对 \( 2x \) ���导,结果是 \( 2 \cdot 1x^{1-1} = 2 \)。
|
25 |
+
3. 对常数项 \( 1 \) ���导,结果是 \( 0 \)。
|
26 |
+
|
27 |
+
将这些结果相加,我们得到:
|
28 |
+
|
29 |
+
\[ y' = 9x^2 + 2 \]
|
30 |
+
|
31 |
+
所以,函数 \( y = 3x^3 + 2x + 1 \) 的导数是 \( y' = 9x^2 + 2 \)。
|
32 |
+
|
33 |
+
prompt (输入 q 退出对话) >> 这个函数中自变量和因变量分别是什么?
|
34 |
+
answer: >> 在数学中,函数通常由两个变量组成:自变量(也称为输入变量)和因变量(也称为输出变量)。自变量是函数中的一个
|
35 |
+
量,它的值决定了因变量的值。
|
36 |
+
|
37 |
+
在你提供的函数 \( y = 3x^3 + 2x + 1 \) 中:
|
38 |
+
|
39 |
+
- \( x \) 是自变量。
|
40 |
+
- \( y \) 是因变量。
|
41 |
+
|
42 |
+
自变量 \( x \) 的值决定了因变量 \( y \) 的值。例如,如果你给 \( x \) ���值为 2,那么 \( y \) ��等于 \( 3(2)^3 + 2(2) +
|
43 |
+
1 = 24 + 4 + 1 = 29 \)。
|
44 |
+
|
45 |
+
因此,这个函数描述了一个关于 \( x \) 和 \( y \) 的关系,其中 \( x \) 是自变量,而 \( y \) 是因变量。通过改变 \( x \)
|
46 |
+
值,你可以计算出相应的 \( y \) ���。
|
47 |
+
|
48 |
+
prompt (输入 q 退出对话) >> 这个函数中最高幂次和最低幂次分别是多少?
|
49 |
+
answer: >> 在函数 \( y = 3x^3 + 2x + 1 \) 中,最高次幂(最高幂次)是 \( x^3 \),因此最高幂次是 3。
|
50 |
+
|
51 |
+
最低次幂(最低幂次)是 \( x^0 \),因为 \( x^0 = 1 \) 对于任何 \( x \) ���成立,所以最低幂次是 0。
|
52 |
+
|
53 |
+
因此,这个函数的最高幂次是 3,最低幂次是 0。最高幂次和最低幂次的差值是 \( 3 - 0 = 3 \)。这意味着函数的图形是一个三次多
|
54 |
+
式,它有一个顶点(如果最高幂次是偶数)或一个拐点(如果最高幂次是奇数)。在这个例子中,由于最高幂次是奇数,函数的图形
|
55 |
+
有一个拐点。
|
56 |
+
|
57 |
+
```
|
58 |
+
|
59 |
+
当上下文窗口达到上限, 可以输入 `reset` 命令重置, 例如:
|
60 |
+
|
61 |
+
```sh
|
62 |
+
prompt (输入 q 退出对话) >> reset
|
63 |
+
上下文已重置
|
64 |
+
prompt (输入 q 退出对话) >> 你是谁?今天天气如何?
|
65 |
+
answer: >> 我是小智,一名人工智能助手。今天是阴天,愚人节,气温在14°C至19°C之间,微风。
|
66 |
+
```
|
python/chat.py
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import numpy as np
|
3 |
+
import os
|
4 |
+
import json
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import List, Tuple, Dict, Optional
|
7 |
+
from ml_dtypes import bfloat16
|
8 |
+
import dataclasses
|
9 |
+
from transformers import AutoTokenizer, AutoConfig
|
10 |
+
import torch
|
11 |
+
from torchvision.transforms.functional import InterpolationMode
|
12 |
+
from axengine import InferenceSession
|
13 |
+
from tqdm import tqdm
|
14 |
+
import torchvision.transforms as T
|
15 |
+
from PIL import Image
|
16 |
+
import argparse
|
17 |
+
from loguru import logger
|
18 |
+
from copy import deepcopy
|
19 |
+
from utils.infer_func import InferManager, KVCacheTools
|
20 |
+
|
21 |
+
|
22 |
+
class LlamaChatSession:
|
23 |
+
def __init__(self, builder_instance):
|
24 |
+
self.system_prompt = builder_instance.system_prompt
|
25 |
+
self.builder_instance = builder_instance
|
26 |
+
self.last_reply = ""
|
27 |
+
|
28 |
+
def encode(self, prompt: str) -> Tuple[List[int], List[int]]:
|
29 |
+
"""
|
30 |
+
keys: "message", "model_inputs", "input_ids", "input_embeds", "input_ids_len"
|
31 |
+
"""
|
32 |
+
return self.builder_instance.encoder_prompt(prompt)
|
33 |
+
|
34 |
+
def get_kvcache(self) -> Tuple[List[np.ndarray], List[np.ndarray], int]:
|
35 |
+
return self.builder_instance.k_caches, self.builder_instance.v_caches
|
36 |
+
|
37 |
+
def generate(self,
|
38 |
+
model_inputs
|
39 |
+
):
|
40 |
+
token_ids = model_inputs["input_ids"]
|
41 |
+
self.builder_instance.decode(token_ids)
|
42 |
+
return None
|
43 |
+
|
44 |
+
def run(self, model_inputs) -> str:
|
45 |
+
response = self.generate(
|
46 |
+
model_inputs
|
47 |
+
)
|
48 |
+
return response
|
49 |
+
|
50 |
+
def reset_context(self, system_prompt: str = None):
|
51 |
+
"""
|
52 |
+
reset 只需要把 kv cache 清空即可 (甚至可以直接复写)
|
53 |
+
但如果 system_prompt 变化了,则需要重新计算 kv cache
|
54 |
+
"""
|
55 |
+
if system_prompt is not None:
|
56 |
+
self.system_prompt = system_prompt
|
57 |
+
|
58 |
+
self.builder_instance.precompute_len = self.builder_instance.system_input_ids_len
|
59 |
+
|
60 |
+
for i in range(len(self.builder_instance.k_caches)):
|
61 |
+
self.builder_instance.k_caches[i][:, self.builder_instance.precompute_len:, :].fill(0)
|
62 |
+
self.builder_instance.v_caches[i][:, self.builder_instance.precompute_len:, :].fill(0)
|
63 |
+
|
64 |
+
def chat_loop(self, live_print: bool = False):
|
65 |
+
|
66 |
+
if self.system_prompt:
|
67 |
+
print(f">>> 系统提示: {self.system_prompt}")
|
68 |
+
|
69 |
+
logger.info("Type 'q' to exit, Ctrl+c to stop current generation\n")
|
70 |
+
|
71 |
+
while True:
|
72 |
+
try:
|
73 |
+
prompt = input("prompt (输入 q 退出对话) >> ")
|
74 |
+
|
75 |
+
if prompt.lower() == "q" or prompt.lower() == "exit":
|
76 |
+
print("\nOK, 已退出对话.")
|
77 |
+
return
|
78 |
+
|
79 |
+
if prompt.lower() == "debug":
|
80 |
+
print(f"\n>>> DEBUG INFO >>>\n precompute_len is {self.builder_instance.precompute_len}\n<<< DEBUG INFO <<<\n")
|
81 |
+
continue
|
82 |
+
|
83 |
+
if not prompt.strip():
|
84 |
+
print(f"\n{self.system_prompt}")
|
85 |
+
continue
|
86 |
+
|
87 |
+
if prompt.strip() == "reset":
|
88 |
+
self.reset_context()
|
89 |
+
print("上下文已重置")
|
90 |
+
continue
|
91 |
+
|
92 |
+
model_inputs = self.encode(prompt)
|
93 |
+
|
94 |
+
if self.builder_instance.precompute_len + 128 >= 2559:
|
95 |
+
logger.info("ERROR: 上下文窗口已满! 请使用 `reset` 命令重置上下文")
|
96 |
+
continue
|
97 |
+
|
98 |
+
response = self.run(model_inputs)
|
99 |
+
|
100 |
+
except KeyboardInterrupt:
|
101 |
+
# 处理用户按 Ctrl+C 中断生成
|
102 |
+
print("\n好的, 已成功退出对话.")
|
103 |
+
exit()
|
104 |
+
|
105 |
+
except Exception as e:
|
106 |
+
print(f"ERROR: {str(e)}")
|
107 |
+
|
108 |
+
|
109 |
+
if __name__ == "__main__":
|
110 |
+
|
111 |
+
hf_model_path = './Qwen2.5-1.5B-Instruct-GPTQ-Int8/'
|
112 |
+
axmodel_model_path = './Qwen2.5-1.5B-Instruct-GPTQ-Int8_axmodel/'
|
113 |
+
|
114 |
+
builder = InferManager(hf_model_path, axmodel_model_path) # init tokenizer & hf_config & system prompt
|
115 |
+
builder.build_system_prompt()
|
116 |
+
builder.build_kvcache()
|
117 |
+
builder.build_infer_model()
|
118 |
+
|
119 |
+
cache_manager = KVCacheTools(axmodel_num=28, dtype=bfloat16)
|
120 |
+
|
121 |
+
if not os.path.exists("./kvcache"):
|
122 |
+
# 预计算 system prompt k,v 缓存
|
123 |
+
update_kv_cache = builder.prefill(
|
124 |
+
builder.model_inputs,
|
125 |
+
slice_len=128,
|
126 |
+
)
|
127 |
+
if cache_manager.save_kvcache(
|
128 |
+
target_dir="./kvcache",
|
129 |
+
system_prompt=builder.system_prompt,
|
130 |
+
precompute_len=builder.system_input_ids_len,
|
131 |
+
k_caches=update_kv_cache[0],
|
132 |
+
v_caches=update_kv_cache[1],
|
133 |
+
metadata={"model_version": "v0.1"}
|
134 |
+
):
|
135 |
+
logger.info(">>> 预计算 system prompt kvcache 保存到 ./kvcache 目录, 下次启动可直接加载缓存 <<<")
|
136 |
+
else:
|
137 |
+
logger.error(">>> kvcache 缓存保存失败, 程序退出! <<<")
|
138 |
+
exit()
|
139 |
+
else:
|
140 |
+
update_kv_cache, prompt, plen, meta = cache_manager.load_kvcache("./kvcache")
|
141 |
+
builder.update_kvcache(update_kv_cache)
|
142 |
+
|
143 |
+
logger.debug(">>> 创建 LlamaChatSession >>>")
|
144 |
+
|
145 |
+
session = LlamaChatSession(
|
146 |
+
builder_instance=builder
|
147 |
+
)
|
148 |
+
session.chat_loop(live_print=False)
|
python/infer.py
ADDED
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# import llm_utils
|
2 |
+
import dataclasses
|
3 |
+
import json
|
4 |
+
from transformers import AutoTokenizer, AutoConfig
|
5 |
+
import torch
|
6 |
+
from torchvision.transforms.functional import InterpolationMode
|
7 |
+
import numpy as np
|
8 |
+
from ml_dtypes import bfloat16
|
9 |
+
from axengine import InferenceSession
|
10 |
+
from tqdm import tqdm
|
11 |
+
import torchvision.transforms as T
|
12 |
+
from PIL import Image
|
13 |
+
import argparse
|
14 |
+
|
15 |
+
|
16 |
+
def post_process(data, topk=1, topp=0.9, temperature=0.6):
|
17 |
+
def top_p(l: np.ndarray, p: float) -> np.ndarray:
|
18 |
+
index = np.argsort(l)
|
19 |
+
res = l.copy()
|
20 |
+
sum_p = 0
|
21 |
+
for i in index[::-1]:
|
22 |
+
if sum_p >= p:
|
23 |
+
res[i] = 0
|
24 |
+
sum_p += res[i]
|
25 |
+
return res / sum_p
|
26 |
+
|
27 |
+
def softmax(l: np.ndarray) -> np.ndarray:
|
28 |
+
l_max = l - l.max()
|
29 |
+
l_exp = np.exp(l_max)
|
30 |
+
res = l_exp / np.sum(l_exp)
|
31 |
+
return res.astype(np.float64)
|
32 |
+
|
33 |
+
r = data.astype(np.float32)
|
34 |
+
r = r.flatten()
|
35 |
+
# topk
|
36 |
+
candidate_index = np.argpartition(r, -topk)[-topk:]
|
37 |
+
candidate_value = r[candidate_index]
|
38 |
+
# temperature
|
39 |
+
candidate_value /= temperature
|
40 |
+
# softmax
|
41 |
+
candidate_soft = softmax(candidate_value)
|
42 |
+
# topp
|
43 |
+
candidate_soft = top_p(candidate_soft, topp)
|
44 |
+
candidate_soft = candidate_soft.astype(np.float64) / candidate_soft.sum()
|
45 |
+
pos = np.random.multinomial(1, candidate_soft).argmax()
|
46 |
+
next_token = candidate_index[pos]
|
47 |
+
return next_token, candidate_index, candidate_soft
|
48 |
+
|
49 |
+
|
50 |
+
def generate_slice_indices(token_len, prefill=128, expand=512):
|
51 |
+
remaining = max(0, token_len - prefill)
|
52 |
+
extra_blocks = (remaining + expand - 1) // expand
|
53 |
+
return list(range(extra_blocks + 1))
|
54 |
+
|
55 |
+
|
56 |
+
if __name__ == "__main__":
|
57 |
+
|
58 |
+
prompt = None
|
59 |
+
parser = argparse.ArgumentParser(description="Model configuration parameters")
|
60 |
+
parser.add_argument("--hf_model", type=str, default="../qwen2.5_tokenizer",
|
61 |
+
help="Path to HuggingFace model")
|
62 |
+
parser.add_argument("--axmodel_path", type=str, default="../qwen2.5-1.5b-ctx-ax650",
|
63 |
+
help="Path to save compiled axmodel of llama model")
|
64 |
+
parser.add_argument("-q", "--question", type=str, default="Please calculate the derivative of the function y=2x^2.",
|
65 |
+
help="Your question that you want to ask the model.")
|
66 |
+
args = parser.parse_args()
|
67 |
+
|
68 |
+
device = "cpu"
|
69 |
+
hf_model_path = args.hf_model
|
70 |
+
axmodel_path = args.axmodel_path
|
71 |
+
|
72 |
+
cfg = AutoConfig.from_pretrained(hf_model_path, trust_remote_code=True)
|
73 |
+
tokenizer = AutoTokenizer.from_pretrained(hf_model_path, trust_remote_code=True, use_fast=False)
|
74 |
+
|
75 |
+
prompt = args.question
|
76 |
+
|
77 |
+
print("注意: 这里预先设定了长 prompt 测试. ")
|
78 |
+
# input_ids: 438 > 128
|
79 |
+
prompt = '''你能将英文翻译成中文吗? 比如这句话:
|
80 |
+
Once when I was six years old I saw a magnificent picture in a book, called True Stories from Nature, about the primeval forest. It was a picture of a boa constrictor in the act of swallowing an animal. Here is a copy of the drawing.
|
81 |
+
In the book it said: "Boa constrictors swallow their prey whole, without chewing it. After that they are not able to move, and they sleep through the six months that they need for digestion."
|
82 |
+
I pondered deeply, then, over the adventures of the jungle. And after some work with a colored pencil I succeeded in making my first drawing. My Drawing Number One. It looked like this:
|
83 |
+
I showed my masterpiece to the grown-ups, and asked them whether the drawing frightened them.
|
84 |
+
But they answered: "Frighten? Why should any one be frightened by a hat?"
|
85 |
+
My drawing was not a picture of a hat. It was a picture of a boa constrictor digesting an elephant. But since the grown-ups were not able to understand it, I made another drawing: I drew the inside of the boa constrictor, so that the grown-ups could see it clearly. They always need to have things explained. My Drawing Number Two looked like this:
|
86 |
+
The grown-ups‘ response, this time, was to advise me to lay aside my drawings of boa constrictors, whether from the inside or the outside, and devote myself instead to geography, history, arithmetic and grammar. That is why, at the age of six, I gave up what might have been a magnificent career as a painter. I had been disheartened by the failure of my Drawing Number One and my Drawing Number Two. Grown-ups never understand anything by themselves, and it is tiresome for children to be always and forever explaining things to them.
|
87 |
+
So then I chose another profession, and learned to pilot airplanes.
|
88 |
+
'''
|
89 |
+
|
90 |
+
# prompt = "介绍一下你自己"
|
91 |
+
# prompt = "今天是几号,天气怎么样"
|
92 |
+
prompt = "你知道 `床前明月光,疑是地上霜`是谁写的吗?"
|
93 |
+
|
94 |
+
messages = [
|
95 |
+
{"role": "system", "content": "你的名字叫小智(allen), 你是一个人畜无害的 AI 助手. 深圳市今天(4月1日)阴天, 愚人节, 气温在 14°C 至 19°C 之间, 微风."},
|
96 |
+
{"role": "user", "content": prompt}
|
97 |
+
]
|
98 |
+
text = tokenizer.apply_chat_template(
|
99 |
+
messages,
|
100 |
+
tokenize=False,
|
101 |
+
add_generation_prompt=True,
|
102 |
+
)
|
103 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(device)
|
104 |
+
token_ids = model_inputs.input_ids[0].cpu().numpy().tolist()
|
105 |
+
|
106 |
+
embeds = np.load(f"{axmodel_path}/model.embed_tokens.weight.npy")
|
107 |
+
prefill_data = np.take(embeds, token_ids, axis=0)
|
108 |
+
token_len = len(token_ids)
|
109 |
+
import pdb; pdb.set_trace()
|
110 |
+
|
111 |
+
##################
|
112 |
+
lastN = 2559
|
113 |
+
|
114 |
+
kv_dim = cfg.hidden_size // cfg.num_attention_heads * cfg.num_key_value_heads
|
115 |
+
k_caches = [
|
116 |
+
np.zeros((1, lastN, kv_dim), dtype=bfloat16)
|
117 |
+
for _ in range(cfg.num_hidden_layers)
|
118 |
+
]
|
119 |
+
v_caches = [
|
120 |
+
np.zeros((1, lastN, kv_dim), dtype=bfloat16)
|
121 |
+
for _ in range(cfg.num_hidden_layers)
|
122 |
+
]
|
123 |
+
|
124 |
+
prefill_decoder_sessins = []
|
125 |
+
|
126 |
+
for i in tqdm(range(cfg.num_hidden_layers), desc="Init InferenceSession"):
|
127 |
+
session = InferenceSession(
|
128 |
+
f"{axmodel_path}/qwen2_p128_l{i}_together.axmodel"
|
129 |
+
)
|
130 |
+
prefill_decoder_sessins.append(session)
|
131 |
+
|
132 |
+
post_process_session = InferenceSession(
|
133 |
+
f"{axmodel_path}/qwen2_post.axmodel"
|
134 |
+
)
|
135 |
+
print("model load done!")
|
136 |
+
print("prefill token_len: ", token_len)
|
137 |
+
|
138 |
+
"""
|
139 |
+
Model input shape:
|
140 |
+
- kv_cache: g1:[1, 1, hidden_size] -> g2:[1, kv_mask_expand_lens, kv_dim] -> g3:[1, kv_mask_expand_lens * 2, kv_dim]
|
141 |
+
- mask: g1:[1, input_prefill_len, input_prefill_len] -> g2:[1, input_prefill_len, input_prefill_len+kv_mask_expand_lens] -> g3:[1, input_prefill_len, input_prefill_len+kv_mask_expand_lens*2]
|
142 |
+
- indices: g1:[1, input_prefill_len] -> g2:[1, input_prefill_len] -> g3:[1, input_prefill_len]
|
143 |
+
- input: g1:[1, input_prefill_len, hidden_size] -> g2:[1, input_prefill_len, hidden_size] -> g3:[1, input_prefill_len, hidden_size]
|
144 |
+
"""
|
145 |
+
|
146 |
+
input_prefill_len = 128
|
147 |
+
kv_mask_expand_len = 128 # 512
|
148 |
+
|
149 |
+
"""
|
150 |
+
Model output shape:
|
151 |
+
- kv_cache: g1:[1, input_prefill_len, kv_dim] -> g2:[1, input_prefill_len, kv_dim] -> g3:[1, input_prefill_len, kv_dim]
|
152 |
+
- output: g1:[1, input_prefill_len, hidden_size] -> g2:[1, input_prefill_len, hidden_size] -> g3:[1, input_prefill_len, hidden_size]
|
153 |
+
"""
|
154 |
+
slice_indexs = generate_slice_indices(token_len, input_prefill_len, input_prefill_len)
|
155 |
+
print(f"slice_indexs is {slice_indexs}")
|
156 |
+
|
157 |
+
"""
|
158 |
+
prefill
|
159 |
+
"""
|
160 |
+
if input_prefill_len > 0:
|
161 |
+
for slice_index in slice_indexs:
|
162 |
+
if slice_index == 0:
|
163 |
+
current_slice_len = input_prefill_len
|
164 |
+
else:
|
165 |
+
current_slice_len = kv_mask_expand_len
|
166 |
+
|
167 |
+
indices = np.array(
|
168 |
+
list(
|
169 |
+
range(
|
170 |
+
slice_index * input_prefill_len,
|
171 |
+
(slice_index + 1) * input_prefill_len,
|
172 |
+
)
|
173 |
+
),
|
174 |
+
np.uint32,
|
175 |
+
).reshape((1, input_prefill_len))
|
176 |
+
|
177 |
+
mask = (
|
178 |
+
np.zeros((1, input_prefill_len, current_slice_len * slice_index + input_prefill_len))
|
179 |
+
- 65536
|
180 |
+
)
|
181 |
+
data = np.zeros((1, input_prefill_len, cfg.hidden_size)).astype(bfloat16)
|
182 |
+
for i, t in enumerate(
|
183 |
+
range(
|
184 |
+
slice_index * input_prefill_len,
|
185 |
+
(slice_index + 1) * input_prefill_len,
|
186 |
+
)
|
187 |
+
):
|
188 |
+
if t < len(token_ids):
|
189 |
+
mask[:, i, : slice_index * input_prefill_len + i + 1] = 0
|
190 |
+
data[:, i : i + 1, :] = (
|
191 |
+
prefill_data[t]
|
192 |
+
.reshape((1, 1, cfg.hidden_size))
|
193 |
+
.astype(bfloat16)
|
194 |
+
)
|
195 |
+
|
196 |
+
if slice_index == slice_indexs[-1]:
|
197 |
+
curlen_procd = token_len - slice_index * input_prefill_len # curlen_procd 是当前处理数据的长度
|
198 |
+
else:
|
199 |
+
curlen_procd = input_prefill_len
|
200 |
+
|
201 |
+
mask = mask.astype(bfloat16)
|
202 |
+
for i in range(cfg.num_hidden_layers):
|
203 |
+
input_feed = {
|
204 |
+
"K_cache": (
|
205 |
+
k_caches[i][:, 0: current_slice_len * slice_index, :]
|
206 |
+
if slice_index
|
207 |
+
else np.zeros((1, 1, cfg.hidden_size), dtype=bfloat16)
|
208 |
+
),
|
209 |
+
"V_cache": (
|
210 |
+
v_caches[i][:, 0: current_slice_len * slice_index, :]
|
211 |
+
if slice_index
|
212 |
+
else np.zeros((1, 1, cfg.hidden_size), dtype=bfloat16)
|
213 |
+
),
|
214 |
+
"indices": indices,
|
215 |
+
"input": data,
|
216 |
+
"mask": mask,
|
217 |
+
}
|
218 |
+
outputs = prefill_decoder_sessins[i].run(None, input_feed, shape_group=slice_index + 1)
|
219 |
+
|
220 |
+
k_caches[i][
|
221 |
+
:,
|
222 |
+
slice_index
|
223 |
+
* input_prefill_len : slice_index
|
224 |
+
* input_prefill_len + curlen_procd, # current_slice_len
|
225 |
+
:,
|
226 |
+
] = outputs[0][:, :curlen_procd, :]
|
227 |
+
|
228 |
+
v_caches[i][
|
229 |
+
:,
|
230 |
+
slice_index
|
231 |
+
* input_prefill_len : slice_index
|
232 |
+
* input_prefill_len + curlen_procd, # current_slice_len
|
233 |
+
:,
|
234 |
+
] = outputs[1][:, :curlen_procd, :]
|
235 |
+
|
236 |
+
data = outputs[2]
|
237 |
+
|
238 |
+
print("slice prefill done", slice_index)
|
239 |
+
|
240 |
+
post_out = post_process_session.run(
|
241 |
+
None,
|
242 |
+
{
|
243 |
+
"input": data[
|
244 |
+
:, token_len - (len(slice_indexs) - 1) * input_prefill_len - 1, None, :
|
245 |
+
]
|
246 |
+
}
|
247 |
+
)[0]
|
248 |
+
next_token, posssible_tokens, possible_soft = post_process(post_out)
|
249 |
+
posibles = [tokenizer.decode([t]) for t in posssible_tokens]
|
250 |
+
posible_soft = [str((t, s)) for t, s in zip(posibles, possible_soft)]
|
251 |
+
token_ids.append(next_token)
|
252 |
+
|
253 |
+
print("answer >>", tokenizer.decode(token_ids[token_len], skip_special_tokens=True), end='', flush=True)
|
254 |
+
# print("answer >>", end='', flush=True)
|
255 |
+
|
256 |
+
# set to decoder
|
257 |
+
kv_cache_len = lastN
|
258 |
+
mask = np.zeros((1, 1, kv_cache_len + 1), dtype=np.float32).astype(bfloat16)
|
259 |
+
mask[:, :, :kv_cache_len] -= 65536
|
260 |
+
if input_prefill_len > 0:
|
261 |
+
mask[:, :, :token_len] = 0
|
262 |
+
|
263 |
+
# for start_indice in tqdm(range(kv_cache_len), desc="Decode"):
|
264 |
+
for start_indice in range(kv_cache_len):
|
265 |
+
if input_prefill_len > 0 and start_indice < token_len:
|
266 |
+
continue
|
267 |
+
|
268 |
+
next_token = token_ids[start_indice]
|
269 |
+
indices = np.array([start_indice], np.uint32).reshape((1, 1))
|
270 |
+
data = embeds[next_token, :].reshape((1, 1, cfg.hidden_size)).astype(bfloat16)
|
271 |
+
for i in range(cfg.num_hidden_layers):
|
272 |
+
input_feed = {
|
273 |
+
"K_cache": k_caches[i],
|
274 |
+
"V_cache": v_caches[i],
|
275 |
+
"indices": indices,
|
276 |
+
"input": data,
|
277 |
+
"mask": mask,
|
278 |
+
}
|
279 |
+
outputs = prefill_decoder_sessins[i].run(None, input_feed, shape_group=0)
|
280 |
+
k_caches[i][:, start_indice, :] = outputs[0][:, :, :]
|
281 |
+
v_caches[i][:, start_indice, :] = outputs[1][:, :, :]
|
282 |
+
data = outputs[2]
|
283 |
+
mask[..., start_indice] = 0
|
284 |
+
if start_indice < token_len - 1:
|
285 |
+
pass
|
286 |
+
else:
|
287 |
+
post_out = post_process_session.run(None, {"input": data})[0]
|
288 |
+
next_token, posssible_tokens, possible_soft = post_process(post_out)
|
289 |
+
token_ids.append(next_token)
|
290 |
+
if next_token == tokenizer.eos_token_id and next_token > token_len:
|
291 |
+
break
|
292 |
+
|
293 |
+
print(tokenizer.decode(next_token, skip_special_tokens=True), end='', flush=True)
|
python/infer_torch.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
+
from loguru import logger
|
3 |
+
|
4 |
+
|
5 |
+
model_name = "./Qwen2.5-1.5B-Instruct-GPTQ-Int8"
|
6 |
+
model = AutoModelForCausalLM.from_pretrained(
|
7 |
+
model_name,
|
8 |
+
torch_dtype="auto",
|
9 |
+
device_map="auto"
|
10 |
+
)
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
12 |
+
prompt = "请你对 large language model 做一个简短的介绍."
|
13 |
+
messages = [
|
14 |
+
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
|
15 |
+
{"role": "user", "content": prompt}
|
16 |
+
]
|
17 |
+
text = tokenizer.apply_chat_template(
|
18 |
+
messages,
|
19 |
+
tokenize=False,
|
20 |
+
add_generation_prompt=True
|
21 |
+
)
|
22 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
23 |
+
|
24 |
+
import pdb; pdb.set_trace()
|
25 |
+
generated_ids = model.generate(
|
26 |
+
**model_inputs,
|
27 |
+
max_new_tokens=512
|
28 |
+
)
|
29 |
+
generated_ids = [
|
30 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
31 |
+
]
|
32 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
33 |
+
logger.debug(response)
|
python/utils/infer_func.py
ADDED
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
from typing import List, Tuple, Optional, Dict
|
4 |
+
from pathlib import Path
|
5 |
+
from tqdm import tqdm
|
6 |
+
from axengine import InferenceSession
|
7 |
+
from ml_dtypes import bfloat16
|
8 |
+
from transformers import AutoTokenizer, AutoConfig
|
9 |
+
import json
|
10 |
+
from loguru import logger
|
11 |
+
|
12 |
+
|
13 |
+
class KVCacheTools:
|
14 |
+
"""
|
15 |
+
k, v cache 的本地保存和加载
|
16 |
+
"""
|
17 |
+
def __init__(self, axmodel_num: int, dtype=np.float32):
|
18 |
+
self.axmodel_num = axmodel_num
|
19 |
+
self.dtype = dtype
|
20 |
+
|
21 |
+
def save_kvcache(
|
22 |
+
self,
|
23 |
+
target_dir: str,
|
24 |
+
system_prompt: str,
|
25 |
+
precompute_len: int,
|
26 |
+
k_caches: List[np.ndarray],
|
27 |
+
v_caches: List[np.ndarray],
|
28 |
+
metadata: Optional[Dict] = None
|
29 |
+
) -> bool:
|
30 |
+
try:
|
31 |
+
target_path = Path(target_dir)
|
32 |
+
target_path.mkdir(parents=True, exist_ok=True)
|
33 |
+
|
34 |
+
for i, (k, v) in enumerate(zip(k_caches, v_caches)):
|
35 |
+
k.astype(self.dtype).tofile(target_path / f"k_cache_{i}.bin")
|
36 |
+
v.astype(self.dtype).tofile(target_path / f"v_cache_{i}.bin")
|
37 |
+
|
38 |
+
config = {
|
39 |
+
"precompute_len": precompute_len,
|
40 |
+
"system_prompt": system_prompt,
|
41 |
+
"axmodel_num": self.axmodel_num,
|
42 |
+
"dtype": str(self.dtype),
|
43 |
+
"metadata": metadata or {},
|
44 |
+
}
|
45 |
+
with open(target_path / "config.json", "w", encoding="utf8") as f:
|
46 |
+
json.dump(config, f, indent=2, ensure_ascii=False)
|
47 |
+
|
48 |
+
return True
|
49 |
+
except Exception as e:
|
50 |
+
print(f"Save failed: {str(e)}")
|
51 |
+
return False
|
52 |
+
|
53 |
+
def load_kvcache(
|
54 |
+
self,
|
55 |
+
cache_dir: str
|
56 |
+
) -> Tuple[
|
57 |
+
List[np.ndarray],
|
58 |
+
List[np.ndarray],
|
59 |
+
str,
|
60 |
+
int,
|
61 |
+
Dict
|
62 |
+
]:
|
63 |
+
try:
|
64 |
+
cache_path = Path(cache_dir)
|
65 |
+
k_caches, v_caches = [], []
|
66 |
+
|
67 |
+
with open(cache_path / "config.json") as f:
|
68 |
+
config = json.load(f)
|
69 |
+
|
70 |
+
if config["axmodel_num"] != self.axmodel_num:
|
71 |
+
raise ValueError(
|
72 |
+
f"Model layer mismatch: "
|
73 |
+
f"Expected {self.axmodel_num}, got {config['axmodel_num']}"
|
74 |
+
)
|
75 |
+
|
76 |
+
for i in range(self.axmodel_num):
|
77 |
+
k_data = np.fromfile(cache_path / f"k_cache_{i}.bin", dtype=self.dtype).reshape(1, -1, 256)
|
78 |
+
v_data = np.fromfile(cache_path / f"v_cache_{i}.bin", dtype=self.dtype).reshape(1, -1, 256)
|
79 |
+
k_caches.append(k_data)
|
80 |
+
v_caches.append(v_data)
|
81 |
+
|
82 |
+
return (
|
83 |
+
(k_caches, v_caches),
|
84 |
+
config["system_prompt"],
|
85 |
+
config["precompute_len"],
|
86 |
+
config.get("metadata", {})
|
87 |
+
)
|
88 |
+
except Exception as e:
|
89 |
+
print(f"Load failed: {str(e)}")
|
90 |
+
exit()
|
91 |
+
|
92 |
+
|
93 |
+
class InferManager:
|
94 |
+
def __init__(self, hf_model_path: str, axmodel_path: str):
|
95 |
+
self.device = "cpu"
|
96 |
+
self.hf_model_path = hf_model_path
|
97 |
+
self.axmodel_path = axmodel_path
|
98 |
+
|
99 |
+
self.hf_config = AutoConfig.from_pretrained(self.hf_model_path, trust_remote_code=True)
|
100 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.hf_model_path, trust_remote_code=True, use_fast=False)
|
101 |
+
self.system_prompt = "你的名字叫小智(allen), 你是一个人畜无害的 AI 助手. 深圳市今天(4月1日)阴天, 愚人节, 气温在 14°C 至 19°C 之间, 微风."
|
102 |
+
self.embeds = np.load(f"{self.axmodel_path}/model.embed_tokens.weight.npy")
|
103 |
+
|
104 |
+
def build_system_prompt(self):
|
105 |
+
|
106 |
+
messages = [
|
107 |
+
{"role": "system", "content": self.system_prompt},
|
108 |
+
# {"role": "user", "content": prompt}
|
109 |
+
]
|
110 |
+
text = self.tokenizer.apply_chat_template(
|
111 |
+
messages,
|
112 |
+
tokenize=False,
|
113 |
+
add_generation_prompt=False
|
114 |
+
)
|
115 |
+
self.system_inputs = self.tokenizer([text], return_tensors="pt").to(self.device)
|
116 |
+
self.system_input_ids = self.system_inputs.input_ids[0].cpu().numpy().tolist()
|
117 |
+
self.system_input_embeds = np.take(self.embeds, self.system_input_ids, axis=0)
|
118 |
+
self.system_input_ids_len = len(self.system_input_ids)
|
119 |
+
self.model_inputs = {
|
120 |
+
"input_ids": self.system_input_ids,
|
121 |
+
"input_embeds": self.system_input_embeds,
|
122 |
+
"input_ids_len": self.system_input_ids_len
|
123 |
+
}
|
124 |
+
self.precompute_len = self.system_input_ids_len
|
125 |
+
# logger.info(f"system prompt prompt ids len: {self.system_input_ids_len}")
|
126 |
+
|
127 |
+
def encoder_prompt(self, prompt):
|
128 |
+
|
129 |
+
text = f'<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n'
|
130 |
+
model_inputs = self.tokenizer([text], return_tensors="pt").to(self.device)
|
131 |
+
input_ids = model_inputs.input_ids[0].cpu().numpy().tolist()
|
132 |
+
input_embeds = np.take(self.embeds, input_ids, axis=0)
|
133 |
+
input_ids_len = len(input_ids)
|
134 |
+
# logger.info(f"user prompt token_len: {input_ids_len}")
|
135 |
+
|
136 |
+
model_inputs = {
|
137 |
+
"message": text,
|
138 |
+
"model_inputs": model_inputs,
|
139 |
+
"input_ids": input_ids,
|
140 |
+
"input_embeds": input_embeds,
|
141 |
+
"input_ids_len": input_ids_len
|
142 |
+
}
|
143 |
+
return model_inputs
|
144 |
+
|
145 |
+
def build_kvcache(self, kv_cache_len: int = 2559):
|
146 |
+
|
147 |
+
kv_dim = self.hf_config.hidden_size // self.hf_config.num_attention_heads * self.hf_config.num_key_value_heads
|
148 |
+
self.k_caches = [
|
149 |
+
np.zeros((1, kv_cache_len, kv_dim), dtype=bfloat16)
|
150 |
+
for _ in range(self.hf_config.num_hidden_layers)
|
151 |
+
]
|
152 |
+
self.v_caches = [
|
153 |
+
np.zeros((1, kv_cache_len, kv_dim), dtype=bfloat16)
|
154 |
+
for _ in range(self.hf_config.num_hidden_layers)
|
155 |
+
]
|
156 |
+
|
157 |
+
def get_kvcache(self):
|
158 |
+
return [self.k_caches, self.v_caches]
|
159 |
+
|
160 |
+
def update_kvcache(self, update_kv_cache):
|
161 |
+
self.k_caches = update_kv_cache[0]
|
162 |
+
self.v_caches = update_kv_cache[1]
|
163 |
+
|
164 |
+
def get_tokenizer(self):
|
165 |
+
return self.tokenizer
|
166 |
+
|
167 |
+
def get_system_prompt(self):
|
168 |
+
return self.system_prompt
|
169 |
+
|
170 |
+
def set_system_prompt(self, prompt):
|
171 |
+
self.system_prompt = prompt
|
172 |
+
|
173 |
+
def build_infer_model(self, ):
|
174 |
+
self.prefill_decoder_sessins = []
|
175 |
+
|
176 |
+
for i in tqdm(range(self.hf_config.num_hidden_layers), desc="Init InferenceSession"):
|
177 |
+
session = InferenceSession(
|
178 |
+
f"{self.axmodel_path}/qwen2_p128_l{i}_together.axmodel"
|
179 |
+
)
|
180 |
+
self.prefill_decoder_sessins.append(session)
|
181 |
+
|
182 |
+
self.post_process_session = InferenceSession(
|
183 |
+
f"{self.axmodel_path}/qwen2_post.axmodel"
|
184 |
+
)
|
185 |
+
print("The models have been loaded!")
|
186 |
+
|
187 |
+
def get_infer_session(self):
|
188 |
+
return [self.prefill_decoder_sessins, self.post_process_session]
|
189 |
+
|
190 |
+
@staticmethod
|
191 |
+
def _top_p(probs: np.ndarray, p: float) -> np.ndarray:
|
192 |
+
sorted_indices = np.argsort(probs)
|
193 |
+
filtered = probs.copy()
|
194 |
+
cumulative = 0
|
195 |
+
for idx in sorted_indices[::-1]:
|
196 |
+
if cumulative >= p:
|
197 |
+
filtered[idx] = 0
|
198 |
+
cumulative += filtered[idx]
|
199 |
+
return filtered / cumulative
|
200 |
+
|
201 |
+
@staticmethod
|
202 |
+
def _softmax(logits: np.ndarray) -> np.ndarray:
|
203 |
+
logits = logits - logits.max()
|
204 |
+
exp_logits = np.exp(logits)
|
205 |
+
return (exp_logits / np.sum(exp_logits)).astype(np.float64)
|
206 |
+
|
207 |
+
def post_process(self, logits, top_k=1, top_p=0.9, temperature=0.6):
|
208 |
+
logits = logits.astype(np.float32).flatten()
|
209 |
+
candidate_indices = np.argpartition(logits, -top_k)[-top_k:]
|
210 |
+
candidate_logits = logits[candidate_indices] / temperature
|
211 |
+
candidate_probs = self._softmax(candidate_logits)
|
212 |
+
candidate_probs = self._top_p(candidate_probs, top_p)
|
213 |
+
candidate_probs = candidate_probs.astype(np.float64) / candidate_probs.sum()
|
214 |
+
chosen_idx = np.random.multinomial(1, candidate_probs).argmax()
|
215 |
+
next_token = candidate_indices[chosen_idx]
|
216 |
+
return next_token, candidate_indices, candidate_probs
|
217 |
+
|
218 |
+
def gen_slice_indices(self, token_len, prefill=128, expand=128):
|
219 |
+
remaining = max(0, token_len - prefill)
|
220 |
+
extra_blocks = (remaining + expand - 1) // expand
|
221 |
+
return list(range(extra_blocks + 1))
|
222 |
+
|
223 |
+
def prefill(
|
224 |
+
self,
|
225 |
+
model_inputs,
|
226 |
+
slice_len=128,
|
227 |
+
precompute_len=0, # system prompt prefill 的时候, 只能设置为 0
|
228 |
+
):
|
229 |
+
"""
|
230 |
+
Prefill step for chunked inference.
|
231 |
+
"""
|
232 |
+
token_ids = model_inputs["input_ids"]
|
233 |
+
token_embeds = model_inputs["input_embeds"]
|
234 |
+
token_len = model_inputs["input_ids_len"]
|
235 |
+
|
236 |
+
seq_len = len(token_ids)
|
237 |
+
slice_indices = [i for i in range(seq_len // slice_len + 1)]
|
238 |
+
print(f"slice_indices: {slice_indices}")
|
239 |
+
# total_prefill_len = (
|
240 |
+
# slice_len * slice_indices[-1]
|
241 |
+
# if slice_indices[-1] != 0
|
242 |
+
# else slice_len
|
243 |
+
# )
|
244 |
+
# slice_indices = self.gen_slice_indices(seq_len)
|
245 |
+
total_prefill_len = slice_len * (slice_indices[-1] + 1)
|
246 |
+
kv_mask_expand_len = 128
|
247 |
+
|
248 |
+
if total_prefill_len > 0:
|
249 |
+
for slice_index in slice_indices:
|
250 |
+
if slice_index == 0:
|
251 |
+
current_slice_len = slice_len
|
252 |
+
else:
|
253 |
+
current_slice_len = kv_mask_expand_len
|
254 |
+
|
255 |
+
indices = np.array(
|
256 |
+
list(
|
257 |
+
range(
|
258 |
+
precompute_len + slice_index * slice_len,
|
259 |
+
precompute_len + (slice_index + 1) * slice_len,
|
260 |
+
)
|
261 |
+
),
|
262 |
+
np.uint32,
|
263 |
+
).reshape((1, slice_len))
|
264 |
+
indices[:, min(token_len, slice_len):] = 0
|
265 |
+
|
266 |
+
mask = (
|
267 |
+
np.zeros((1, slice_len, current_slice_len * slice_index + slice_len))
|
268 |
+
- 65536
|
269 |
+
)
|
270 |
+
data = np.zeros((1, slice_len, self.hf_config.hidden_size)).astype(bfloat16)
|
271 |
+
|
272 |
+
for i, t in enumerate(
|
273 |
+
range(
|
274 |
+
slice_index * slice_len,
|
275 |
+
(slice_index + 1) * slice_len,
|
276 |
+
)
|
277 |
+
):
|
278 |
+
if t < len(token_ids):
|
279 |
+
# mask[:, i, 0: slice_index * slice_len + i + 1] = 0
|
280 |
+
data[:, i : i + 1, :] = (
|
281 |
+
token_embeds[t]
|
282 |
+
.reshape((1, 1, self.hf_config.hidden_size))
|
283 |
+
.astype(bfloat16)
|
284 |
+
)
|
285 |
+
if t < len(token_ids) + precompute_len:
|
286 |
+
mask[:, i, 0: slice_index * slice_len + i + 1] = 0
|
287 |
+
|
288 |
+
if slice_index == slice_indices[-1]:
|
289 |
+
curlen_procd = token_len - slice_index * slice_len # curlen_procd 是当前处理数据的长度
|
290 |
+
else:
|
291 |
+
curlen_procd = slice_len
|
292 |
+
|
293 |
+
mask = mask.astype(bfloat16)
|
294 |
+
for i in range(self.hf_config.num_hidden_layers):
|
295 |
+
input_feed = {
|
296 |
+
"K_cache": (
|
297 |
+
self.k_caches[i][:, 0: current_slice_len * slice_index, :]
|
298 |
+
if slice_index
|
299 |
+
else np.zeros((1, 1, self.hf_config.hidden_size), dtype=bfloat16)
|
300 |
+
),
|
301 |
+
"V_cache": (
|
302 |
+
self.v_caches[i][:, 0: current_slice_len * slice_index, :]
|
303 |
+
if slice_index
|
304 |
+
else np.zeros((1, 1, self.hf_config.hidden_size), dtype=bfloat16)
|
305 |
+
),
|
306 |
+
"indices": indices,
|
307 |
+
"input": data,
|
308 |
+
"mask": mask,
|
309 |
+
}
|
310 |
+
outputs = self.prefill_decoder_sessins[i].run(None, input_feed, shape_group=slice_index + 1)
|
311 |
+
self.k_caches[i][
|
312 |
+
:,
|
313 |
+
slice_index
|
314 |
+
* slice_len + precompute_len : slice_index
|
315 |
+
* slice_len + curlen_procd + precompute_len,
|
316 |
+
:,
|
317 |
+
] = outputs[0][:, :curlen_procd, :]
|
318 |
+
|
319 |
+
self.v_caches[i][
|
320 |
+
:,
|
321 |
+
slice_index
|
322 |
+
* slice_len + precompute_len: slice_index
|
323 |
+
* slice_len + curlen_procd + precompute_len,
|
324 |
+
:,
|
325 |
+
] = outputs[1][:, :curlen_procd, :]
|
326 |
+
|
327 |
+
data = outputs[2]
|
328 |
+
|
329 |
+
print("slice prefill done", slice_index)
|
330 |
+
else:
|
331 |
+
print("No prefill needed.")
|
332 |
+
# return "Calculated the kv cache of the system prompt."
|
333 |
+
return (self.k_caches, self.v_caches)
|
334 |
+
|
335 |
+
def decode(
|
336 |
+
self,
|
337 |
+
token_ids,
|
338 |
+
prefill_len=128,
|
339 |
+
slice_len=128
|
340 |
+
):
|
341 |
+
token_len = len(token_ids)
|
342 |
+
# set to decoder
|
343 |
+
print("answer: >> ", end='', flush=True)
|
344 |
+
kv_cache_len = 2559
|
345 |
+
mask = np.zeros((1, 1, kv_cache_len + 1), dtype=np.float32).astype(bfloat16)
|
346 |
+
mask[:, :, :kv_cache_len] -= 65536
|
347 |
+
if prefill_len > 0:
|
348 |
+
mask[:, :, :token_len + self.precompute_len] = 0
|
349 |
+
|
350 |
+
for start_indice in range(kv_cache_len):
|
351 |
+
if self.precompute_len > 0 and start_indice < self.precompute_len:
|
352 |
+
continue
|
353 |
+
next_token = token_ids[start_indice - self.precompute_len]
|
354 |
+
indices = np.array([start_indice], np.uint32).reshape((1, 1))
|
355 |
+
data = self.embeds[next_token, :].reshape((1, 1, self.hf_config.hidden_size)).astype(bfloat16)
|
356 |
+
for i in range(self.hf_config.num_hidden_layers):
|
357 |
+
input_feed = {
|
358 |
+
"K_cache": self.k_caches[i],
|
359 |
+
"V_cache": self.v_caches[i],
|
360 |
+
"indices": indices,
|
361 |
+
"input": data,
|
362 |
+
"mask": mask,
|
363 |
+
}
|
364 |
+
outputs = self.prefill_decoder_sessins[i].run(None, input_feed, shape_group=0)
|
365 |
+
self.k_caches[i][:, start_indice, :] = outputs[0][:, :, :]
|
366 |
+
self.v_caches[i][:, start_indice, :] = outputs[1][:, :, :]
|
367 |
+
data = outputs[2]
|
368 |
+
mask[..., start_indice] = 0
|
369 |
+
if start_indice < token_len + self.precompute_len - 1:
|
370 |
+
pass
|
371 |
+
else:
|
372 |
+
post_out = self.post_process_session.run(None, {"input": data})[0]
|
373 |
+
next_token, posssible_tokens, possible_soft = self.post_process(post_out)
|
374 |
+
token_ids.append(next_token)
|
375 |
+
print(self.tokenizer.decode(next_token, skip_special_tokens=True), end='', flush=True)
|
376 |
+
|
377 |
+
if next_token == self.tokenizer.eos_token_id and start_indice > token_len + self.precompute_len:
|
378 |
+
# print("\n>> HINT: The next_token encountered EOS token, generation completed.")
|
379 |
+
break
|
380 |
+
print("\n")
|
381 |
+
self.precompute_len = len(token_ids) + self.precompute_len - 1
|
382 |
+
return self.tokenizer.decode(token_ids[self.precompute_len - 1:], skip_special_tokens=True)
|
383 |
+
|