Robotics
Transformers
Safetensors
minicpm_robottrack
feature-extraction
vision-language-action
embodied-ai
minicpm
visual-tracking
custom_code
Instructions to use openbmb/MiniCPM-RobotTrack with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use openbmb/MiniCPM-RobotTrack with Transformers:
# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("openbmb/MiniCPM-RobotTrack", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Commit ·
f9b94bf
0
Parent(s):
Upload MiniCPM-RobotTrack model weights and assets
Browse files- .gitattributes +5 -0
- LICENSE +202 -0
- LICENSE_MINICPM +202 -0
- LICENSE_MIT +22 -0
- README.md +227 -0
- THIRD_PARTY_NOTICES.md +16 -0
- added_tokens.json +10 -0
- assets/discord.jpg +3 -0
- assets/discord.png +3 -0
- assets/github.png +3 -0
- assets/hf.png +3 -0
- assets/metric.png +3 -0
- assets/track1.gif +3 -0
- assets/track2.gif +3 -0
- assets/track3.gif +3 -0
- assets/x.jpg +3 -0
- assets/x.png +3 -0
- config.json +118 -0
- configuration_minicpm.py +203 -0
- configuration_robottrack.py +70 -0
- model.safetensors +3 -0
- modeling_minicpm.py +1514 -0
- modeling_robottrack.py +321 -0
- requirements.txt +5 -0
- special_tokens_map.json +40 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +117 -0
.gitattributes
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 [yyyy] [name of copyright owner]
|
| 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.
|
LICENSE_MINICPM
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 [yyyy] [name of copyright owner]
|
| 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.
|
LICENSE_MIT
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 MiniCPM-RobotTrack contributors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
README.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
library_name: transformers
|
| 4 |
+
pipeline_tag: robotics
|
| 5 |
+
tags:
|
| 6 |
+
- vision-language-action
|
| 7 |
+
- robotics
|
| 8 |
+
- embodied-ai
|
| 9 |
+
- minicpm
|
| 10 |
+
- visual-tracking
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
<h1 align="center">
|
| 14 |
+
MiniCPM-RobotTrack
|
| 15 |
+
</h1>
|
| 16 |
+
|
| 17 |
+
<p align="center">
|
| 18 |
+
<strong>A Compact Vision-Language-Action Policy for Embodied target Tracking</strong>
|
| 19 |
+
</p>
|
| 20 |
+
|
| 21 |
+
<p align="center">
|
| 22 |
+
<span style="display: inline-flex; align-items: center; margin-right: 2px;">
|
| 23 |
+
<img src="assets/github.png" alt="github" width="15" height="15" style="margin-right: 4px;">
|
| 24 |
+
<a href="https://github.com/OpenBMB/MiniCPM-RobotTrack" target="_blank"> Github</a> |
|
| 25 |
+
</span>
|
| 26 |
+
<span style="display: inline-flex; align-items: center; margin-right: 2px;">
|
| 27 |
+
<img src="assets/x.jpg" alt="X" width="15" height="15" style="margin-right: 4px;">
|
| 28 |
+
<a href="assets/x.png" target="_blank"> X</a> |
|
| 29 |
+
</span>
|
| 30 |
+
<span style="display: inline-flex; align-items: center; margin-right: 2px;">
|
| 31 |
+
<img src="assets/discord.png" alt="Discord" width="15" height="15" style="margin-right: 4px;">
|
| 32 |
+
<a href="assets/discord.jpg" target="_blank"> Discord</a> |
|
| 33 |
+
</span>
|
| 34 |
+
</p>
|
| 35 |
+
|
| 36 |
+
<strong>MiniCPM-RobotTrack</strong> is a compact vision-language-action model built on MiniCPM4-0.5B for target tracking with the following highlights:
|
| 37 |
+
<ul>
|
| 38 |
+
<li><b>Language-conditioned target tracking:</b> The model combines natural-language instructions with fused DINOv3 and SigLIP visual features, then directly predicts eight future <code>[x, y, yaw]</code> waypoints for embodied person following.</li>
|
| 39 |
+
<li><b>Quality-driven Self-evolving Data:</b> Automated checks and manual review remove abnormal trajectories, incorrect actions, and invalid interactions. DAgger-style model-environment interaction continually adds difficult samples involving target crossings, rapid turns, short occlusions, and multi-person intersections.</li>
|
| 40 |
+
<li><b>Efficient On-device Inference:</b> Joint optimization of visual capture, input encoding, model inference, action generation, command transmission, and execution delivers a stable <b>5+ FPS</b> with approximately <b>180 ms</b> end-to-end latency on the Unitree Go2's native onboard compute.</li>
|
| 41 |
+
</ul>
|
| 42 |
+
|
| 43 |
+
<table align="center">
|
| 44 |
+
<tr>
|
| 45 |
+
<td align="center" width="33%">
|
| 46 |
+
<img src="assets/track1.gif" width="100%" alt="Outdoor obstacle-aware person-tracking demo" />
|
| 47 |
+
</td>
|
| 48 |
+
<td align="center" width="33%">
|
| 49 |
+
<img src="assets/track2.gif" width="100%" alt="Elevator person-tracking demo" />
|
| 50 |
+
</td>
|
| 51 |
+
<td align="center" width="33%">
|
| 52 |
+
<img src="assets/track3.gif" width="100%" alt="Underground parking person-tracking demo" />
|
| 53 |
+
</td>
|
| 54 |
+
</tr>
|
| 55 |
+
<tr>
|
| 56 |
+
<td align="center"><b>Outdoor Obstacle-aware Tracking</b></td>
|
| 57 |
+
<td align="center"><b>Elevator Tracking</b></td>
|
| 58 |
+
<td align="center"><b>Underground Parking Tracking</b></td>
|
| 59 |
+
</tr>
|
| 60 |
+
</table>
|
| 61 |
+
|
| 62 |
+
## Benchmark Results
|
| 63 |
+
<p align="center">
|
| 64 |
+
<img src="assets/metric.png" width="700" alt="MiniCPM-RobotTrack benchmark results" />
|
| 65 |
+
</p>
|
| 66 |
+
|
| 67 |
+
## Inference Example
|
| 68 |
+
|
| 69 |
+
Please ensure `transformers>=4.56,<5`.
|
| 70 |
+
|
| 71 |
+
<pre><code class="language-python">from __future__ import annotations
|
| 72 |
+
|
| 73 |
+
from pathlib import Path
|
| 74 |
+
|
| 75 |
+
import torch
|
| 76 |
+
from transformers import AutoModel, AutoTokenizer
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
VISION_FEATURE_DIM = 1536
|
| 80 |
+
HISTORY_FRAMES = 31
|
| 81 |
+
COARSE_TOKENS_PER_FRAME = 4
|
| 82 |
+
FINE_TOKENS_CURRENT_FRAME = 64
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class MiniCPMRobotTrackInference:
|
| 86 |
+
"""Tokenizer and model wrapper for MiniCPM-RobotTrack inference."""
|
| 87 |
+
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
checkpoint_path: str | Path = "openbmb/MiniCPM-RobotTrack",
|
| 91 |
+
device: str | torch.device | None = None,
|
| 92 |
+
):
|
| 93 |
+
if device is None:
|
| 94 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 95 |
+
self.device = torch.device(device)
|
| 96 |
+
checkpoint = str(checkpoint_path)
|
| 97 |
+
|
| 98 |
+
self.tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
| 99 |
+
if self.tokenizer.pad_token_id is None:
|
| 100 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 101 |
+
|
| 102 |
+
self.model = AutoModel.from_pretrained(
|
| 103 |
+
checkpoint,
|
| 104 |
+
trust_remote_code=True,
|
| 105 |
+
)
|
| 106 |
+
self.model.to(self.device).eval()
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def _prepare_visual_tokens(
|
| 110 |
+
tokens: torch.Tensor,
|
| 111 |
+
time_indices: torch.Tensor,
|
| 112 |
+
name: str,
|
| 113 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 114 |
+
tokens = torch.as_tensor(tokens, dtype=torch.float32)
|
| 115 |
+
time_indices = torch.as_tensor(time_indices, dtype=torch.long)
|
| 116 |
+
|
| 117 |
+
if tokens.ndim == 2:
|
| 118 |
+
tokens = tokens.unsqueeze(0)
|
| 119 |
+
if time_indices.ndim == 1:
|
| 120 |
+
time_indices = time_indices.unsqueeze(0)
|
| 121 |
+
if tokens.ndim != 3 or tokens.shape[-1] != VISION_FEATURE_DIM:
|
| 122 |
+
raise ValueError(
|
| 123 |
+
f"{name}_tokens must have shape [B, N, {VISION_FEATURE_DIM}]"
|
| 124 |
+
)
|
| 125 |
+
if time_indices.shape != tokens.shape[:2]:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
f"{name}_time_indices must match the first two dimensions of "
|
| 128 |
+
f"{name}_tokens"
|
| 129 |
+
)
|
| 130 |
+
return tokens, time_indices
|
| 131 |
+
|
| 132 |
+
@torch.inference_mode()
|
| 133 |
+
def predict(
|
| 134 |
+
self,
|
| 135 |
+
instruction: str,
|
| 136 |
+
coarse_tokens: torch.Tensor,
|
| 137 |
+
coarse_time_indices: torch.Tensor,
|
| 138 |
+
fine_tokens: torch.Tensor,
|
| 139 |
+
fine_time_indices: torch.Tensor,
|
| 140 |
+
) -> torch.Tensor:
|
| 141 |
+
"""Return eight ``[x, y, yaw]`` waypoints for each batch item."""
|
| 142 |
+
coarse_tokens, coarse_time_indices = self._prepare_visual_tokens(
|
| 143 |
+
coarse_tokens,
|
| 144 |
+
coarse_time_indices,
|
| 145 |
+
"coarse",
|
| 146 |
+
)
|
| 147 |
+
fine_tokens, fine_time_indices = self._prepare_visual_tokens(
|
| 148 |
+
fine_tokens,
|
| 149 |
+
fine_time_indices,
|
| 150 |
+
"fine",
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
batch_size = coarse_tokens.shape[0]
|
| 154 |
+
if fine_tokens.shape[0] != batch_size:
|
| 155 |
+
raise ValueError("coarse and fine feature batch sizes must match")
|
| 156 |
+
|
| 157 |
+
text = self.tokenizer(
|
| 158 |
+
[instruction] * batch_size,
|
| 159 |
+
return_tensors="pt",
|
| 160 |
+
padding=True,
|
| 161 |
+
truncation=True,
|
| 162 |
+
max_length=self.model.config.max_text_tokens,
|
| 163 |
+
)
|
| 164 |
+
outputs = self.model(
|
| 165 |
+
input_ids=text.input_ids.to(self.device),
|
| 166 |
+
attention_mask=text.attention_mask.to(self.device),
|
| 167 |
+
coarse_tokens=coarse_tokens.to(self.device),
|
| 168 |
+
coarse_time_indices=coarse_time_indices.to(self.device),
|
| 169 |
+
fine_tokens=fine_tokens.to(self.device),
|
| 170 |
+
fine_time_indices=fine_time_indices.to(self.device),
|
| 171 |
+
)
|
| 172 |
+
return outputs.trajectories.float().cpu()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
infer_runner = MiniCPMRobotTrackInference()
|
| 177 |
+
|
| 178 |
+
# Replace these placeholders with fused DINOv3 + SigLIP features produced
|
| 179 |
+
# by the project preprocessing pipeline.
|
| 180 |
+
coarse_tokens = torch.zeros(
|
| 181 |
+
HISTORY_FRAMES * COARSE_TOKENS_PER_FRAME,
|
| 182 |
+
VISION_FEATURE_DIM,
|
| 183 |
+
)
|
| 184 |
+
coarse_time_indices = torch.arange(HISTORY_FRAMES).repeat_interleave(
|
| 185 |
+
COARSE_TOKENS_PER_FRAME
|
| 186 |
+
)
|
| 187 |
+
fine_tokens = torch.zeros(
|
| 188 |
+
FINE_TOKENS_CURRENT_FRAME,
|
| 189 |
+
VISION_FEATURE_DIM,
|
| 190 |
+
)
|
| 191 |
+
fine_time_indices = torch.full(
|
| 192 |
+
(FINE_TOKENS_CURRENT_FRAME,),
|
| 193 |
+
HISTORY_FRAMES,
|
| 194 |
+
dtype=torch.long,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
trajectory = infer_runner.predict(
|
| 198 |
+
instruction="Follow the person in the red shirt.",
|
| 199 |
+
coarse_tokens=coarse_tokens,
|
| 200 |
+
coarse_time_indices=coarse_time_indices,
|
| 201 |
+
fine_tokens=fine_tokens,
|
| 202 |
+
fine_time_indices=fine_time_indices,
|
| 203 |
+
)
|
| 204 |
+
print(trajectory) # [1, 8, 3]
|
| 205 |
+
|
| 206 |
+
</code></pre>
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
## Acknowledgement
|
| 211 |
+
|
| 212 |
+
<p>
|
| 213 |
+
This project builds on and references
|
| 214 |
+
<a href="https://github.com/OpenBMB/MiniCPM">MiniCPM</a>,
|
| 215 |
+
<a href="https://github.com/facebookresearch/dinov3">DINOv3</a>,
|
| 216 |
+
<a href="https://huggingface.co/google/siglip-so400m-patch14-384">SigLIP</a>,
|
| 217 |
+
<a href="https://github.com/facebookresearch/habitat-lab">Habitat-Lab</a>,
|
| 218 |
+
<a href="https://github.com/facebookresearch/habitat-sim">Habitat-Sim</a>,
|
| 219 |
+
EVT-Bench,
|
| 220 |
+
and
|
| 221 |
+
<a href="https://github.com/wsakobe/TrackVLA">TrackVLA</a>.
|
| 222 |
+
We thank the authors for their open-source contributions.
|
| 223 |
+
</p>
|
| 224 |
+
|
| 225 |
+
## License
|
| 226 |
+
|
| 227 |
+
Model weights and code are open-sourced under the [Apache-2.0](./LICENSE) license.
|
THIRD_PARTY_NOTICES.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-party notices
|
| 2 |
+
|
| 3 |
+
MiniCPM-RobotTrack integrates with the following projects. Their code, model
|
| 4 |
+
weights, datasets, and assets remain subject to their own licenses.
|
| 5 |
+
|
| 6 |
+
- MiniCPM: compact language backbone from OpenBMB.
|
| 7 |
+
- DINOv3: visual feature encoder from Meta. The model license is reproduced in
|
| 8 |
+
`licenses/DINOV3_LICENSE.md`.
|
| 9 |
+
- SigLIP: visual feature encoder from Google.
|
| 10 |
+
- Habitat-Lab and Habitat-Sim: simulation framework from Meta. The vendored
|
| 11 |
+
Habitat-Lab fork is under `third_party/habitat-lab` and retains its upstream
|
| 12 |
+
copyright headers and MIT terms.
|
| 13 |
+
- EVT-Bench tracking extensions: simulator actions, sensors, and measurements
|
| 14 |
+
under `evt_bench`.
|
| 15 |
+
- HM3D, MP3D, humanoid, and robot assets are not redistributed. Users must
|
| 16 |
+
obtain them from their providers and accept the applicable licenses.
|
added_tokens.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"<|execute_end|>": 73444,
|
| 3 |
+
"<|execute_start|>": 73443,
|
| 4 |
+
"<|fim_middle|>": 73446,
|
| 5 |
+
"<|fim_prefix|>": 73445,
|
| 6 |
+
"<|fim_suffix|>": 73447,
|
| 7 |
+
"<|im_end|>": 73440,
|
| 8 |
+
"<|im_start|>": 73441,
|
| 9 |
+
"<|tool_call|>": 73442
|
| 10 |
+
}
|
assets/discord.jpg
ADDED
|
Git LFS Details
|
assets/discord.png
ADDED
|
Git LFS Details
|
assets/github.png
ADDED
|
Git LFS Details
|
assets/hf.png
ADDED
|
Git LFS Details
|
assets/metric.png
ADDED
|
Git LFS Details
|
assets/track1.gif
ADDED
|
Git LFS Details
|
assets/track2.gif
ADDED
|
Git LFS Details
|
assets/track3.gif
ADDED
|
Git LFS Details
|
assets/x.jpg
ADDED
|
Git LFS Details
|
assets/x.png
ADDED
|
Git LFS Details
|
config.json
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"MiniCPMRobotTrackModel"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_robottrack.MiniCPMRobotTrackConfig",
|
| 7 |
+
"AutoModel": "modeling_robottrack.MiniCPMRobotTrackModel"
|
| 8 |
+
},
|
| 9 |
+
"model_type": "minicpm_robottrack",
|
| 10 |
+
"model_name": "MiniCPM-RobotTrack",
|
| 11 |
+
"backbone_name": "openbmb/MiniCPM4-0.5B",
|
| 12 |
+
"backbone_config": {
|
| 13 |
+
"bos_token_id": 1,
|
| 14 |
+
"eos_token_id": [
|
| 15 |
+
2,
|
| 16 |
+
73440
|
| 17 |
+
],
|
| 18 |
+
"hidden_act": "silu",
|
| 19 |
+
"hidden_size": 1024,
|
| 20 |
+
"initializer_range": 0.1,
|
| 21 |
+
"intermediate_size": 4096,
|
| 22 |
+
"max_position_embeddings": 32768,
|
| 23 |
+
"num_attention_heads": 16,
|
| 24 |
+
"num_hidden_layers": 24,
|
| 25 |
+
"num_key_value_heads": 2,
|
| 26 |
+
"rms_norm_eps": 1e-05,
|
| 27 |
+
"rope_scaling": {
|
| 28 |
+
"rope_type": "longrope",
|
| 29 |
+
"long_factor": [
|
| 30 |
+
1.0004360675811768,
|
| 31 |
+
1.0668443441390991,
|
| 32 |
+
1.1631425619125366,
|
| 33 |
+
1.3025742769241333,
|
| 34 |
+
1.5040205717086792,
|
| 35 |
+
1.7941505908966064,
|
| 36 |
+
2.2101221084594727,
|
| 37 |
+
2.802666664123535,
|
| 38 |
+
3.6389970779418945,
|
| 39 |
+
4.804192543029785,
|
| 40 |
+
6.39855432510376,
|
| 41 |
+
8.527148246765137,
|
| 42 |
+
11.277542114257812,
|
| 43 |
+
14.684998512268066,
|
| 44 |
+
18.69317054748535,
|
| 45 |
+
23.13019371032715,
|
| 46 |
+
27.72362518310547,
|
| 47 |
+
32.1606559753418,
|
| 48 |
+
36.168827056884766,
|
| 49 |
+
39.57627868652344,
|
| 50 |
+
42.32667541503906,
|
| 51 |
+
44.45526885986328,
|
| 52 |
+
46.04962921142578,
|
| 53 |
+
47.21482849121094,
|
| 54 |
+
48.05115509033203,
|
| 55 |
+
48.64370346069336,
|
| 56 |
+
49.05967712402344,
|
| 57 |
+
49.34980392456055,
|
| 58 |
+
49.551246643066406,
|
| 59 |
+
49.69068145751953,
|
| 60 |
+
49.78697967529297,
|
| 61 |
+
49.85338592529297
|
| 62 |
+
],
|
| 63 |
+
"short_factor": [
|
| 64 |
+
1.0004360675811768,
|
| 65 |
+
1.0668443441390991,
|
| 66 |
+
1.1631425619125366,
|
| 67 |
+
1.3025742769241333,
|
| 68 |
+
1.5040205717086792,
|
| 69 |
+
1.7941505908966064,
|
| 70 |
+
2.2101221084594727,
|
| 71 |
+
2.802666664123535,
|
| 72 |
+
3.6389970779418945,
|
| 73 |
+
4.804192543029785,
|
| 74 |
+
6.39855432510376,
|
| 75 |
+
8.527148246765137,
|
| 76 |
+
11.277542114257812,
|
| 77 |
+
14.684998512268066,
|
| 78 |
+
18.69317054748535,
|
| 79 |
+
23.13019371032715,
|
| 80 |
+
27.72362518310547,
|
| 81 |
+
32.1606559753418,
|
| 82 |
+
36.168827056884766,
|
| 83 |
+
39.57627868652344,
|
| 84 |
+
42.32667541503906,
|
| 85 |
+
44.45526885986328,
|
| 86 |
+
46.04962921142578,
|
| 87 |
+
47.21482849121094,
|
| 88 |
+
48.05115509033203,
|
| 89 |
+
48.64370346069336,
|
| 90 |
+
49.05967712402344,
|
| 91 |
+
49.34980392456055,
|
| 92 |
+
49.551246643066406,
|
| 93 |
+
49.69068145751953,
|
| 94 |
+
49.78697967529297,
|
| 95 |
+
49.85338592529297
|
| 96 |
+
],
|
| 97 |
+
"original_max_position_embeddings": 32768
|
| 98 |
+
},
|
| 99 |
+
"use_cache": false,
|
| 100 |
+
"vocab_size": 73448,
|
| 101 |
+
"scale_emb": 12,
|
| 102 |
+
"dim_model_base": 256,
|
| 103 |
+
"scale_depth": 1.4
|
| 104 |
+
},
|
| 105 |
+
"backbone_dtype": "bfloat16",
|
| 106 |
+
"vision_feature_dim": 1536,
|
| 107 |
+
"history_frames": 31,
|
| 108 |
+
"coarse_tokens_per_frame": 4,
|
| 109 |
+
"fine_tokens_current_frame": 64,
|
| 110 |
+
"num_waypoints": 8,
|
| 111 |
+
"action_dim": 3,
|
| 112 |
+
"max_text_tokens": 128,
|
| 113 |
+
"max_time_steps": 4096,
|
| 114 |
+
"trajectory_dropout": 0.4,
|
| 115 |
+
"xy_scale": 2.0,
|
| 116 |
+
"use_tanh_actions": true,
|
| 117 |
+
"transformers_version": "4.56.2"
|
| 118 |
+
}
|
configuration_minicpm.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The OpenBMB Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" MiniCPM model configuration"""
|
| 16 |
+
|
| 17 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 18 |
+
from transformers.utils import logging
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
MINICPM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MiniCPMConfig(PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`MiniCPMModel`]. It is used to instantiate an MiniCPM
|
| 28 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 29 |
+
defaults will yield a similar configuration to that of the MiniCPM-7B.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
| 37 |
+
Vocabulary size of the MiniCPM model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`MiniCPMModel`]
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 40 |
+
Dimension of the hidden representations.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
| 42 |
+
Dimension of the MLP representations.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 44 |
+
Number of hidden layers in the Transformer decoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
| 47 |
+
num_key_value_heads (`int`, *optional*):
|
| 48 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 49 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 50 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 51 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 52 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 53 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 54 |
+
`num_attention_heads`.
|
| 55 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 56 |
+
The non-linear activation function (function or string) in the decoder.
|
| 57 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 58 |
+
The maximum sequence length that this model might ever be used with. MiniCPM 1 supports up to 2048 tokens,
|
| 59 |
+
MiniCPM 2 up to 4096, CodeMiniCPM up to 16384.
|
| 60 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 61 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 62 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 63 |
+
The epsilon used by the rms normalization layers.
|
| 64 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 65 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 66 |
+
relevant if `config.is_decoder=True`.
|
| 67 |
+
pad_token_id (`int`, *optional*):
|
| 68 |
+
Padding token id.
|
| 69 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
| 70 |
+
Beginning of stream token id.
|
| 71 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 72 |
+
End of stream token id.
|
| 73 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
| 74 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
| 75 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
| 76 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 77 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
| 78 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 79 |
+
Whether to tie weight embeddings
|
| 80 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
| 81 |
+
The base period of the RoPE embeddings.
|
| 82 |
+
rope_scaling (`Dict`, *optional*):
|
| 83 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
| 84 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
| 85 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
| 86 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
| 87 |
+
these scaling strategies behave:
|
| 88 |
+
https://www.reddit.com/r/LocalMiniCPM/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
| 89 |
+
experimental feature, subject to breaking API changes in future versions.
|
| 90 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
| 91 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
| 92 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 93 |
+
The dropout ratio for the attention probabilities.
|
| 94 |
+
|
| 95 |
+
```python
|
| 96 |
+
>>> from transformers import MiniCPMModel, MiniCPMConfig
|
| 97 |
+
|
| 98 |
+
>>> # Initializing a MiniCPM minicpm-7b style configuration
|
| 99 |
+
>>> configuration = MiniCPMConfig()
|
| 100 |
+
|
| 101 |
+
>>> # Initializing a model from the minicpm-7b style configuration
|
| 102 |
+
>>> model = MiniCPMModel(configuration)
|
| 103 |
+
|
| 104 |
+
>>> # Accessing the model configuration
|
| 105 |
+
>>> configuration = model.config
|
| 106 |
+
```"""
|
| 107 |
+
|
| 108 |
+
model_type = 'minicpm'
|
| 109 |
+
keys_to_ignore_at_inference = ['past_key_values']
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
vocab_size=32000,
|
| 114 |
+
hidden_size=4096,
|
| 115 |
+
intermediate_size=11008,
|
| 116 |
+
num_hidden_layers=32,
|
| 117 |
+
num_attention_heads=32,
|
| 118 |
+
num_key_value_heads=None,
|
| 119 |
+
hidden_act='silu',
|
| 120 |
+
max_position_embeddings=2048,
|
| 121 |
+
initializer_range=0.02,
|
| 122 |
+
rms_norm_eps=1e-6,
|
| 123 |
+
use_cache=True,
|
| 124 |
+
pad_token_id=None,
|
| 125 |
+
bos_token_id=1,
|
| 126 |
+
eos_token_id=2,
|
| 127 |
+
pretraining_tp=1,
|
| 128 |
+
tie_word_embeddings=True,
|
| 129 |
+
rope_theta=10000.0,
|
| 130 |
+
rope_scaling=None,
|
| 131 |
+
attention_bias=False,
|
| 132 |
+
attention_dropout=0.0,
|
| 133 |
+
scale_emb=1,
|
| 134 |
+
dim_model_base=1,
|
| 135 |
+
scale_depth=1,
|
| 136 |
+
mup_denominator=None,
|
| 137 |
+
sparse_config=None,
|
| 138 |
+
**kwargs):
|
| 139 |
+
|
| 140 |
+
self.vocab_size = vocab_size
|
| 141 |
+
self.max_position_embeddings = max_position_embeddings
|
| 142 |
+
self.hidden_size = hidden_size
|
| 143 |
+
self.intermediate_size = intermediate_size
|
| 144 |
+
self.num_hidden_layers = num_hidden_layers
|
| 145 |
+
self.num_attention_heads = num_attention_heads
|
| 146 |
+
|
| 147 |
+
# for backward compatibility
|
| 148 |
+
if num_key_value_heads is None:
|
| 149 |
+
num_key_value_heads = num_attention_heads
|
| 150 |
+
|
| 151 |
+
self.num_key_value_heads = num_key_value_heads
|
| 152 |
+
self.hidden_act = hidden_act
|
| 153 |
+
self.initializer_range = initializer_range
|
| 154 |
+
self.rms_norm_eps = rms_norm_eps
|
| 155 |
+
self.pretraining_tp = pretraining_tp
|
| 156 |
+
self.use_cache = use_cache
|
| 157 |
+
self.rope_theta = rope_theta
|
| 158 |
+
self.rope_scaling = rope_scaling
|
| 159 |
+
# self._rope_scaling_validation()
|
| 160 |
+
self.attention_bias = attention_bias
|
| 161 |
+
self.attention_dropout = attention_dropout
|
| 162 |
+
self.scale_emb = scale_emb
|
| 163 |
+
self.dim_model_base = dim_model_base
|
| 164 |
+
self.scale_depth = scale_depth
|
| 165 |
+
# only used for Eagle Head
|
| 166 |
+
self.mup_denominator = mup_denominator
|
| 167 |
+
|
| 168 |
+
# sparse config
|
| 169 |
+
self.sparse_config = sparse_config
|
| 170 |
+
|
| 171 |
+
super().__init__(
|
| 172 |
+
pad_token_id=pad_token_id,
|
| 173 |
+
bos_token_id=bos_token_id,
|
| 174 |
+
eos_token_id=eos_token_id,
|
| 175 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 176 |
+
**kwargs,
|
| 177 |
+
)
|
| 178 |
+
try:
|
| 179 |
+
import flash_attn
|
| 180 |
+
self._attn_implementation = 'flash_attention_2'
|
| 181 |
+
except:
|
| 182 |
+
pass
|
| 183 |
+
|
| 184 |
+
def _rope_scaling_validation(self):
|
| 185 |
+
"""
|
| 186 |
+
Validate the `rope_scaling` configuration.
|
| 187 |
+
"""
|
| 188 |
+
if self.rope_scaling is None:
|
| 189 |
+
return
|
| 190 |
+
|
| 191 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
| 192 |
+
raise ValueError(
|
| 193 |
+
'`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, '
|
| 194 |
+
f'got {self.rope_scaling}'
|
| 195 |
+
)
|
| 196 |
+
rope_scaling_type = self.rope_scaling.get('type', None)
|
| 197 |
+
rope_scaling_factor = self.rope_scaling.get('factor', None)
|
| 198 |
+
if rope_scaling_type is None or rope_scaling_type not in ['linear', 'dynamic']:
|
| 199 |
+
raise ValueError(
|
| 200 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
| 201 |
+
)
|
| 202 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
| 203 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
configuration_robottrack.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face configuration for MiniCPM-RobotTrack."""
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, Optional
|
| 4 |
+
|
| 5 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class MiniCPMRobotTrackConfig(PretrainedConfig):
|
| 9 |
+
"""Configuration for the MiniCPM-RobotTrack trajectory policy."""
|
| 10 |
+
|
| 11 |
+
model_type = "minicpm_robottrack"
|
| 12 |
+
has_no_defaults_at_init = True
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
backbone_config: Optional[Dict[str, Any]] = None,
|
| 17 |
+
vision_feature_dim: int = 1536,
|
| 18 |
+
history_frames: int = 31,
|
| 19 |
+
coarse_tokens_per_frame: int = 4,
|
| 20 |
+
fine_tokens_current_frame: int = 64,
|
| 21 |
+
num_waypoints: int = 8,
|
| 22 |
+
action_dim: int = 3,
|
| 23 |
+
max_text_tokens: int = 128,
|
| 24 |
+
max_time_steps: int = 4096,
|
| 25 |
+
trajectory_dropout: float = 0.4,
|
| 26 |
+
xy_scale: float = 2.0,
|
| 27 |
+
use_tanh_actions: bool = True,
|
| 28 |
+
backbone_dtype: str = "bfloat16",
|
| 29 |
+
**kwargs: Any,
|
| 30 |
+
) -> None:
|
| 31 |
+
self.backbone_config = dict(backbone_config or {})
|
| 32 |
+
self.vision_feature_dim = int(vision_feature_dim)
|
| 33 |
+
self.history_frames = int(history_frames)
|
| 34 |
+
self.coarse_tokens_per_frame = int(coarse_tokens_per_frame)
|
| 35 |
+
self.fine_tokens_current_frame = int(fine_tokens_current_frame)
|
| 36 |
+
self.num_waypoints = int(num_waypoints)
|
| 37 |
+
self.action_dim = int(action_dim)
|
| 38 |
+
self.max_text_tokens = int(max_text_tokens)
|
| 39 |
+
self.max_time_steps = int(max_time_steps)
|
| 40 |
+
self.trajectory_dropout = float(trajectory_dropout)
|
| 41 |
+
self.xy_scale = float(xy_scale)
|
| 42 |
+
self.use_tanh_actions = bool(use_tanh_actions)
|
| 43 |
+
self.backbone_dtype = str(backbone_dtype)
|
| 44 |
+
self._validate_robot_track_config()
|
| 45 |
+
super().__init__(**kwargs)
|
| 46 |
+
|
| 47 |
+
def _validate_robot_track_config(self) -> None:
|
| 48 |
+
if not self.backbone_config:
|
| 49 |
+
raise ValueError("backbone_config must contain the bundled MiniCPM configuration")
|
| 50 |
+
if self.vision_feature_dim <= 0:
|
| 51 |
+
raise ValueError("vision_feature_dim must be positive")
|
| 52 |
+
if self.history_frames < 0:
|
| 53 |
+
raise ValueError("history_frames cannot be negative")
|
| 54 |
+
for name, value in (
|
| 55 |
+
("coarse_tokens_per_frame", self.coarse_tokens_per_frame),
|
| 56 |
+
("fine_tokens_current_frame", self.fine_tokens_current_frame),
|
| 57 |
+
):
|
| 58 |
+
side = int(round(value**0.5)) if value > 0 else 0
|
| 59 |
+
if side * side != value:
|
| 60 |
+
raise ValueError(f"{name} must be a positive square number")
|
| 61 |
+
if self.num_waypoints < 2:
|
| 62 |
+
raise ValueError("num_waypoints must be at least 2")
|
| 63 |
+
if self.action_dim != 3:
|
| 64 |
+
raise ValueError("actions must use [x, y, yaw] format")
|
| 65 |
+
if self.max_text_tokens <= 0 or self.max_time_steps <= 0:
|
| 66 |
+
raise ValueError("token and time limits must be positive")
|
| 67 |
+
if not 0.0 <= self.trajectory_dropout < 1.0:
|
| 68 |
+
raise ValueError("trajectory_dropout must be in [0, 1)")
|
| 69 |
+
if self.xy_scale <= 0.0:
|
| 70 |
+
raise ValueError("xy_scale must be positive")
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:27cc7e58fd0797ea2dfa03b250847a7142eeedc7babbadd7bc63401d051ec7f3
|
| 3 |
+
size 931428452
|
modeling_minicpm.py
ADDED
|
@@ -0,0 +1,1514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The OpenBMB Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch MiniCPM model."""
|
| 16 |
+
import math
|
| 17 |
+
import re
|
| 18 |
+
import warnings
|
| 19 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 26 |
+
from transformers.activations import ACT2FN
|
| 27 |
+
from transformers.cache_utils import Cache, DynamicCache, CacheLayerMixin, DynamicLayer
|
| 28 |
+
from transformers.modeling_attn_mask_utils import (
|
| 29 |
+
AttentionMaskConverter,
|
| 30 |
+
_prepare_4d_attention_mask,
|
| 31 |
+
_prepare_4d_causal_attention_mask,
|
| 32 |
+
_prepare_4d_causal_attention_mask_for_sdpa,
|
| 33 |
+
)
|
| 34 |
+
from transformers.modeling_outputs import (
|
| 35 |
+
BaseModelOutputWithPast,
|
| 36 |
+
CausalLMOutputWithPast,
|
| 37 |
+
SequenceClassifierOutputWithPast,
|
| 38 |
+
)
|
| 39 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 40 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
|
| 41 |
+
from transformers.utils import (
|
| 42 |
+
add_start_docstrings,
|
| 43 |
+
add_start_docstrings_to_model_forward,
|
| 44 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 45 |
+
logging,
|
| 46 |
+
replace_return_docstrings,
|
| 47 |
+
)
|
| 48 |
+
from transformers.utils.import_utils import is_torch_fx_available
|
| 49 |
+
|
| 50 |
+
from .configuration_minicpm import MiniCPMConfig
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 54 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
| 55 |
+
except:
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
|
| 61 |
+
# It means that the function will not be traced through and simply appear as a node in the graph.
|
| 62 |
+
if is_torch_fx_available():
|
| 63 |
+
if not is_torch_greater_or_equal_than_1_13:
|
| 64 |
+
import torch.fx
|
| 65 |
+
|
| 66 |
+
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
logger = logging.get_logger(__name__)
|
| 70 |
+
|
| 71 |
+
_CONFIG_FOR_DOC = 'MiniCPMConfig'
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _get_unpad_data(attention_mask):
|
| 75 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
| 76 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
| 77 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
| 78 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
| 79 |
+
return (
|
| 80 |
+
indices,
|
| 81 |
+
cu_seqlens,
|
| 82 |
+
max_seqlen_in_batch,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# @torch.jit.script # type: ignore
|
| 89 |
+
def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
|
| 90 |
+
old_dtype = hidden.dtype
|
| 91 |
+
variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
|
| 92 |
+
hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
|
| 93 |
+
return hidden * weight
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class MiniCPMRMSNorm(nn.Module):
|
| 97 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 98 |
+
"""
|
| 99 |
+
MiniCPMRMSNorm is equivalent to T5LayerNorm
|
| 100 |
+
"""
|
| 101 |
+
super().__init__()
|
| 102 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 103 |
+
self.variance_epsilon = eps
|
| 104 |
+
|
| 105 |
+
def forward(self, hidden_states):
|
| 106 |
+
return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class MiniCPMRotaryEmbedding(nn.Module):
|
| 113 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 114 |
+
super().__init__()
|
| 115 |
+
|
| 116 |
+
self.dim = dim
|
| 117 |
+
self.max_position_embeddings = max_position_embeddings
|
| 118 |
+
self.base = base
|
| 119 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 120 |
+
self.register_buffer('inv_freq', inv_freq, persistent=False)
|
| 121 |
+
|
| 122 |
+
# Build here to make `torch.jit.trace` work.
|
| 123 |
+
self._set_cos_sin_cache(
|
| 124 |
+
# seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
| 125 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 129 |
+
self.max_seq_len_cached = seq_len
|
| 130 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 131 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 132 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 133 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 134 |
+
|
| 135 |
+
self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
|
| 136 |
+
self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
|
| 137 |
+
|
| 138 |
+
def forward(self, x, seq_len=None):
|
| 139 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 140 |
+
if seq_len > self.max_seq_len_cached:
|
| 141 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
| 142 |
+
|
| 143 |
+
return (
|
| 144 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
| 145 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class MiniCPMLongRoPE(MiniCPMRotaryEmbedding):
|
| 150 |
+
"""MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 151 |
+
|
| 152 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, short_factor=None, long_factor=None, original_max_position_embeddings=None):
|
| 153 |
+
self.short_factor = short_factor
|
| 154 |
+
self.long_factor = long_factor
|
| 155 |
+
self.original_max_position_embeddings = original_max_position_embeddings
|
| 156 |
+
scale = (max_position_embeddings / self.original_max_position_embeddings)
|
| 157 |
+
self.scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
|
| 158 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
| 159 |
+
|
| 160 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 161 |
+
self.max_seq_len_cached = seq_len
|
| 162 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 163 |
+
if seq_len > self.original_max_position_embeddings:
|
| 164 |
+
ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=device)
|
| 165 |
+
else:
|
| 166 |
+
ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=device)
|
| 167 |
+
|
| 168 |
+
freqs = torch.mul(
|
| 169 |
+
torch.outer(t, 1.0 / ext_factors).to(device=device),
|
| 170 |
+
self.inv_freq.to(device=device).to(dtype)
|
| 171 |
+
)
|
| 172 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 173 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 174 |
+
self.register_buffer('cos_cached', emb.cos().to(dtype) * self.scaling_factor, persistent=False)
|
| 175 |
+
self.register_buffer('sin_cached', emb.sin().to(dtype) * self.scaling_factor, persistent=False)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
|
| 179 |
+
"""MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 180 |
+
|
| 181 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 182 |
+
self.scaling_factor = scaling_factor
|
| 183 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
| 184 |
+
|
| 185 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 186 |
+
self.max_seq_len_cached = seq_len
|
| 187 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 188 |
+
t = t / self.scaling_factor
|
| 189 |
+
|
| 190 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 191 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 192 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 193 |
+
self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
|
| 194 |
+
self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
|
| 198 |
+
"""MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 199 |
+
|
| 200 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 201 |
+
self.scaling_factor = scaling_factor
|
| 202 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
| 203 |
+
|
| 204 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 205 |
+
self.max_seq_len_cached = seq_len
|
| 206 |
+
|
| 207 |
+
if seq_len > self.max_position_embeddings:
|
| 208 |
+
base = self.base * (
|
| 209 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
| 210 |
+
) ** (self.dim / (self.dim - 2))
|
| 211 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 212 |
+
self.register_buffer('inv_freq', inv_freq, persistent=False)
|
| 213 |
+
|
| 214 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 215 |
+
|
| 216 |
+
freqs = torch.outer(t, self.inv_freq)
|
| 217 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 218 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 219 |
+
|
| 220 |
+
self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
|
| 221 |
+
self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def rotate_half(x):
|
| 225 |
+
"""Rotates half the hidden dims of the input."""
|
| 226 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 227 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 228 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
| 232 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 233 |
+
|
| 234 |
+
Args:
|
| 235 |
+
q (`torch.Tensor`): The query tensor.
|
| 236 |
+
k (`torch.Tensor`): The key tensor.
|
| 237 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 238 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 239 |
+
position_ids (`torch.Tensor`):
|
| 240 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
| 241 |
+
used to pass offsetted position ids when working with a KV-cache.
|
| 242 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 243 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 244 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 245 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 246 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 247 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 248 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 249 |
+
Returns:
|
| 250 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 251 |
+
"""
|
| 252 |
+
# cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
| 253 |
+
# sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
| 254 |
+
# q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 255 |
+
# k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 256 |
+
orig_dtype = k.dtype
|
| 257 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
|
| 258 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
|
| 259 |
+
q_fp32 = q.to(dtype=torch.float32, device=q.device)
|
| 260 |
+
k_fp32 = k.to(dtype=torch.float32, device=k.device)
|
| 261 |
+
q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
|
| 262 |
+
k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
|
| 263 |
+
return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class MiniCPMMLP(nn.Module):
|
| 267 |
+
def __init__(self, config):
|
| 268 |
+
super().__init__()
|
| 269 |
+
self.config = config
|
| 270 |
+
self.hidden_size = config.hidden_size
|
| 271 |
+
self.intermediate_size = config.intermediate_size
|
| 272 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 273 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 274 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 275 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 276 |
+
|
| 277 |
+
def forward(self, x):
|
| 278 |
+
if self.config.pretraining_tp > 1:
|
| 279 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
| 280 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
| 281 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
| 282 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
| 283 |
+
|
| 284 |
+
gate_proj = torch.cat(
|
| 285 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
| 286 |
+
)
|
| 287 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
| 288 |
+
|
| 289 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
| 290 |
+
down_proj = [
|
| 291 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
| 292 |
+
]
|
| 293 |
+
down_proj = sum(down_proj)
|
| 294 |
+
else:
|
| 295 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 296 |
+
|
| 297 |
+
return down_proj
|
| 298 |
+
|
| 299 |
+
def _unpad_one_tensor(hidden_states, attention_mask):
|
| 300 |
+
# Unpad the hidden states using the indices
|
| 301 |
+
indices, cu_seqlens, max_seqlen_in_batch = _get_unpad_data(attention_mask)
|
| 302 |
+
batch_size, seq_len = hidden_states.shape[:2]
|
| 303 |
+
|
| 304 |
+
# Get the remaining dimensions
|
| 305 |
+
remaining_dims = hidden_states.shape[2:]
|
| 306 |
+
|
| 307 |
+
# Reshape to (batch_size * seq_len, *remaining_dims)
|
| 308 |
+
reshaped_states = hidden_states.reshape(batch_size * seq_len, *remaining_dims)
|
| 309 |
+
|
| 310 |
+
# Apply unpadding using indices
|
| 311 |
+
unpadded_states = index_first_axis(reshaped_states, indices)
|
| 312 |
+
|
| 313 |
+
return unpadded_states, indices, cu_seqlens, max_seqlen_in_batch
|
| 314 |
+
|
| 315 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 316 |
+
"""
|
| 317 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 318 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 319 |
+
"""
|
| 320 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 321 |
+
if n_rep == 1:
|
| 322 |
+
return hidden_states
|
| 323 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 324 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class MiniCPMAttention(nn.Module):
|
| 328 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 329 |
+
|
| 330 |
+
def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
|
| 331 |
+
super().__init__()
|
| 332 |
+
self.config = config
|
| 333 |
+
self.layer_idx = layer_idx
|
| 334 |
+
if layer_idx is None:
|
| 335 |
+
logger.warning_once(
|
| 336 |
+
f'Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will '
|
| 337 |
+
'to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` '
|
| 338 |
+
'when creating this class.'
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
self.attention_dropout = config.attention_dropout
|
| 342 |
+
self.hidden_size = config.hidden_size
|
| 343 |
+
self.num_heads = config.num_attention_heads
|
| 344 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 345 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 346 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 347 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 348 |
+
self.rope_theta = config.rope_theta
|
| 349 |
+
self.is_causal = True
|
| 350 |
+
|
| 351 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 352 |
+
raise ValueError(
|
| 353 |
+
f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
|
| 354 |
+
f' and `num_heads`: {self.num_heads}).'
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
| 358 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 359 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 360 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
| 361 |
+
self._init_rope()
|
| 362 |
+
|
| 363 |
+
def _init_rope(self):
|
| 364 |
+
if self.config.rope_scaling is None:
|
| 365 |
+
self.rotary_emb = MiniCPMRotaryEmbedding(
|
| 366 |
+
self.head_dim,
|
| 367 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 368 |
+
base=self.rope_theta,
|
| 369 |
+
)
|
| 370 |
+
else:
|
| 371 |
+
scaling_type = self.config.rope_scaling['rope_type']
|
| 372 |
+
scaling_factor = self.config.rope_scaling.get('factor', None)
|
| 373 |
+
if scaling_type == 'linear':
|
| 374 |
+
self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
|
| 375 |
+
self.head_dim,
|
| 376 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 377 |
+
scaling_factor=scaling_factor,
|
| 378 |
+
base=self.rope_theta,
|
| 379 |
+
)
|
| 380 |
+
elif scaling_type == 'dynamic':
|
| 381 |
+
self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
|
| 382 |
+
self.head_dim,
|
| 383 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 384 |
+
scaling_factor=scaling_factor,
|
| 385 |
+
base=self.rope_theta,
|
| 386 |
+
)
|
| 387 |
+
elif scaling_type == 'longrope':
|
| 388 |
+
self.rotary_emb = MiniCPMLongRoPE(
|
| 389 |
+
self.head_dim,
|
| 390 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 391 |
+
short_factor=self.config.rope_scaling['short_factor'],
|
| 392 |
+
long_factor=self.config.rope_scaling['long_factor'],
|
| 393 |
+
base=self.rope_theta,
|
| 394 |
+
original_max_position_embeddings=self.config.rope_scaling['original_max_position_embeddings']
|
| 395 |
+
)
|
| 396 |
+
else:
|
| 397 |
+
raise ValueError(f'Unknown RoPE scaling type {scaling_type}')
|
| 398 |
+
|
| 399 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 400 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 401 |
+
|
| 402 |
+
def forward(
|
| 403 |
+
self,
|
| 404 |
+
hidden_states: torch.Tensor,
|
| 405 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 406 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 407 |
+
past_key_value: Optional[Cache] = None,
|
| 408 |
+
output_attentions: bool = False,
|
| 409 |
+
use_cache: bool = False,
|
| 410 |
+
**kwargs,
|
| 411 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 412 |
+
if 'padding_mask' in kwargs:
|
| 413 |
+
warnings.warn(
|
| 414 |
+
'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
bsz, q_len, _ = hidden_states.size()
|
| 418 |
+
|
| 419 |
+
if self.config.pretraining_tp > 1:
|
| 420 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
| 421 |
+
query_slices = self.q_proj.weight.split(
|
| 422 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
| 423 |
+
)
|
| 424 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
| 425 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
| 426 |
+
|
| 427 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 428 |
+
query_states = torch.cat(query_states, dim=-1)
|
| 429 |
+
|
| 430 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 431 |
+
key_states = torch.cat(key_states, dim=-1)
|
| 432 |
+
|
| 433 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 434 |
+
value_states = torch.cat(value_states, dim=-1)
|
| 435 |
+
|
| 436 |
+
else:
|
| 437 |
+
query_states = self.q_proj(hidden_states)
|
| 438 |
+
key_states = self.k_proj(hidden_states)
|
| 439 |
+
value_states = self.v_proj(hidden_states)
|
| 440 |
+
|
| 441 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 442 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 443 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 444 |
+
|
| 445 |
+
kv_seq_len = position_ids.max().item() + 1
|
| 446 |
+
cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
|
| 447 |
+
|
| 448 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 449 |
+
|
| 450 |
+
if past_key_value is not None:
|
| 451 |
+
cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
|
| 452 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 453 |
+
|
| 454 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 455 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 456 |
+
|
| 457 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 458 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
| 459 |
+
raise ValueError(
|
| 460 |
+
f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
|
| 461 |
+
f' {attn_weights.size()}'
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
if attention_mask is not None:
|
| 465 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 466 |
+
raise ValueError(
|
| 467 |
+
f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
|
| 468 |
+
)
|
| 469 |
+
attn_weights = attn_weights + attention_mask
|
| 470 |
+
|
| 471 |
+
# upcast attention to fp32
|
| 472 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 473 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 474 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 475 |
+
|
| 476 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 477 |
+
raise ValueError(
|
| 478 |
+
f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
|
| 479 |
+
f' {attn_output.size()}'
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 483 |
+
|
| 484 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 485 |
+
|
| 486 |
+
if self.config.pretraining_tp > 1:
|
| 487 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
| 488 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
| 489 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
| 490 |
+
else:
|
| 491 |
+
attn_output = self.o_proj(attn_output)
|
| 492 |
+
|
| 493 |
+
if not output_attentions:
|
| 494 |
+
attn_weights = None
|
| 495 |
+
|
| 496 |
+
return attn_output, attn_weights, past_key_value
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
class MiniCPMFlashAttention2(MiniCPMAttention):
|
| 500 |
+
"""
|
| 501 |
+
MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
|
| 502 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 503 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 504 |
+
"""
|
| 505 |
+
|
| 506 |
+
def __init__(self, *args, **kwargs):
|
| 507 |
+
super().__init__(*args, **kwargs)
|
| 508 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 509 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
| 510 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
| 511 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 512 |
+
|
| 513 |
+
def forward(
|
| 514 |
+
self,
|
| 515 |
+
hidden_states: torch.Tensor,
|
| 516 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 517 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 518 |
+
past_key_value: Optional[Cache] = None,
|
| 519 |
+
output_attentions: bool = False,
|
| 520 |
+
use_cache: bool = False,
|
| 521 |
+
**kwargs,
|
| 522 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 523 |
+
# MiniCPMFlashAttention2 attention does not support output_attentions
|
| 524 |
+
if 'padding_mask' in kwargs:
|
| 525 |
+
warnings.warn(
|
| 526 |
+
'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# overwrite attention_mask with padding_mask
|
| 530 |
+
attention_mask = kwargs.pop('padding_mask')
|
| 531 |
+
|
| 532 |
+
output_attentions = False
|
| 533 |
+
|
| 534 |
+
bsz, q_len, _ = hidden_states.size()
|
| 535 |
+
|
| 536 |
+
query_states = self.q_proj(hidden_states)
|
| 537 |
+
key_states = self.k_proj(hidden_states)
|
| 538 |
+
value_states = self.v_proj(hidden_states)
|
| 539 |
+
|
| 540 |
+
# Flash attention requires the input to have the shape
|
| 541 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 542 |
+
# therefore we just need to keep the original shape
|
| 543 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 544 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 545 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 546 |
+
|
| 547 |
+
kv_seq_len = position_ids.max().item() + 1
|
| 548 |
+
cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
|
| 549 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 550 |
+
|
| 551 |
+
if past_key_value is not None:
|
| 552 |
+
cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
|
| 553 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 554 |
+
|
| 555 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
| 556 |
+
# to be able to avoid many of these transpose/reshape/view.
|
| 557 |
+
query_states = query_states.transpose(1, 2)
|
| 558 |
+
key_states = key_states.transpose(1, 2)
|
| 559 |
+
value_states = value_states.transpose(1, 2)
|
| 560 |
+
|
| 561 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
| 562 |
+
|
| 563 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 564 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 565 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
| 566 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
| 567 |
+
# in fp32. (MiniCPMRMSNorm handles it correctly)
|
| 568 |
+
|
| 569 |
+
input_dtype = query_states.dtype
|
| 570 |
+
if input_dtype == torch.float32:
|
| 571 |
+
# Handle the case where the model is quantized
|
| 572 |
+
if hasattr(self.config, '_pre_quantization_dtype'):
|
| 573 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 574 |
+
else:
|
| 575 |
+
target_dtype = self.q_proj.weight.dtype
|
| 576 |
+
|
| 577 |
+
logger.warning_once(
|
| 578 |
+
f'The input hidden states seems to be silently casted in float32, this might be related to'
|
| 579 |
+
f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in'
|
| 580 |
+
f' {target_dtype}.'
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
query_states = query_states.to(target_dtype)
|
| 584 |
+
key_states = key_states.to(target_dtype)
|
| 585 |
+
value_states = value_states.to(target_dtype)
|
| 586 |
+
|
| 587 |
+
attn_output = self._flash_attention_forward(
|
| 588 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
| 592 |
+
attn_output = self.o_proj(attn_output)
|
| 593 |
+
|
| 594 |
+
if not output_attentions:
|
| 595 |
+
attn_weights = None
|
| 596 |
+
|
| 597 |
+
return attn_output, attn_weights, past_key_value
|
| 598 |
+
|
| 599 |
+
def _flash_attention_forward(
|
| 600 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
| 601 |
+
):
|
| 602 |
+
"""
|
| 603 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
| 604 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
| 605 |
+
|
| 606 |
+
Args:
|
| 607 |
+
query_states (`torch.Tensor`):
|
| 608 |
+
Input query states to be passed to Flash Attention API
|
| 609 |
+
key_states (`torch.Tensor`):
|
| 610 |
+
Input key states to be passed to Flash Attention API
|
| 611 |
+
value_states (`torch.Tensor`):
|
| 612 |
+
Input value states to be passed to Flash Attention API
|
| 613 |
+
attention_mask (`torch.Tensor`):
|
| 614 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
| 615 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
| 616 |
+
dropout (`int`, *optional*):
|
| 617 |
+
Attention dropout
|
| 618 |
+
softmax_scale (`float`, *optional*):
|
| 619 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
| 620 |
+
"""
|
| 621 |
+
if not self._flash_attn_uses_top_left_mask:
|
| 622 |
+
causal = self.is_causal
|
| 623 |
+
else:
|
| 624 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MiniCPMFlashAttention2 __init__.
|
| 625 |
+
causal = self.is_causal and query_length != 1
|
| 626 |
+
# Contains at least one padding token in the sequence
|
| 627 |
+
if attention_mask is not None:
|
| 628 |
+
batch_size = query_states.shape[0]
|
| 629 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
| 630 |
+
query_states, key_states, value_states, attention_mask, query_length
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
| 634 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
| 635 |
+
attn_output_unpad = flash_attn_varlen_func(
|
| 636 |
+
query_states,
|
| 637 |
+
key_states,
|
| 638 |
+
value_states,
|
| 639 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 640 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 641 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 642 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 643 |
+
dropout_p=dropout,
|
| 644 |
+
softmax_scale=softmax_scale,
|
| 645 |
+
causal=causal,
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
| 649 |
+
else:
|
| 650 |
+
attn_output = flash_attn_func(
|
| 651 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
return attn_output
|
| 655 |
+
|
| 656 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
| 657 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
| 658 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
| 659 |
+
|
| 660 |
+
key_layer = index_first_axis(
|
| 661 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 662 |
+
)
|
| 663 |
+
value_layer = index_first_axis(
|
| 664 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
| 665 |
+
)
|
| 666 |
+
if query_length == kv_seq_len:
|
| 667 |
+
query_layer = index_first_axis(
|
| 668 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
| 669 |
+
)
|
| 670 |
+
cu_seqlens_q = cu_seqlens_k
|
| 671 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 672 |
+
indices_q = indices_k
|
| 673 |
+
elif query_length == 1:
|
| 674 |
+
max_seqlen_in_batch_q = 1
|
| 675 |
+
cu_seqlens_q = torch.arange(
|
| 676 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 677 |
+
) # There is a memcpy here, that is very bad.
|
| 678 |
+
indices_q = cu_seqlens_q[:-1]
|
| 679 |
+
query_layer = query_layer.squeeze(1)
|
| 680 |
+
else:
|
| 681 |
+
# The -q_len: slice assumes left padding.
|
| 682 |
+
attention_mask = attention_mask[:, -query_length:]
|
| 683 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 684 |
+
|
| 685 |
+
return (
|
| 686 |
+
query_layer,
|
| 687 |
+
key_layer,
|
| 688 |
+
value_layer,
|
| 689 |
+
indices_q,
|
| 690 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 691 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
class MiniCPMSdpaAttention(MiniCPMAttention):
|
| 696 |
+
"""
|
| 697 |
+
MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 698 |
+
`MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 699 |
+
SDPA API.
|
| 700 |
+
"""
|
| 701 |
+
|
| 702 |
+
# Adapted from MiniCPMAttention.forward
|
| 703 |
+
def forward(
|
| 704 |
+
self,
|
| 705 |
+
hidden_states: torch.Tensor,
|
| 706 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 707 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 708 |
+
past_key_value: Optional[Cache] = None,
|
| 709 |
+
output_attentions: bool = False,
|
| 710 |
+
use_cache: bool = False,
|
| 711 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 712 |
+
if output_attentions:
|
| 713 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 714 |
+
logger.warning_once(
|
| 715 |
+
'MiniCPMModel is using MiniCPMSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, '
|
| 716 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 717 |
+
)
|
| 718 |
+
return super().forward(
|
| 719 |
+
hidden_states=hidden_states,
|
| 720 |
+
attention_mask=attention_mask,
|
| 721 |
+
position_ids=position_ids,
|
| 722 |
+
past_key_value=past_key_value,
|
| 723 |
+
output_attentions=output_attentions,
|
| 724 |
+
use_cache=use_cache,
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
bsz, q_len, _ = hidden_states.size()
|
| 728 |
+
|
| 729 |
+
query_states = self.q_proj(hidden_states)
|
| 730 |
+
key_states = self.k_proj(hidden_states)
|
| 731 |
+
value_states = self.v_proj(hidden_states)
|
| 732 |
+
|
| 733 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 734 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 735 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 736 |
+
|
| 737 |
+
kv_seq_len = position_ids.max().item() + 1
|
| 738 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 739 |
+
|
| 740 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 741 |
+
|
| 742 |
+
if past_key_value is not None:
|
| 743 |
+
cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
|
| 744 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 745 |
+
|
| 746 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 747 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 748 |
+
|
| 749 |
+
if attention_mask is not None:
|
| 750 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 751 |
+
raise ValueError(
|
| 752 |
+
f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 756 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 757 |
+
if query_states.device.type == 'cuda' and attention_mask is not None:
|
| 758 |
+
query_states = query_states.contiguous()
|
| 759 |
+
key_states = key_states.contiguous()
|
| 760 |
+
value_states = value_states.contiguous()
|
| 761 |
+
|
| 762 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 763 |
+
query_states,
|
| 764 |
+
key_states,
|
| 765 |
+
value_states,
|
| 766 |
+
attn_mask=attention_mask,
|
| 767 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 768 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
| 769 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 773 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 774 |
+
|
| 775 |
+
attn_output = self.o_proj(attn_output)
|
| 776 |
+
|
| 777 |
+
return attn_output, None, past_key_value
|
| 778 |
+
|
| 779 |
+
|
| 780 |
+
MINICPM_ATTENTION_CLASSES = {
|
| 781 |
+
'eager': MiniCPMAttention,
|
| 782 |
+
'flash_attention_2': MiniCPMFlashAttention2,
|
| 783 |
+
'sdpa': MiniCPMSdpaAttention,
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
class MiniCPMDecoderLayer(nn.Module):
|
| 788 |
+
def __init__(self, config: MiniCPMConfig, layer_idx: int):
|
| 789 |
+
super().__init__()
|
| 790 |
+
self.hidden_size = config.hidden_size
|
| 791 |
+
self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
| 792 |
+
|
| 793 |
+
self.mlp = MiniCPMMLP(config)
|
| 794 |
+
self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 795 |
+
self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 796 |
+
|
| 797 |
+
self.scale_depth = config.scale_depth
|
| 798 |
+
self.num_hidden_layers = config.num_hidden_layers
|
| 799 |
+
|
| 800 |
+
def forward(
|
| 801 |
+
self,
|
| 802 |
+
hidden_states: torch.Tensor,
|
| 803 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 804 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 805 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 806 |
+
output_attentions: Optional[bool] = False,
|
| 807 |
+
use_cache: Optional[bool] = False,
|
| 808 |
+
**kwargs,
|
| 809 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 810 |
+
"""
|
| 811 |
+
Args:
|
| 812 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 813 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 814 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
| 815 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
| 816 |
+
output_attentions (`bool`, *optional*):
|
| 817 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 818 |
+
returned tensors for more detail.
|
| 819 |
+
use_cache (`bool`, *optional*):
|
| 820 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 821 |
+
(see `past_key_values`).
|
| 822 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 823 |
+
"""
|
| 824 |
+
if 'padding_mask' in kwargs:
|
| 825 |
+
warnings.warn(
|
| 826 |
+
'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
residual = hidden_states
|
| 830 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 831 |
+
# Self Attention
|
| 832 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 833 |
+
hidden_states=hidden_states,
|
| 834 |
+
attention_mask=attention_mask,
|
| 835 |
+
position_ids=position_ids,
|
| 836 |
+
past_key_value=past_key_value,
|
| 837 |
+
output_attentions=output_attentions,
|
| 838 |
+
use_cache=use_cache,
|
| 839 |
+
**kwargs,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
|
| 843 |
+
|
| 844 |
+
# Fully Connected
|
| 845 |
+
residual = hidden_states
|
| 846 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 847 |
+
|
| 848 |
+
hidden_states = self.mlp(hidden_states)
|
| 849 |
+
hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
|
| 850 |
+
|
| 851 |
+
outputs = (hidden_states,)
|
| 852 |
+
|
| 853 |
+
if output_attentions:
|
| 854 |
+
outputs += (self_attn_weights,)
|
| 855 |
+
|
| 856 |
+
if use_cache:
|
| 857 |
+
outputs += (present_key_value,)
|
| 858 |
+
|
| 859 |
+
return outputs
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
MINICPM_START_DOCSTRING = r"""
|
| 863 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 864 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 865 |
+
etc.)
|
| 866 |
+
|
| 867 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 868 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 869 |
+
and behavior.
|
| 870 |
+
|
| 871 |
+
Parameters:
|
| 872 |
+
config ([`MiniCPMConfig`]):
|
| 873 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 874 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 875 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 876 |
+
"""
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
@add_start_docstrings(
|
| 880 |
+
'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
|
| 881 |
+
MINICPM_START_DOCSTRING,
|
| 882 |
+
)
|
| 883 |
+
class MiniCPMPreTrainedModel(PreTrainedModel):
|
| 884 |
+
config_class = MiniCPMConfig
|
| 885 |
+
base_model_prefix = 'model'
|
| 886 |
+
supports_gradient_checkpointing = True
|
| 887 |
+
_no_split_modules = ['MiniCPMDecoderLayer']
|
| 888 |
+
_skip_keys_device_placement = 'past_key_values'
|
| 889 |
+
_supports_flash_attn_2 = True
|
| 890 |
+
_supports_sdpa = True
|
| 891 |
+
_supports_cache_class = True
|
| 892 |
+
|
| 893 |
+
def _init_weights(self, module):
|
| 894 |
+
std = self.config.initializer_range
|
| 895 |
+
if isinstance(module, nn.Linear):
|
| 896 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 897 |
+
if module.bias is not None:
|
| 898 |
+
module.bias.data.zero_()
|
| 899 |
+
elif isinstance(module, nn.Embedding):
|
| 900 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 901 |
+
if module.padding_idx is not None:
|
| 902 |
+
module.weight.data[module.padding_idx].zero_()
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
MINICPM_INPUTS_DOCSTRING = r"""
|
| 906 |
+
Args:
|
| 907 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 908 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 909 |
+
it.
|
| 910 |
+
|
| 911 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 912 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 913 |
+
|
| 914 |
+
[What are input IDs?](../glossary#input-ids)
|
| 915 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 916 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 917 |
+
|
| 918 |
+
- 1 for tokens that are **not masked**,
|
| 919 |
+
- 0 for tokens that are **masked**.
|
| 920 |
+
|
| 921 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 922 |
+
|
| 923 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 924 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 925 |
+
|
| 926 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
| 927 |
+
`past_key_values`).
|
| 928 |
+
|
| 929 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 930 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 931 |
+
information on the default strategy.
|
| 932 |
+
|
| 933 |
+
- 1 indicates the head is **not masked**,
|
| 934 |
+
- 0 indicates the head is **masked**.
|
| 935 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 936 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 937 |
+
config.n_positions - 1]`.
|
| 938 |
+
|
| 939 |
+
[What are position IDs?](../glossary#position-ids)
|
| 940 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 941 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 942 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
| 943 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
| 944 |
+
|
| 945 |
+
Two formats are allowed:
|
| 946 |
+
- a [`~cache_utils.Cache`] instance;
|
| 947 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
| 948 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
| 949 |
+
cache format.
|
| 950 |
+
|
| 951 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
| 952 |
+
legacy cache format will be returned.
|
| 953 |
+
|
| 954 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
| 955 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
| 956 |
+
of shape `(batch_size, sequence_length)`.
|
| 957 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 958 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 959 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 960 |
+
model's internal embedding lookup matrix.
|
| 961 |
+
use_cache (`bool`, *optional*):
|
| 962 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 963 |
+
`past_key_values`).
|
| 964 |
+
output_attentions (`bool`, *optional*):
|
| 965 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 966 |
+
tensors for more detail.
|
| 967 |
+
output_hidden_states (`bool`, *optional*):
|
| 968 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 969 |
+
more detail.
|
| 970 |
+
return_dict (`bool`, *optional*):
|
| 971 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 972 |
+
"""
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
@add_start_docstrings(
|
| 976 |
+
'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
|
| 977 |
+
MINICPM_START_DOCSTRING,
|
| 978 |
+
)
|
| 979 |
+
class MiniCPMModel(MiniCPMPreTrainedModel):
|
| 980 |
+
"""
|
| 981 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
|
| 982 |
+
|
| 983 |
+
Args:
|
| 984 |
+
config: MiniCPMConfig
|
| 985 |
+
"""
|
| 986 |
+
|
| 987 |
+
def __init__(self, config: MiniCPMConfig):
|
| 988 |
+
super().__init__(config)
|
| 989 |
+
self.padding_idx = config.pad_token_id
|
| 990 |
+
self.vocab_size = config.vocab_size
|
| 991 |
+
|
| 992 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 993 |
+
self.layers = nn.ModuleList(
|
| 994 |
+
[MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 995 |
+
)
|
| 996 |
+
self._use_sdpa = config._attn_implementation == 'sdpa'
|
| 997 |
+
self._use_flash_attention_2 = config._attn_implementation == 'flash_attention_2'
|
| 998 |
+
|
| 999 |
+
self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 1000 |
+
|
| 1001 |
+
self.gradient_checkpointing = False
|
| 1002 |
+
# Initialize weights and apply final processing
|
| 1003 |
+
self.post_init()
|
| 1004 |
+
|
| 1005 |
+
def get_input_embeddings(self):
|
| 1006 |
+
return self.embed_tokens
|
| 1007 |
+
|
| 1008 |
+
def set_input_embeddings(self, value):
|
| 1009 |
+
self.embed_tokens = value
|
| 1010 |
+
|
| 1011 |
+
@add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
|
| 1012 |
+
def forward(
|
| 1013 |
+
self,
|
| 1014 |
+
input_ids: torch.LongTensor = None,
|
| 1015 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1016 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1017 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1018 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1019 |
+
use_cache: Optional[bool] = None,
|
| 1020 |
+
output_attentions: Optional[bool] = None,
|
| 1021 |
+
output_hidden_states: Optional[bool] = None,
|
| 1022 |
+
return_dict: Optional[bool] = None,
|
| 1023 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 1024 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1025 |
+
output_hidden_states = (
|
| 1026 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1027 |
+
)
|
| 1028 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1029 |
+
|
| 1030 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1031 |
+
|
| 1032 |
+
# retrieve input_ids and inputs_embeds
|
| 1033 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1034 |
+
raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
|
| 1035 |
+
elif input_ids is not None:
|
| 1036 |
+
batch_size, seq_length = input_ids.shape[:2]
|
| 1037 |
+
elif inputs_embeds is not None:
|
| 1038 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
| 1039 |
+
else:
|
| 1040 |
+
raise ValueError('You have to specify either input_ids or inputs_embeds')
|
| 1041 |
+
|
| 1042 |
+
if self.gradient_checkpointing and self.training:
|
| 1043 |
+
if use_cache:
|
| 1044 |
+
logger.warning_once(
|
| 1045 |
+
'`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
|
| 1046 |
+
)
|
| 1047 |
+
use_cache = False
|
| 1048 |
+
|
| 1049 |
+
past_key_values_length = 0
|
| 1050 |
+
|
| 1051 |
+
if use_cache:
|
| 1052 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
| 1053 |
+
if use_legacy_cache:
|
| 1054 |
+
raise ValueError(
|
| 1055 |
+
'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
|
| 1056 |
+
)
|
| 1057 |
+
|
| 1058 |
+
# Calculate the usable length of past key values
|
| 1059 |
+
past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, Cache) else 0
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
if position_ids is None:
|
| 1063 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1064 |
+
position_ids = torch.arange(
|
| 1065 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 1066 |
+
)
|
| 1067 |
+
position_ids = position_ids.unsqueeze(0)
|
| 1068 |
+
|
| 1069 |
+
if inputs_embeds is None:
|
| 1070 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
|
| 1071 |
+
|
| 1072 |
+
if self._use_flash_attention_2:
|
| 1073 |
+
# 2d mask is passed through the layers
|
| 1074 |
+
# attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
| 1075 |
+
if attention_mask is None:
|
| 1076 |
+
raise ValueError(
|
| 1077 |
+
f'need attention_mask for flash attention, but got {attention_mask}.'
|
| 1078 |
+
)
|
| 1079 |
+
elif self._use_sdpa and not output_attentions:
|
| 1080 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
| 1081 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
| 1082 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
| 1083 |
+
attention_mask,
|
| 1084 |
+
(batch_size, seq_length),
|
| 1085 |
+
inputs_embeds,
|
| 1086 |
+
past_key_values_length,
|
| 1087 |
+
)
|
| 1088 |
+
else:
|
| 1089 |
+
# 4d mask is passed through the layers
|
| 1090 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
| 1091 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
# embed positions
|
| 1095 |
+
hidden_states = inputs_embeds
|
| 1096 |
+
|
| 1097 |
+
# decoder layers
|
| 1098 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1099 |
+
all_self_attns = () if output_attentions else None
|
| 1100 |
+
next_decoder_cache = None
|
| 1101 |
+
|
| 1102 |
+
for decoder_layer in self.layers:
|
| 1103 |
+
if output_hidden_states:
|
| 1104 |
+
all_hidden_states += (hidden_states,)
|
| 1105 |
+
|
| 1106 |
+
if self.gradient_checkpointing and self.training:
|
| 1107 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1108 |
+
decoder_layer.__call__,
|
| 1109 |
+
hidden_states,
|
| 1110 |
+
attention_mask,
|
| 1111 |
+
position_ids,
|
| 1112 |
+
past_key_values,
|
| 1113 |
+
output_attentions,
|
| 1114 |
+
use_cache,
|
| 1115 |
+
)
|
| 1116 |
+
else:
|
| 1117 |
+
layer_outputs = decoder_layer(
|
| 1118 |
+
hidden_states,
|
| 1119 |
+
attention_mask=attention_mask,
|
| 1120 |
+
position_ids=position_ids,
|
| 1121 |
+
past_key_value=past_key_values,
|
| 1122 |
+
output_attentions=output_attentions,
|
| 1123 |
+
use_cache=use_cache,
|
| 1124 |
+
)
|
| 1125 |
+
|
| 1126 |
+
hidden_states = layer_outputs[0]
|
| 1127 |
+
|
| 1128 |
+
if use_cache:
|
| 1129 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
| 1130 |
+
|
| 1131 |
+
if output_attentions:
|
| 1132 |
+
all_self_attns += (layer_outputs[1],)
|
| 1133 |
+
|
| 1134 |
+
hidden_states = self.norm(hidden_states)
|
| 1135 |
+
|
| 1136 |
+
# add hidden states from the last decoder layer
|
| 1137 |
+
if output_hidden_states:
|
| 1138 |
+
all_hidden_states += (hidden_states,)
|
| 1139 |
+
|
| 1140 |
+
next_cache = None
|
| 1141 |
+
if use_cache:
|
| 1142 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
| 1143 |
+
if not return_dict:
|
| 1144 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 1145 |
+
return BaseModelOutputWithPast(
|
| 1146 |
+
last_hidden_state=hidden_states,
|
| 1147 |
+
past_key_values=next_cache,
|
| 1148 |
+
hidden_states=all_hidden_states,
|
| 1149 |
+
attentions=all_self_attns,
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
+
class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
|
| 1154 |
+
_tied_weights_keys = ['lm_head.weight']
|
| 1155 |
+
|
| 1156 |
+
def __init__(self, config):
|
| 1157 |
+
super().__init__(config)
|
| 1158 |
+
self.model = MiniCPMModel(config)
|
| 1159 |
+
self.vocab_size = config.vocab_size
|
| 1160 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1161 |
+
|
| 1162 |
+
# Initialize weights and apply final processing
|
| 1163 |
+
self.post_init()
|
| 1164 |
+
|
| 1165 |
+
def get_input_embeddings(self):
|
| 1166 |
+
return self.model.embed_tokens
|
| 1167 |
+
|
| 1168 |
+
def set_input_embeddings(self, value):
|
| 1169 |
+
self.model.embed_tokens = value
|
| 1170 |
+
|
| 1171 |
+
def get_output_embeddings(self):
|
| 1172 |
+
return self.lm_head
|
| 1173 |
+
|
| 1174 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1175 |
+
self.lm_head = new_embeddings
|
| 1176 |
+
|
| 1177 |
+
def set_decoder(self, decoder):
|
| 1178 |
+
self.model = decoder
|
| 1179 |
+
|
| 1180 |
+
def get_decoder(self):
|
| 1181 |
+
return self.model
|
| 1182 |
+
|
| 1183 |
+
@add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
|
| 1184 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
| 1185 |
+
def forward(
|
| 1186 |
+
self,
|
| 1187 |
+
input_ids: torch.LongTensor = None,
|
| 1188 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1189 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1190 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1191 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1192 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1193 |
+
use_cache: Optional[bool] = None,
|
| 1194 |
+
output_attentions: Optional[bool] = None,
|
| 1195 |
+
output_hidden_states: Optional[bool] = None,
|
| 1196 |
+
return_dict: Optional[bool] = None,
|
| 1197 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 1198 |
+
**kwargs,
|
| 1199 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 1200 |
+
r"""
|
| 1201 |
+
Args:
|
| 1202 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1203 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1204 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1205 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1206 |
+
|
| 1207 |
+
Returns:
|
| 1208 |
+
|
| 1209 |
+
Example:
|
| 1210 |
+
|
| 1211 |
+
```python
|
| 1212 |
+
>>> from transformers import AutoTokenizer, MiniCPMForCausalLM
|
| 1213 |
+
|
| 1214 |
+
>>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
| 1215 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
| 1216 |
+
|
| 1217 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 1218 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1219 |
+
|
| 1220 |
+
>>> # Generate
|
| 1221 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1222 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1223 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1224 |
+
```"""
|
| 1225 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1226 |
+
output_hidden_states = (
|
| 1227 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1228 |
+
)
|
| 1229 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1230 |
+
|
| 1231 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1232 |
+
outputs = self.model(
|
| 1233 |
+
input_ids=input_ids,
|
| 1234 |
+
attention_mask=attention_mask,
|
| 1235 |
+
position_ids=position_ids,
|
| 1236 |
+
past_key_values=past_key_values,
|
| 1237 |
+
inputs_embeds=inputs_embeds,
|
| 1238 |
+
use_cache=use_cache,
|
| 1239 |
+
output_attentions=output_attentions,
|
| 1240 |
+
output_hidden_states=output_hidden_states,
|
| 1241 |
+
return_dict=return_dict,
|
| 1242 |
+
)
|
| 1243 |
+
|
| 1244 |
+
hidden_states = outputs[0]
|
| 1245 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1246 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1247 |
+
hidden_states = hidden_states[:, slice_indices, :].contiguous()
|
| 1248 |
+
if self.config.pretraining_tp > 1:
|
| 1249 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
| 1250 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 1251 |
+
logits = torch.cat(logits, dim=-1)
|
| 1252 |
+
else:
|
| 1253 |
+
logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
|
| 1254 |
+
logits = logits.float()
|
| 1255 |
+
|
| 1256 |
+
loss = None
|
| 1257 |
+
if labels is not None:
|
| 1258 |
+
# Shift so that tokens < n predict n
|
| 1259 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 1260 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 1261 |
+
# Flatten the tokens
|
| 1262 |
+
loss_fct = CrossEntropyLoss()
|
| 1263 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 1264 |
+
shift_labels = shift_labels.view(-1)
|
| 1265 |
+
# Enable model parallelism
|
| 1266 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 1267 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 1268 |
+
|
| 1269 |
+
if not return_dict:
|
| 1270 |
+
output = (logits,) + outputs[1:]
|
| 1271 |
+
return (loss,) + output if loss is not None else output
|
| 1272 |
+
|
| 1273 |
+
return CausalLMOutputWithPast(
|
| 1274 |
+
loss=loss,
|
| 1275 |
+
logits=logits,
|
| 1276 |
+
past_key_values=outputs.past_key_values,
|
| 1277 |
+
hidden_states=outputs.hidden_states,
|
| 1278 |
+
attentions=outputs.attentions,
|
| 1279 |
+
)
|
| 1280 |
+
|
| 1281 |
+
def prepare_inputs_for_generation(
|
| 1282 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 1283 |
+
):
|
| 1284 |
+
if past_key_values is not None:
|
| 1285 |
+
if isinstance(past_key_values, Cache):
|
| 1286 |
+
# Use the new Cache class methods
|
| 1287 |
+
cache_length = past_key_values.get_seq_length()
|
| 1288 |
+
|
| 1289 |
+
|
| 1290 |
+
past_length = cache_length
|
| 1291 |
+
max_cache_length = None
|
| 1292 |
+
else:
|
| 1293 |
+
raise ValueError(
|
| 1294 |
+
'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
|
| 1295 |
+
)
|
| 1296 |
+
|
| 1297 |
+
# Keep only the unprocessed tokens:
|
| 1298 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
| 1299 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
| 1300 |
+
# input)
|
| 1301 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
| 1302 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
|
| 1303 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
| 1304 |
+
# input_ids based on the past_length.
|
| 1305 |
+
elif past_length < input_ids.shape[1]:
|
| 1306 |
+
input_ids = input_ids[:, past_length:]
|
| 1307 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
| 1308 |
+
|
| 1309 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
| 1310 |
+
if (
|
| 1311 |
+
max_cache_length is not None
|
| 1312 |
+
and attention_mask is not None
|
| 1313 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
| 1314 |
+
):
|
| 1315 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
| 1316 |
+
|
| 1317 |
+
position_ids = kwargs.get('position_ids', None)
|
| 1318 |
+
if attention_mask is not None and position_ids is None:
|
| 1319 |
+
# create position_ids on the fly for batch generation
|
| 1320 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1321 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 1322 |
+
if past_key_values:
|
| 1323 |
+
position_ids = position_ids[:, -input_ids.shape[1]:]
|
| 1324 |
+
|
| 1325 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 1326 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 1327 |
+
model_inputs = {'inputs_embeds': inputs_embeds}
|
| 1328 |
+
else:
|
| 1329 |
+
model_inputs = {'input_ids': input_ids}
|
| 1330 |
+
|
| 1331 |
+
model_inputs.update(
|
| 1332 |
+
{
|
| 1333 |
+
'position_ids': position_ids,
|
| 1334 |
+
'past_key_values': past_key_values,
|
| 1335 |
+
'use_cache': kwargs.get('use_cache'),
|
| 1336 |
+
'attention_mask': attention_mask,
|
| 1337 |
+
}
|
| 1338 |
+
)
|
| 1339 |
+
# Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
|
| 1340 |
+
for key, value in kwargs.items():
|
| 1341 |
+
if key not in model_inputs:
|
| 1342 |
+
model_inputs[key] = value
|
| 1343 |
+
return model_inputs
|
| 1344 |
+
|
| 1345 |
+
@staticmethod
|
| 1346 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 1347 |
+
reordered_past = ()
|
| 1348 |
+
for layer_past in past_key_values:
|
| 1349 |
+
reordered_past += (
|
| 1350 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1351 |
+
)
|
| 1352 |
+
return reordered_past
|
| 1353 |
+
|
| 1354 |
+
@torch.inference_mode()
|
| 1355 |
+
def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = 'user',
|
| 1356 |
+
max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
|
| 1357 |
+
**kwargs):
|
| 1358 |
+
if history is None:
|
| 1359 |
+
history = []
|
| 1360 |
+
if logits_processor:
|
| 1361 |
+
gen_kwargs = {
|
| 1362 |
+
'max_length': max_length,
|
| 1363 |
+
'num_beams': num_beams,
|
| 1364 |
+
'do_sample': do_sample,
|
| 1365 |
+
'top_p': top_p,
|
| 1366 |
+
'temperature': temperature,
|
| 1367 |
+
'logits_processor': logits_processor,
|
| 1368 |
+
**kwargs
|
| 1369 |
+
}
|
| 1370 |
+
else:
|
| 1371 |
+
gen_kwargs = {
|
| 1372 |
+
'max_length': max_length,
|
| 1373 |
+
'num_beams': num_beams,
|
| 1374 |
+
'do_sample': do_sample,
|
| 1375 |
+
'top_p': top_p,
|
| 1376 |
+
'temperature': temperature,
|
| 1377 |
+
'logits_processor': logits_processor,
|
| 1378 |
+
**kwargs
|
| 1379 |
+
}
|
| 1380 |
+
|
| 1381 |
+
history.append({'role': role, 'content': query})
|
| 1382 |
+
history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
|
| 1383 |
+
inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
|
| 1384 |
+
outputs = self.generate(**inputs, **gen_kwargs)
|
| 1385 |
+
outputs = outputs.tolist()[0][len(inputs['input_ids'][0]):-1]
|
| 1386 |
+
response = tokenizer.decode(outputs)
|
| 1387 |
+
pattern = re.compile(r'.*?(?=<AI>|<用户>)', re.DOTALL)
|
| 1388 |
+
matches = pattern.findall(response)
|
| 1389 |
+
if len(matches) > 0:
|
| 1390 |
+
response = matches[0]
|
| 1391 |
+
history.append({'role': 'assistant', 'content': response})
|
| 1392 |
+
return response, history
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
@add_start_docstrings(
|
| 1396 |
+
"""
|
| 1397 |
+
The MiniCPM Model transformer with a sequence classification head on top (linear layer).
|
| 1398 |
+
|
| 1399 |
+
[`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 1400 |
+
(e.g. GPT-2) do.
|
| 1401 |
+
|
| 1402 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 1403 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 1404 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 1405 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 1406 |
+
each row of the batch).
|
| 1407 |
+
""",
|
| 1408 |
+
MINICPM_START_DOCSTRING,
|
| 1409 |
+
)
|
| 1410 |
+
class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
|
| 1411 |
+
def __init__(self, config):
|
| 1412 |
+
super().__init__(config)
|
| 1413 |
+
self.num_labels = config.num_labels
|
| 1414 |
+
self.model = MiniCPMModel(config)
|
| 1415 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 1416 |
+
|
| 1417 |
+
# Initialize weights and apply final processing
|
| 1418 |
+
self.post_init()
|
| 1419 |
+
|
| 1420 |
+
def get_input_embeddings(self):
|
| 1421 |
+
return self.model.embed_tokens
|
| 1422 |
+
|
| 1423 |
+
def set_input_embeddings(self, value):
|
| 1424 |
+
self.model.embed_tokens = value
|
| 1425 |
+
|
| 1426 |
+
@add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
|
| 1427 |
+
def forward(
|
| 1428 |
+
self,
|
| 1429 |
+
input_ids: torch.LongTensor = None,
|
| 1430 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1431 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1432 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1433 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1434 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1435 |
+
use_cache: Optional[bool] = None,
|
| 1436 |
+
output_attentions: Optional[bool] = None,
|
| 1437 |
+
output_hidden_states: Optional[bool] = None,
|
| 1438 |
+
return_dict: Optional[bool] = None,
|
| 1439 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1440 |
+
r"""
|
| 1441 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1442 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1443 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1444 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1445 |
+
"""
|
| 1446 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1447 |
+
|
| 1448 |
+
transformer_outputs = self.model(
|
| 1449 |
+
input_ids,
|
| 1450 |
+
attention_mask=attention_mask,
|
| 1451 |
+
position_ids=position_ids,
|
| 1452 |
+
past_key_values=past_key_values,
|
| 1453 |
+
inputs_embeds=inputs_embeds,
|
| 1454 |
+
use_cache=use_cache,
|
| 1455 |
+
output_attentions=output_attentions,
|
| 1456 |
+
output_hidden_states=output_hidden_states,
|
| 1457 |
+
return_dict=return_dict,
|
| 1458 |
+
)
|
| 1459 |
+
hidden_states = transformer_outputs[0]
|
| 1460 |
+
logits = self.score(hidden_states)
|
| 1461 |
+
|
| 1462 |
+
if input_ids is not None:
|
| 1463 |
+
batch_size = input_ids.shape[0]
|
| 1464 |
+
else:
|
| 1465 |
+
batch_size = inputs_embeds.shape[0]
|
| 1466 |
+
|
| 1467 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1468 |
+
raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
|
| 1469 |
+
if self.config.pad_token_id is None:
|
| 1470 |
+
sequence_lengths = -1
|
| 1471 |
+
else:
|
| 1472 |
+
if input_ids is not None:
|
| 1473 |
+
sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
|
| 1474 |
+
logits.device
|
| 1475 |
+
)
|
| 1476 |
+
else:
|
| 1477 |
+
sequence_lengths = -1
|
| 1478 |
+
|
| 1479 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1480 |
+
|
| 1481 |
+
loss = None
|
| 1482 |
+
if labels is not None:
|
| 1483 |
+
labels = labels.to(logits.device)
|
| 1484 |
+
if self.config.problem_type is None:
|
| 1485 |
+
if self.num_labels == 1:
|
| 1486 |
+
self.config.problem_type = 'regression'
|
| 1487 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1488 |
+
self.config.problem_type = 'single_label_classification'
|
| 1489 |
+
else:
|
| 1490 |
+
self.config.problem_type = 'multi_label_classification'
|
| 1491 |
+
|
| 1492 |
+
if self.config.problem_type == 'regression':
|
| 1493 |
+
loss_fct = MSELoss()
|
| 1494 |
+
if self.num_labels == 1:
|
| 1495 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1496 |
+
else:
|
| 1497 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1498 |
+
elif self.config.problem_type == 'single_label_classification':
|
| 1499 |
+
loss_fct = CrossEntropyLoss()
|
| 1500 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 1501 |
+
elif self.config.problem_type == 'multi_label_classification':
|
| 1502 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1503 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1504 |
+
if not return_dict:
|
| 1505 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1506 |
+
return ((loss,) + output) if loss is not None else output
|
| 1507 |
+
|
| 1508 |
+
return SequenceClassifierOutputWithPast(
|
| 1509 |
+
loss=loss,
|
| 1510 |
+
logits=pooled_logits,
|
| 1511 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1512 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1513 |
+
attentions=transformer_outputs.attentions,
|
| 1514 |
+
)
|
modeling_robottrack.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face model implementation for MiniCPM-RobotTrack."""
|
| 2 |
+
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import List, Optional, Tuple, Union
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import nn
|
| 9 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 10 |
+
from transformers.utils import ModelOutput
|
| 11 |
+
|
| 12 |
+
from .configuration_minicpm import MiniCPMConfig
|
| 13 |
+
from .configuration_robottrack import MiniCPMRobotTrackConfig
|
| 14 |
+
from .modeling_minicpm import MiniCPMModel
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@contextmanager
|
| 18 |
+
def _default_dtype(dtype: torch.dtype):
|
| 19 |
+
previous = torch.get_default_dtype()
|
| 20 |
+
torch.set_default_dtype(dtype)
|
| 21 |
+
try:
|
| 22 |
+
yield
|
| 23 |
+
finally:
|
| 24 |
+
torch.set_default_dtype(previous)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _dtype_from_name(name: str) -> torch.dtype:
|
| 28 |
+
try:
|
| 29 |
+
dtype = getattr(torch, name)
|
| 30 |
+
except AttributeError as exc:
|
| 31 |
+
raise ValueError(f"unsupported backbone_dtype={name!r}") from exc
|
| 32 |
+
if not isinstance(dtype, torch.dtype) or not dtype.is_floating_point:
|
| 33 |
+
raise ValueError(f"backbone_dtype must name a floating-point torch dtype: {name!r}")
|
| 34 |
+
return dtype
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _module_dtype(module: nn.Module) -> torch.dtype:
|
| 38 |
+
try:
|
| 39 |
+
return next(module.parameters()).dtype
|
| 40 |
+
except StopIteration:
|
| 41 |
+
return torch.float32
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class VisionProjector(nn.Module):
|
| 45 |
+
"""Map concatenated DINOv3 and SigLIP features into MiniCPM space."""
|
| 46 |
+
|
| 47 |
+
def __init__(self, input_dim: int, hidden_dim: int) -> None:
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.layers = nn.Sequential(
|
| 50 |
+
nn.LayerNorm(input_dim),
|
| 51 |
+
nn.Linear(input_dim, hidden_dim),
|
| 52 |
+
nn.GELU(),
|
| 53 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
| 57 |
+
return self.layers(features)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TemporalMarkerEncoder(nn.Module):
|
| 61 |
+
"""Build one marker token for each frame represented in the sequence."""
|
| 62 |
+
|
| 63 |
+
def __init__(self, hidden_dim: int, max_time_steps: int) -> None:
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.time_embedding = nn.Embedding(max_time_steps, hidden_dim)
|
| 66 |
+
self.stream_embedding = nn.Embedding(2, hidden_dim)
|
| 67 |
+
self.camera_embedding = nn.Embedding(1, hidden_dim)
|
| 68 |
+
|
| 69 |
+
def forward(self, time_step: int, stream_id: int, device: torch.device) -> torch.Tensor:
|
| 70 |
+
time = torch.tensor([time_step], dtype=torch.long, device=device)
|
| 71 |
+
stream = torch.tensor([stream_id], dtype=torch.long, device=device)
|
| 72 |
+
camera = torch.zeros(1, dtype=torch.long, device=device)
|
| 73 |
+
return (
|
| 74 |
+
self.time_embedding(time)
|
| 75 |
+
+ self.stream_embedding(stream)
|
| 76 |
+
+ self.camera_embedding(camera)
|
| 77 |
+
).squeeze(0)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class FunnelTrajectoryHead(nn.Module):
|
| 81 |
+
"""Six-layer funnel MLP that predicts a fixed waypoint trajectory."""
|
| 82 |
+
|
| 83 |
+
def __init__(
|
| 84 |
+
self,
|
| 85 |
+
hidden_dim: int,
|
| 86 |
+
num_waypoints: int,
|
| 87 |
+
action_dim: int,
|
| 88 |
+
dropout: float,
|
| 89 |
+
use_tanh: bool,
|
| 90 |
+
) -> None:
|
| 91 |
+
super().__init__()
|
| 92 |
+
output_dim = num_waypoints * action_dim
|
| 93 |
+
self.num_waypoints = num_waypoints
|
| 94 |
+
self.action_dim = action_dim
|
| 95 |
+
self.use_tanh = use_tanh
|
| 96 |
+
self.layers = nn.Sequential(
|
| 97 |
+
nn.LayerNorm(hidden_dim),
|
| 98 |
+
nn.Linear(hidden_dim, 4096),
|
| 99 |
+
nn.GELU(),
|
| 100 |
+
nn.Dropout(dropout),
|
| 101 |
+
nn.Linear(4096, 1024),
|
| 102 |
+
nn.GELU(),
|
| 103 |
+
nn.Dropout(dropout),
|
| 104 |
+
nn.Linear(1024, 512),
|
| 105 |
+
nn.GELU(),
|
| 106 |
+
nn.Dropout(dropout),
|
| 107 |
+
nn.Linear(512, 256),
|
| 108 |
+
nn.GELU(),
|
| 109 |
+
nn.Dropout(dropout),
|
| 110 |
+
nn.Linear(256, 128),
|
| 111 |
+
nn.GELU(),
|
| 112 |
+
nn.Dropout(dropout),
|
| 113 |
+
nn.LayerNorm(128),
|
| 114 |
+
nn.Linear(128, output_dim),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def forward(self, control_state: torch.Tensor) -> torch.Tensor:
|
| 118 |
+
trajectory = self.layers(control_state)
|
| 119 |
+
if self.use_tanh:
|
| 120 |
+
trajectory = torch.tanh(trajectory)
|
| 121 |
+
return trajectory.view(-1, self.num_waypoints, self.action_dim)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@dataclass
|
| 125 |
+
class MiniCPMRobotTrackOutput(ModelOutput):
|
| 126 |
+
"""Output of MiniCPM-RobotTrack."""
|
| 127 |
+
|
| 128 |
+
loss: Optional[torch.FloatTensor] = None
|
| 129 |
+
trajectories: Optional[torch.FloatTensor] = None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class MiniCPMRobotTrackModel(PreTrainedModel):
|
| 133 |
+
"""MiniCPM visual tracking policy with a funnel trajectory head."""
|
| 134 |
+
|
| 135 |
+
config_class = MiniCPMRobotTrackConfig
|
| 136 |
+
base_model_prefix = "backbone"
|
| 137 |
+
main_input_name = "input_ids"
|
| 138 |
+
supports_gradient_checkpointing = True
|
| 139 |
+
_supports_sdpa = True
|
| 140 |
+
_supports_flash_attn_2 = True
|
| 141 |
+
_no_split_modules = ["MiniCPMDecoderLayer"]
|
| 142 |
+
|
| 143 |
+
def __init__(self, config: MiniCPMRobotTrackConfig) -> None:
|
| 144 |
+
super().__init__(config)
|
| 145 |
+
|
| 146 |
+
backbone_config = MiniCPMConfig(**config.backbone_config)
|
| 147 |
+
attention_implementation = getattr(config, "_attn_implementation", None)
|
| 148 |
+
if attention_implementation is not None:
|
| 149 |
+
backbone_config._attn_implementation = attention_implementation
|
| 150 |
+
backbone_config.use_cache = False
|
| 151 |
+
|
| 152 |
+
backbone_dtype = _dtype_from_name(config.backbone_dtype)
|
| 153 |
+
with _default_dtype(backbone_dtype):
|
| 154 |
+
self.backbone = MiniCPMModel(backbone_config)
|
| 155 |
+
|
| 156 |
+
hidden_dim = int(backbone_config.hidden_size)
|
| 157 |
+
self.vision_projector = VisionProjector(config.vision_feature_dim, hidden_dim)
|
| 158 |
+
self.temporal_markers = TemporalMarkerEncoder(hidden_dim, config.max_time_steps)
|
| 159 |
+
self.control_query = nn.Parameter(torch.empty(1, 1, hidden_dim))
|
| 160 |
+
nn.init.normal_(self.control_query, mean=0.0, std=0.02)
|
| 161 |
+
self.trajectory_head = FunnelTrajectoryHead(
|
| 162 |
+
hidden_dim=hidden_dim,
|
| 163 |
+
num_waypoints=config.num_waypoints,
|
| 164 |
+
action_dim=config.action_dim,
|
| 165 |
+
dropout=config.trajectory_dropout,
|
| 166 |
+
use_tanh=config.use_tanh_actions,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
output_scale = torch.ones(1, 1, config.action_dim, dtype=torch.float32)
|
| 170 |
+
output_scale[..., :2] = config.xy_scale
|
| 171 |
+
self.register_buffer("output_scale", output_scale)
|
| 172 |
+
|
| 173 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 174 |
+
return self.backbone.get_input_embeddings()
|
| 175 |
+
|
| 176 |
+
def set_input_embeddings(self, value: nn.Module) -> None:
|
| 177 |
+
self.backbone.set_input_embeddings(value)
|
| 178 |
+
|
| 179 |
+
def _insert_temporal_markers(
|
| 180 |
+
self,
|
| 181 |
+
tokens: torch.Tensor,
|
| 182 |
+
time_indices: torch.Tensor,
|
| 183 |
+
stream_id: int,
|
| 184 |
+
) -> torch.Tensor:
|
| 185 |
+
if tokens.ndim != 3 or time_indices.ndim != 2:
|
| 186 |
+
raise ValueError("visual tokens and time indices must have shapes [B, N, C] and [B, N]")
|
| 187 |
+
if tokens.shape[:2] != time_indices.shape:
|
| 188 |
+
raise ValueError("visual token and time-index shapes do not match")
|
| 189 |
+
if tokens.size(1) == 0:
|
| 190 |
+
return tokens
|
| 191 |
+
|
| 192 |
+
packed_rows: List[torch.Tensor] = []
|
| 193 |
+
time_rows = time_indices.detach().to("cpu").tolist()
|
| 194 |
+
for batch_index, time_row in enumerate(time_rows):
|
| 195 |
+
pieces: List[torch.Tensor] = []
|
| 196 |
+
start = 0
|
| 197 |
+
while start < len(time_row):
|
| 198 |
+
time_step = int(time_row[start])
|
| 199 |
+
if not 0 <= time_step < self.config.max_time_steps:
|
| 200 |
+
raise ValueError(f"time index {time_step} is outside the configured range")
|
| 201 |
+
end = start + 1
|
| 202 |
+
while end < len(time_row) and int(time_row[end]) == time_step:
|
| 203 |
+
end += 1
|
| 204 |
+
marker = self.temporal_markers(time_step, stream_id, tokens.device)
|
| 205 |
+
pieces.extend((marker.unsqueeze(0), tokens[batch_index, start:end]))
|
| 206 |
+
start = end
|
| 207 |
+
packed_rows.append(torch.cat(pieces, dim=0))
|
| 208 |
+
|
| 209 |
+
packed_lengths = {row.size(0) for row in packed_rows}
|
| 210 |
+
if len(packed_lengths) != 1:
|
| 211 |
+
raise ValueError("each batch item must contain the same number of represented frames")
|
| 212 |
+
return torch.stack(packed_rows, dim=0)
|
| 213 |
+
|
| 214 |
+
def _build_sequence(
|
| 215 |
+
self,
|
| 216 |
+
input_ids: torch.LongTensor,
|
| 217 |
+
attention_mask: Optional[torch.Tensor],
|
| 218 |
+
coarse_tokens: torch.Tensor,
|
| 219 |
+
coarse_time_indices: torch.Tensor,
|
| 220 |
+
fine_tokens: torch.Tensor,
|
| 221 |
+
fine_time_indices: torch.Tensor,
|
| 222 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 223 |
+
device = self.control_query.device
|
| 224 |
+
input_ids = input_ids.to(device)
|
| 225 |
+
if attention_mask is None:
|
| 226 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.long)
|
| 227 |
+
else:
|
| 228 |
+
attention_mask = attention_mask.to(device)
|
| 229 |
+
|
| 230 |
+
batch_size = coarse_tokens.size(0)
|
| 231 |
+
if fine_tokens.size(0) != batch_size or input_ids.size(0) != batch_size:
|
| 232 |
+
raise ValueError("batch dimensions do not match")
|
| 233 |
+
|
| 234 |
+
projector_dtype = _module_dtype(self.vision_projector)
|
| 235 |
+
history = self.vision_projector(coarse_tokens.to(device=device, dtype=projector_dtype))
|
| 236 |
+
current = self.vision_projector(fine_tokens.to(device=device, dtype=projector_dtype))
|
| 237 |
+
history = self._insert_temporal_markers(
|
| 238 |
+
history, coarse_time_indices.to(device), stream_id=0
|
| 239 |
+
)
|
| 240 |
+
current = self._insert_temporal_markers(
|
| 241 |
+
current, fine_time_indices.to(device), stream_id=1
|
| 242 |
+
)
|
| 243 |
+
text = self.backbone.get_input_embeddings()(input_ids)
|
| 244 |
+
|
| 245 |
+
control_query = self.control_query.expand(batch_size, -1, -1)
|
| 246 |
+
sequence = torch.cat((text, history, current, control_query), dim=1)
|
| 247 |
+
sequence = sequence.to(dtype=_module_dtype(self.backbone))
|
| 248 |
+
|
| 249 |
+
full_attention_mask = torch.cat(
|
| 250 |
+
(
|
| 251 |
+
attention_mask,
|
| 252 |
+
torch.ones(batch_size, history.size(1), dtype=torch.long, device=device),
|
| 253 |
+
torch.ones(batch_size, current.size(1), dtype=torch.long, device=device),
|
| 254 |
+
torch.ones(batch_size, 1, dtype=torch.long, device=device),
|
| 255 |
+
),
|
| 256 |
+
dim=1,
|
| 257 |
+
)
|
| 258 |
+
return sequence, full_attention_mask
|
| 259 |
+
|
| 260 |
+
def normalize_trajectory(self, trajectory: torch.Tensor) -> torch.Tensor:
|
| 261 |
+
return trajectory / self.output_scale.to(device=trajectory.device, dtype=trajectory.dtype)
|
| 262 |
+
|
| 263 |
+
def forward(
|
| 264 |
+
self,
|
| 265 |
+
input_ids: torch.LongTensor,
|
| 266 |
+
coarse_tokens: torch.Tensor,
|
| 267 |
+
coarse_time_indices: torch.Tensor,
|
| 268 |
+
fine_tokens: torch.Tensor,
|
| 269 |
+
fine_time_indices: torch.Tensor,
|
| 270 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 271 |
+
labels: Optional[torch.Tensor] = None,
|
| 272 |
+
valid_mask: Optional[torch.Tensor] = None,
|
| 273 |
+
return_dict: Optional[bool] = None,
|
| 274 |
+
) -> Union[MiniCPMRobotTrackOutput, Tuple[torch.Tensor, ...]]:
|
| 275 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 276 |
+
sequence, full_attention_mask = self._build_sequence(
|
| 277 |
+
input_ids=input_ids,
|
| 278 |
+
attention_mask=attention_mask,
|
| 279 |
+
coarse_tokens=coarse_tokens,
|
| 280 |
+
coarse_time_indices=coarse_time_indices,
|
| 281 |
+
fine_tokens=fine_tokens,
|
| 282 |
+
fine_time_indices=fine_time_indices,
|
| 283 |
+
)
|
| 284 |
+
output = self.backbone(
|
| 285 |
+
inputs_embeds=sequence,
|
| 286 |
+
attention_mask=full_attention_mask,
|
| 287 |
+
use_cache=False,
|
| 288 |
+
return_dict=True,
|
| 289 |
+
)
|
| 290 |
+
control_state = output.last_hidden_state[:, -1].to(
|
| 291 |
+
dtype=_module_dtype(self.trajectory_head)
|
| 292 |
+
)
|
| 293 |
+
normalized_trajectory = self.trajectory_head(control_state)
|
| 294 |
+
trajectories = normalized_trajectory * self.output_scale.to(
|
| 295 |
+
normalized_trajectory.dtype
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
loss = None
|
| 299 |
+
if labels is not None:
|
| 300 |
+
labels = labels.to(device=trajectories.device, dtype=trajectories.dtype)
|
| 301 |
+
if labels.shape != trajectories.shape:
|
| 302 |
+
raise ValueError("labels and predicted trajectories must have identical shapes")
|
| 303 |
+
normalized_labels = self.normalize_trajectory(labels)
|
| 304 |
+
squared_error = (normalized_trajectory - normalized_labels).square()
|
| 305 |
+
if valid_mask is None:
|
| 306 |
+
loss = squared_error.mean()
|
| 307 |
+
else:
|
| 308 |
+
mask = valid_mask.to(
|
| 309 |
+
device=trajectories.device, dtype=trajectories.dtype
|
| 310 |
+
).unsqueeze(-1)
|
| 311 |
+
denominator = mask.sum() * trajectories.size(-1)
|
| 312 |
+
loss = (
|
| 313 |
+
squared_error.mul(mask).sum() / denominator
|
| 314 |
+
if denominator.item() > 0
|
| 315 |
+
else trajectories.sum() * 0.0
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
if not return_dict:
|
| 319 |
+
return (trajectories,) if loss is None else (loss, trajectories)
|
| 320 |
+
return MiniCPMRobotTrackOutput(loss=loss, trajectories=trajectories)
|
| 321 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.1
|
| 2 |
+
transformers>=4.56,<5
|
| 3 |
+
safetensors>=0.4
|
| 4 |
+
sentencepiece>=0.1.99
|
| 5 |
+
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|im_end|>",
|
| 4 |
+
"<|im_start|>",
|
| 5 |
+
"<|tool_call|>",
|
| 6 |
+
"<|execute_start|>",
|
| 7 |
+
"<|execute_end|>",
|
| 8 |
+
"<|fim_prefix|>",
|
| 9 |
+
"<|fim_middle|>",
|
| 10 |
+
"<|fim_suffix|>"
|
| 11 |
+
],
|
| 12 |
+
"bos_token": {
|
| 13 |
+
"content": "<s>",
|
| 14 |
+
"lstrip": false,
|
| 15 |
+
"normalized": false,
|
| 16 |
+
"rstrip": false,
|
| 17 |
+
"single_word": false
|
| 18 |
+
},
|
| 19 |
+
"eos_token": {
|
| 20 |
+
"content": "<|im_end|>",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false
|
| 25 |
+
},
|
| 26 |
+
"unk_token": {
|
| 27 |
+
"content": "<unk>",
|
| 28 |
+
"lstrip": false,
|
| 29 |
+
"normalized": false,
|
| 30 |
+
"rstrip": false,
|
| 31 |
+
"single_word": false
|
| 32 |
+
},
|
| 33 |
+
"pad_token": {
|
| 34 |
+
"content": "<|im_end|>",
|
| 35 |
+
"lstrip": false,
|
| 36 |
+
"normalized": false,
|
| 37 |
+
"rstrip": false,
|
| 38 |
+
"single_word": false
|
| 39 |
+
}
|
| 40 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bb74d51116831c3bf65db812c553f94ab0c88dcf97a5bbb37e3504f6d359c530
|
| 3 |
+
size 1181204
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": true,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"add_prefix_space": null,
|
| 5 |
+
"added_tokens_decoder": {
|
| 6 |
+
"0": {
|
| 7 |
+
"content": "<unk>",
|
| 8 |
+
"lstrip": false,
|
| 9 |
+
"normalized": false,
|
| 10 |
+
"rstrip": false,
|
| 11 |
+
"single_word": false,
|
| 12 |
+
"special": true
|
| 13 |
+
},
|
| 14 |
+
"1": {
|
| 15 |
+
"content": "<s>",
|
| 16 |
+
"lstrip": false,
|
| 17 |
+
"normalized": false,
|
| 18 |
+
"rstrip": false,
|
| 19 |
+
"single_word": false,
|
| 20 |
+
"special": true
|
| 21 |
+
},
|
| 22 |
+
"2": {
|
| 23 |
+
"content": "</s>",
|
| 24 |
+
"lstrip": false,
|
| 25 |
+
"normalized": false,
|
| 26 |
+
"rstrip": false,
|
| 27 |
+
"single_word": false,
|
| 28 |
+
"special": true
|
| 29 |
+
},
|
| 30 |
+
"73440": {
|
| 31 |
+
"content": "<|im_end|>",
|
| 32 |
+
"lstrip": false,
|
| 33 |
+
"normalized": false,
|
| 34 |
+
"rstrip": false,
|
| 35 |
+
"single_word": false,
|
| 36 |
+
"special": true
|
| 37 |
+
},
|
| 38 |
+
"73441": {
|
| 39 |
+
"content": "<|im_start|>",
|
| 40 |
+
"lstrip": false,
|
| 41 |
+
"normalized": false,
|
| 42 |
+
"rstrip": false,
|
| 43 |
+
"single_word": false,
|
| 44 |
+
"special": true
|
| 45 |
+
},
|
| 46 |
+
"73442": {
|
| 47 |
+
"content": "<|tool_call|>",
|
| 48 |
+
"lstrip": false,
|
| 49 |
+
"normalized": false,
|
| 50 |
+
"rstrip": false,
|
| 51 |
+
"single_word": false,
|
| 52 |
+
"special": true
|
| 53 |
+
},
|
| 54 |
+
"73443": {
|
| 55 |
+
"content": "<|execute_start|>",
|
| 56 |
+
"lstrip": false,
|
| 57 |
+
"normalized": false,
|
| 58 |
+
"rstrip": false,
|
| 59 |
+
"single_word": false,
|
| 60 |
+
"special": true
|
| 61 |
+
},
|
| 62 |
+
"73444": {
|
| 63 |
+
"content": "<|execute_end|>",
|
| 64 |
+
"lstrip": false,
|
| 65 |
+
"normalized": false,
|
| 66 |
+
"rstrip": false,
|
| 67 |
+
"single_word": false,
|
| 68 |
+
"special": true
|
| 69 |
+
},
|
| 70 |
+
"73445": {
|
| 71 |
+
"content": "<|fim_prefix|>",
|
| 72 |
+
"lstrip": false,
|
| 73 |
+
"normalized": false,
|
| 74 |
+
"rstrip": false,
|
| 75 |
+
"single_word": false,
|
| 76 |
+
"special": true
|
| 77 |
+
},
|
| 78 |
+
"73446": {
|
| 79 |
+
"content": "<|fim_middle|>",
|
| 80 |
+
"lstrip": false,
|
| 81 |
+
"normalized": false,
|
| 82 |
+
"rstrip": false,
|
| 83 |
+
"single_word": false,
|
| 84 |
+
"special": true
|
| 85 |
+
},
|
| 86 |
+
"73447": {
|
| 87 |
+
"content": "<|fim_suffix|>",
|
| 88 |
+
"lstrip": false,
|
| 89 |
+
"normalized": false,
|
| 90 |
+
"rstrip": false,
|
| 91 |
+
"single_word": false,
|
| 92 |
+
"special": true
|
| 93 |
+
}
|
| 94 |
+
},
|
| 95 |
+
"additional_special_tokens": [
|
| 96 |
+
"<|im_end|>",
|
| 97 |
+
"<|im_start|>",
|
| 98 |
+
"<|tool_call|>",
|
| 99 |
+
"<|execute_start|>",
|
| 100 |
+
"<|execute_end|>",
|
| 101 |
+
"<|fim_prefix|>",
|
| 102 |
+
"<|fim_middle|>",
|
| 103 |
+
"<|fim_suffix|>"
|
| 104 |
+
],
|
| 105 |
+
"bos_token": "<s>",
|
| 106 |
+
"chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
|
| 107 |
+
"clean_up_tokenization_spaces": false,
|
| 108 |
+
"eos_token": "<|im_end|>",
|
| 109 |
+
"legacy": true,
|
| 110 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 111 |
+
"pad_token": "<|im_end|>",
|
| 112 |
+
"sp_model_kwargs": {},
|
| 113 |
+
"spaces_between_special_tokens": false,
|
| 114 |
+
"tokenizer_class": "LlamaTokenizer",
|
| 115 |
+
"unk_token": "<unk>",
|
| 116 |
+
"use_default_system_prompt": false
|
| 117 |
+
}
|