yujiepan commited on
Commit
beda442
·
verified ·
1 Parent(s): 1451645

Upload folder using huggingface_hub

Browse files
.meta/create_model.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def create_model(source_model_id: str, source_revision: str, save_folder: str) -> str:
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import torch
6
+ from huggingface_hub import hf_hub_download
7
+ from transformers import AutoConfig, AutoModel, set_seed
8
+
9
+ folder = Path(save_folder)
10
+ folder.mkdir(parents=True, exist_ok=True)
11
+ for name in (
12
+ "configuration_minicpm.py",
13
+ "configuration_robottrack.py",
14
+ "modeling_minicpm.py",
15
+ "modeling_robottrack.py",
16
+ "added_tokens.json",
17
+ "special_tokens_map.json",
18
+ "tokenizer.json",
19
+ "tokenizer.model",
20
+ "tokenizer_config.json",
21
+ "LICENSE",
22
+ "LICENSE_MINICPM",
23
+ "LICENSE_MIT",
24
+ "THIRD_PARTY_NOTICES.md",
25
+ ):
26
+ (folder / name).write_bytes(Path(hf_hub_download(source_model_id, name, revision=source_revision)).read_bytes())
27
+
28
+ config = json.loads(Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text())
29
+ backbone = config["backbone_config"]
30
+ backbone.update(
31
+ hidden_size=32,
32
+ intermediate_size=64,
33
+ num_attention_heads=1,
34
+ num_key_value_heads=1,
35
+ num_hidden_layers=4,
36
+ max_position_embeddings=128,
37
+ dim_model_base=32,
38
+ )
39
+ for name in ("short_factor", "long_factor"):
40
+ backbone["rope_scaling"][name] = backbone["rope_scaling"][name][:16]
41
+ backbone["rope_scaling"]["original_max_position_embeddings"] = 128
42
+ config["max_time_steps"] = 128
43
+ (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n")
44
+
45
+ backbone_source = (folder / "modeling_minicpm.py").read_text()
46
+ old_import = "from transformers.utils.import_utils import is_torch_fx_available"
47
+ replacement = "try:\n from transformers.utils.import_utils import is_torch_fx_available\nexcept ImportError:\n def is_torch_fx_available():\n return False"
48
+ if old_import not in backbone_source:
49
+ raise ValueError("Expected RobotTrack Transformers compatibility import is missing")
50
+ (folder / "modeling_minicpm.py").write_text(backbone_source.replace(old_import, replacement))
51
+
52
+ track_source = (folder / "modeling_robottrack.py").read_text()
53
+ old_funnel = """ self.layers = nn.Sequential(
54
+ nn.LayerNorm(hidden_dim),
55
+ nn.Linear(hidden_dim, 4096),
56
+ nn.GELU(),
57
+ nn.Dropout(dropout),
58
+ nn.Linear(4096, 1024),
59
+ nn.GELU(),
60
+ nn.Dropout(dropout),
61
+ nn.Linear(1024, 512),
62
+ nn.GELU(),
63
+ nn.Dropout(dropout),
64
+ nn.Linear(512, 256),
65
+ nn.GELU(),
66
+ nn.Dropout(dropout),
67
+ nn.Linear(256, 128),
68
+ nn.GELU(),
69
+ nn.Dropout(dropout),
70
+ nn.LayerNorm(128),
71
+ nn.Linear(128, output_dim),
72
+ )"""
73
+ new_funnel = """ widths = (max(hidden_dim * 4, 32), max(hidden_dim * 2, 32), hidden_dim, hidden_dim, hidden_dim)
74
+ blocks = [nn.LayerNorm(hidden_dim)]
75
+ previous = hidden_dim
76
+ for width in widths:
77
+ blocks.extend((nn.Linear(previous, width), nn.GELU(), nn.Dropout(dropout)))
78
+ previous = width
79
+ blocks.extend((nn.LayerNorm(previous), nn.Linear(previous, output_dim)))
80
+ self.layers = nn.Sequential(*blocks)"""
81
+ if old_funnel not in track_source:
82
+ raise ValueError("Expected RobotTrack six-layer funnel is missing")
83
+ track_source = track_source.replace(old_funnel, new_funnel)
84
+ old_buffer = ' self.register_buffer("output_scale", output_scale)'
85
+ new_buffer = (
86
+ old_buffer
87
+ + "\n # Transformers >=5 reads this compatibility map during from_pretrained().\n self.all_tied_weights_keys = {}"
88
+ )
89
+ if old_buffer not in track_source:
90
+ raise ValueError("Expected RobotTrack output-scale registration is missing")
91
+ (folder / "modeling_robottrack.py").write_text(track_source.replace(old_buffer, new_buffer))
92
+
93
+ set_seed(42)
94
+ model = AutoModel.from_config(AutoConfig.from_pretrained(folder, trust_remote_code=True), trust_remote_code=True)
95
+ model.save_pretrained(folder, safe_serialization=True)
96
+ return str(model)
97
+
98
+
99
+ create_model(
100
+ source_model_id="openbmb/MiniCPM-RobotTrack",
101
+ source_revision="80d32d0b091c3b340a1e4a6c78d441e8af19590e",
102
+ save_folder="/tmp/minicpm-robot-track",
103
+ )
.meta/env.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_model": {
3
+ "name": "openbmb/MiniCPM-RobotTrack",
4
+ "commit_id": "80d32d0b091c3b340a1e4a6c78d441e8af19590e"
5
+ },
6
+ "environments": {
7
+ "creation": {
8
+ "python": "3.12.13",
9
+ "packages": {
10
+ "huggingface_hub": "2.3.0",
11
+ "safetensors": "0.8.0",
12
+ "tokenizers": "0.23.3",
13
+ "torch": "2.13.0+cu126",
14
+ "transformers": "5.20.2"
15
+ },
16
+ "cuda": "12.6",
17
+ "hardware": {
18
+ "gpu_model": "mlx lab master节点不包含GPU。请使用mlx worker launch -- nvidia-smi 来检查GPU状态, 或通过mlx worker launch -- bash登入gpu worker使用gpu相关命令。也可以通过mlx worker launch -h 查看更多launch命令使用方法。 如果mlx worker命令使用遇到问题,可运行 mlx upgrade将命令行工具升级至最新版"
19
+ }
20
+ },
21
+ "transformers": {
22
+ "python": "3.12.13",
23
+ "packages": {
24
+ "huggingface_hub": "2.3.0",
25
+ "safetensors": "0.8.0",
26
+ "tokenizers": "0.23.3",
27
+ "torch": "2.13.0+cu126",
28
+ "transformers": "5.20.2"
29
+ },
30
+ "cuda": "12.6",
31
+ "hardware": {
32
+ "gpu_model": "NVIDIA H20"
33
+ }
34
+ }
35
+ }
36
+ }
.meta/model.log ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MiniCPMRobotTrackModel(
2
+ (backbone): MiniCPMModel(
3
+ (embed_tokens): Embedding(73448, 32)
4
+ (layers): ModuleList(
5
+ (0-3): 4 x MiniCPMDecoderLayer(
6
+ (self_attn): MiniCPMSdpaAttention(
7
+ (q_proj): Linear(in_features=32, out_features=32, bias=False)
8
+ (k_proj): Linear(in_features=32, out_features=32, bias=False)
9
+ (v_proj): Linear(in_features=32, out_features=32, bias=False)
10
+ (o_proj): Linear(in_features=32, out_features=32, bias=False)
11
+ (rotary_emb): MiniCPMLongRoPE()
12
+ )
13
+ (mlp): MiniCPMMLP(
14
+ (gate_proj): Linear(in_features=32, out_features=64, bias=False)
15
+ (up_proj): Linear(in_features=32, out_features=64, bias=False)
16
+ (down_proj): Linear(in_features=64, out_features=32, bias=False)
17
+ (act_fn): SiLUActivation()
18
+ )
19
+ (input_layernorm): MiniCPMRMSNorm()
20
+ (post_attention_layernorm): MiniCPMRMSNorm()
21
+ )
22
+ )
23
+ (norm): MiniCPMRMSNorm()
24
+ )
25
+ (vision_projector): VisionProjector(
26
+ (layers): Sequential(
27
+ (0): LayerNorm((1536,), eps=1e-05, elementwise_affine=True, bias=True)
28
+ (1): Linear(in_features=1536, out_features=32, bias=True)
29
+ (2): GELU(approximate='none')
30
+ (3): Linear(in_features=32, out_features=32, bias=True)
31
+ )
32
+ )
33
+ (temporal_markers): TemporalMarkerEncoder(
34
+ (time_embedding): Embedding(128, 32)
35
+ (stream_embedding): Embedding(2, 32)
36
+ (camera_embedding): Embedding(1, 32)
37
+ )
38
+ (trajectory_head): FunnelTrajectoryHead(
39
+ (layers): Sequential(
40
+ (0): LayerNorm((32,), eps=1e-05, elementwise_affine=True, bias=True)
41
+ (1): Linear(in_features=32, out_features=128, bias=True)
42
+ (2): GELU(approximate='none')
43
+ (3): Dropout(p=0.4, inplace=False)
44
+ (4): Linear(in_features=128, out_features=64, bias=True)
45
+ (5): GELU(approximate='none')
46
+ (6): Dropout(p=0.4, inplace=False)
47
+ (7): Linear(in_features=64, out_features=32, bias=True)
48
+ (8): GELU(approximate='none')
49
+ (9): Dropout(p=0.4, inplace=False)
50
+ (10): Linear(in_features=32, out_features=32, bias=True)
51
+ (11): GELU(approximate='none')
52
+ (12): Dropout(p=0.4, inplace=False)
53
+ (13): Linear(in_features=32, out_features=32, bias=True)
54
+ (14): GELU(approximate='none')
55
+ (15): Dropout(p=0.4, inplace=False)
56
+ (16): LayerNorm((32,), eps=1e-05, elementwise_affine=True, bias=True)
57
+ (17): Linear(in_features=32, out_features=24, bias=True)
58
+ )
59
+ )
60
+ )
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [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,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ pipeline_tag: robotics
4
+ base_model:
5
+ - openbmb/MiniCPM-RobotTrack
6
+ ---
7
+
8
+ This is a randomly initialized tiny model based on [openbmb/MiniCPM-RobotTrack](https://huggingface.co/openbmb/MiniCPM-RobotTrack) for testing and debugging.
9
+
10
+ | Feature | Source | This repo |
11
+ |---|---|---|
12
+ | Checkpoint tensor elements | 465.65M BF16, 1.13M F32 | 2.39M BF16, 75.13K F32 |
13
+ | Safetensors weight files | 931.43 MB (model.safetensors) | 5.09 MB (model.safetensors) |
14
+ | Backbone layers / width / heads | 24 / 1024 / 16 | 4 / 32 / 1 |
15
+ | Backbone MLP / KV heads | 4096 / 2 | 64 / 1 |
16
+ | Trajectory funnel linear stages | 6 | 6 |
17
+ | External visual feature dimension | 1536 | Same |
18
+ | History / coarse tokens / current fine tokens | 31 / 4 per frame / 64 | Same |
19
+ | Waypoints / action dimensions | 8 / [x, y, yaw] | Same |
20
+ | Text vocabulary rows | 73448 | Same |
21
+ | Stored backbone precision | BF16 | Same |
22
+ | Input / output | Instruction, DINOv3+SigLIP tokens → trajectory | Same |
23
+
24
+ RobotTrack accepts fused DINOv3 and SigLIP features, not raw pixels. The source checkpoint does not include those visual encoders; the example validates both required feature streams directly.
25
+
26
+ | File path | Size |
27
+ |------|------|
28
+ | model.safetensors | 5.1MB |
29
+
30
+ ### Example usage
31
+
32
+ #### Transformers (✅ verified)
33
+
34
+ ```python
35
+ def run_transformers(model_id: str):
36
+ import torch
37
+ from transformers import AutoModel, AutoTokenizer
38
+
39
+ model = AutoModel.from_pretrained(model_id, trust_remote_code=True, dtype=torch.bfloat16).eval().cuda()
40
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
41
+ if tokenizer.pad_token_id is None:
42
+ tokenizer.pad_token = tokenizer.eos_token
43
+ text = tokenizer("Follow the person in the blue shirt.", return_tensors="pt")
44
+ coarse = torch.zeros(1, 31 * 4, 1536, device=model.device)
45
+ coarse_time = torch.arange(31, device=model.device).repeat_interleave(4).unsqueeze(0)
46
+ fine = torch.zeros(1, 64, 1536, device=model.device)
47
+ fine_time = torch.full((1, 64), 31, dtype=torch.long, device=model.device)
48
+ output = model(
49
+ input_ids=text.input_ids.to(model.device),
50
+ attention_mask=text.attention_mask.to(model.device),
51
+ coarse_tokens=coarse,
52
+ coarse_time_indices=coarse_time,
53
+ fine_tokens=fine,
54
+ fine_time_indices=fine_time,
55
+ )
56
+ assert output.trajectories.shape == (1, 8, 3)
57
+ assert torch.isfinite(output.trajectories).all()
58
+ print(output.trajectories.shape)
59
+
60
+
61
+ if __name__ == "__main__":
62
+ run_transformers(model_id="tiny-random/minicpm-robot-track")
63
+ ```
64
+
65
+ ### Creating this repo
66
+
67
+ - Code: [.meta/create_model.py](.meta/create_model.py)
68
+ - Model structure: [.meta/model.log](.meta/model.log)
69
+ - Environment: [.meta/env.json](.meta/env.json)
70
+
71
+ ### Change log
72
+
73
+ - 2026-10-27: Created a tiny MiniCPM RobotTrack visual-token trajectory policy.
74
+
75
+ *This repo is generated by GPT-6.1-Sol.*
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
+ }
config.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "action_dim": 3,
3
+ "architectures": [
4
+ "MiniCPMRobotTrackModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_robottrack.MiniCPMRobotTrackConfig",
8
+ "AutoModel": "modeling_robottrack.MiniCPMRobotTrackModel"
9
+ },
10
+ "backbone_config": {
11
+ "bos_token_id": 1,
12
+ "dim_model_base": 32,
13
+ "eos_token_id": [
14
+ 2,
15
+ 73440
16
+ ],
17
+ "hidden_act": "silu",
18
+ "hidden_size": 32,
19
+ "initializer_range": 0.1,
20
+ "intermediate_size": 64,
21
+ "max_position_embeddings": 128,
22
+ "num_attention_heads": 1,
23
+ "num_hidden_layers": 4,
24
+ "num_key_value_heads": 1,
25
+ "rms_norm_eps": 1e-05,
26
+ "rope_scaling": {
27
+ "long_factor": [
28
+ 1.0004360675811768,
29
+ 1.0668443441390991,
30
+ 1.1631425619125366,
31
+ 1.3025742769241333,
32
+ 1.5040205717086792,
33
+ 1.7941505908966064,
34
+ 2.2101221084594727,
35
+ 2.802666664123535,
36
+ 3.6389970779418945,
37
+ 4.804192543029785,
38
+ 6.39855432510376,
39
+ 8.527148246765137,
40
+ 11.277542114257812,
41
+ 14.684998512268066,
42
+ 18.69317054748535,
43
+ 23.13019371032715
44
+ ],
45
+ "original_max_position_embeddings": 128,
46
+ "rope_theta": 10000.0,
47
+ "rope_type": "longrope",
48
+ "short_factor": [
49
+ 1.0004360675811768,
50
+ 1.0668443441390991,
51
+ 1.1631425619125366,
52
+ 1.3025742769241333,
53
+ 1.5040205717086792,
54
+ 1.7941505908966064,
55
+ 2.2101221084594727,
56
+ 2.802666664123535,
57
+ 3.6389970779418945,
58
+ 4.804192543029785,
59
+ 6.39855432510376,
60
+ 8.527148246765137,
61
+ 11.277542114257812,
62
+ 14.684998512268066,
63
+ 18.69317054748535,
64
+ 23.13019371032715
65
+ ]
66
+ },
67
+ "scale_depth": 1.4,
68
+ "scale_emb": 12,
69
+ "use_cache": false,
70
+ "vocab_size": 73448
71
+ },
72
+ "backbone_dtype": "bfloat16",
73
+ "backbone_name": "openbmb/MiniCPM4-0.5B",
74
+ "coarse_tokens_per_frame": 4,
75
+ "dtype": "float32",
76
+ "fine_tokens_current_frame": 64,
77
+ "history_frames": 31,
78
+ "max_text_tokens": 128,
79
+ "max_time_steps": 128,
80
+ "model_name": "MiniCPM-RobotTrack",
81
+ "model_type": "minicpm_robottrack",
82
+ "num_waypoints": 8,
83
+ "trajectory_dropout": 0.4,
84
+ "transformers_version": "5.20.2",
85
+ "use_tanh_actions": true,
86
+ "vision_feature_dim": 1536,
87
+ "xy_scale": 2.0
88
+ }
configuration_minicpm.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ 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:d73169f98a6ae284cdbc3db0c0ba18ea389e41a1b3ae0ff6609ab6ee5ea7b31f
3
+ size 5090340
modeling_minicpm.py ADDED
@@ -0,0 +1,1518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ try:
49
+ from transformers.utils.import_utils import is_torch_fx_available
50
+ except ImportError:
51
+ def is_torch_fx_available():
52
+ return False
53
+
54
+ from .configuration_minicpm import MiniCPMConfig
55
+
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+ except:
60
+ pass
61
+
62
+
63
+
64
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
65
+ # It means that the function will not be traced through and simply appear as a node in the graph.
66
+ if is_torch_fx_available():
67
+ if not is_torch_greater_or_equal_than_1_13:
68
+ import torch.fx
69
+
70
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
71
+
72
+
73
+ logger = logging.get_logger(__name__)
74
+
75
+ _CONFIG_FOR_DOC = 'MiniCPMConfig'
76
+
77
+
78
+ def _get_unpad_data(attention_mask):
79
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
80
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
81
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
82
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
83
+ return (
84
+ indices,
85
+ cu_seqlens,
86
+ max_seqlen_in_batch,
87
+ )
88
+
89
+
90
+
91
+
92
+ # @torch.jit.script # type: ignore
93
+ def rms_layernorm(hidden: torch.Tensor, weight: torch.Tensor, eps: float):
94
+ old_dtype = hidden.dtype
95
+ variance = hidden.to(torch.float32).pow(2).mean(dim=-1, keepdim=True)
96
+ hidden = (hidden * torch.rsqrt(variance + eps)).to(old_dtype)
97
+ return hidden * weight
98
+
99
+
100
+ class MiniCPMRMSNorm(nn.Module):
101
+ def __init__(self, hidden_size, eps=1e-6):
102
+ """
103
+ MiniCPMRMSNorm is equivalent to T5LayerNorm
104
+ """
105
+ super().__init__()
106
+ self.weight = nn.Parameter(torch.ones(hidden_size))
107
+ self.variance_epsilon = eps
108
+
109
+ def forward(self, hidden_states):
110
+ return rms_layernorm(hidden_states, self.weight, self.variance_epsilon)
111
+
112
+
113
+ ALL_LAYERNORM_LAYERS.append(MiniCPMRMSNorm)
114
+
115
+
116
+ class MiniCPMRotaryEmbedding(nn.Module):
117
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
118
+ super().__init__()
119
+
120
+ self.dim = dim
121
+ self.max_position_embeddings = max_position_embeddings
122
+ self.base = base
123
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
124
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
125
+
126
+ # Build here to make `torch.jit.trace` work.
127
+ self._set_cos_sin_cache(
128
+ # seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
129
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.float32
130
+ )
131
+
132
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
133
+ self.max_seq_len_cached = seq_len
134
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
135
+ freqs = torch.outer(t, self.inv_freq)
136
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+
139
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
140
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
141
+
142
+ def forward(self, x, seq_len=None):
143
+ # x: [bs, num_attention_heads, seq_len, head_size]
144
+ if seq_len > self.max_seq_len_cached:
145
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
146
+
147
+ return (
148
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
149
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
150
+ )
151
+
152
+
153
+ class MiniCPMLongRoPE(MiniCPMRotaryEmbedding):
154
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
155
+
156
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, short_factor=None, long_factor=None, original_max_position_embeddings=None):
157
+ self.short_factor = short_factor
158
+ self.long_factor = long_factor
159
+ self.original_max_position_embeddings = original_max_position_embeddings
160
+ scale = (max_position_embeddings / self.original_max_position_embeddings)
161
+ self.scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
162
+ super().__init__(dim, max_position_embeddings, base, device)
163
+
164
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
165
+ self.max_seq_len_cached = seq_len
166
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
167
+ if seq_len > self.original_max_position_embeddings:
168
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=device)
169
+ else:
170
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=device)
171
+
172
+ freqs = torch.mul(
173
+ torch.outer(t, 1.0 / ext_factors).to(device=device),
174
+ self.inv_freq.to(device=device).to(dtype)
175
+ )
176
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
177
+ emb = torch.cat((freqs, freqs), dim=-1)
178
+ self.register_buffer('cos_cached', emb.cos().to(dtype) * self.scaling_factor, persistent=False)
179
+ self.register_buffer('sin_cached', emb.sin().to(dtype) * self.scaling_factor, persistent=False)
180
+
181
+
182
+ class MiniCPMLinearScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
183
+ """MiniCPMRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
184
+
185
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
186
+ self.scaling_factor = scaling_factor
187
+ super().__init__(dim, max_position_embeddings, base, device)
188
+
189
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
190
+ self.max_seq_len_cached = seq_len
191
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
192
+ t = t / self.scaling_factor
193
+
194
+ freqs = torch.outer(t, self.inv_freq)
195
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
196
+ emb = torch.cat((freqs, freqs), dim=-1)
197
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
198
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
199
+
200
+
201
+ class MiniCPMDynamicNTKScalingRotaryEmbedding(MiniCPMRotaryEmbedding):
202
+ """MiniCPMRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
203
+
204
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
205
+ self.scaling_factor = scaling_factor
206
+ super().__init__(dim, max_position_embeddings, base, device)
207
+
208
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
209
+ self.max_seq_len_cached = seq_len
210
+
211
+ if seq_len > self.max_position_embeddings:
212
+ base = self.base * (
213
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
214
+ ) ** (self.dim / (self.dim - 2))
215
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
216
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
217
+
218
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
219
+
220
+ freqs = torch.outer(t, self.inv_freq)
221
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
222
+ emb = torch.cat((freqs, freqs), dim=-1)
223
+
224
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
225
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
226
+
227
+
228
+ def rotate_half(x):
229
+ """Rotates half the hidden dims of the input."""
230
+ x1 = x[..., : x.shape[-1] // 2]
231
+ x2 = x[..., x.shape[-1] // 2:]
232
+ return torch.cat((-x2, x1), dim=-1)
233
+
234
+
235
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
236
+ """Applies Rotary Position Embedding to the query and key tensors.
237
+
238
+ Args:
239
+ q (`torch.Tensor`): The query tensor.
240
+ k (`torch.Tensor`): The key tensor.
241
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
242
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
243
+ position_ids (`torch.Tensor`):
244
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
245
+ used to pass offsetted position ids when working with a KV-cache.
246
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
247
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
248
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
249
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
250
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
251
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
252
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
253
+ Returns:
254
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
255
+ """
256
+ # cos = cos[position_ids].unsqueeze(unsqueeze_dim)
257
+ # sin = sin[position_ids].unsqueeze(unsqueeze_dim)
258
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
259
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
260
+ orig_dtype = k.dtype
261
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
262
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim) # [bs, 1, seq_len, dim]
263
+ q_fp32 = q.to(dtype=torch.float32, device=q.device)
264
+ k_fp32 = k.to(dtype=torch.float32, device=k.device)
265
+ q_embed = (q_fp32 * cos) + (rotate_half(q_fp32) * sin)
266
+ k_embed = (k_fp32 * cos) + (rotate_half(k_fp32) * sin)
267
+ return q_embed.to(dtype=orig_dtype), k_embed.to(dtype=orig_dtype)
268
+
269
+
270
+ class MiniCPMMLP(nn.Module):
271
+ def __init__(self, config):
272
+ super().__init__()
273
+ self.config = config
274
+ self.hidden_size = config.hidden_size
275
+ self.intermediate_size = config.intermediate_size
276
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
277
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
278
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
279
+ self.act_fn = ACT2FN[config.hidden_act]
280
+
281
+ def forward(self, x):
282
+ if self.config.pretraining_tp > 1:
283
+ slice = self.intermediate_size // self.config.pretraining_tp
284
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
285
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
286
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
287
+
288
+ gate_proj = torch.cat(
289
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
290
+ )
291
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
292
+
293
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
294
+ down_proj = [
295
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
296
+ ]
297
+ down_proj = sum(down_proj)
298
+ else:
299
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
300
+
301
+ return down_proj
302
+
303
+ def _unpad_one_tensor(hidden_states, attention_mask):
304
+ # Unpad the hidden states using the indices
305
+ indices, cu_seqlens, max_seqlen_in_batch = _get_unpad_data(attention_mask)
306
+ batch_size, seq_len = hidden_states.shape[:2]
307
+
308
+ # Get the remaining dimensions
309
+ remaining_dims = hidden_states.shape[2:]
310
+
311
+ # Reshape to (batch_size * seq_len, *remaining_dims)
312
+ reshaped_states = hidden_states.reshape(batch_size * seq_len, *remaining_dims)
313
+
314
+ # Apply unpadding using indices
315
+ unpadded_states = index_first_axis(reshaped_states, indices)
316
+
317
+ return unpadded_states, indices, cu_seqlens, max_seqlen_in_batch
318
+
319
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
320
+ """
321
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
322
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
323
+ """
324
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
325
+ if n_rep == 1:
326
+ return hidden_states
327
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
328
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
329
+
330
+
331
+ class MiniCPMAttention(nn.Module):
332
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
333
+
334
+ def __init__(self, config: MiniCPMConfig, layer_idx: Optional[int] = None):
335
+ super().__init__()
336
+ self.config = config
337
+ self.layer_idx = layer_idx
338
+ if layer_idx is None:
339
+ logger.warning_once(
340
+ f'Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will '
341
+ 'to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` '
342
+ 'when creating this class.'
343
+ )
344
+
345
+ self.attention_dropout = config.attention_dropout
346
+ self.hidden_size = config.hidden_size
347
+ self.num_heads = config.num_attention_heads
348
+ self.head_dim = self.hidden_size // self.num_heads
349
+ self.num_key_value_heads = config.num_key_value_heads
350
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
351
+ self.max_position_embeddings = config.max_position_embeddings
352
+ self.rope_theta = config.rope_theta
353
+ self.is_causal = True
354
+
355
+ if (self.head_dim * self.num_heads) != self.hidden_size:
356
+ raise ValueError(
357
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
358
+ f' and `num_heads`: {self.num_heads}).'
359
+ )
360
+
361
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
362
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
363
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
364
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
365
+ self._init_rope()
366
+
367
+ def _init_rope(self):
368
+ if self.config.rope_scaling is None:
369
+ self.rotary_emb = MiniCPMRotaryEmbedding(
370
+ self.head_dim,
371
+ max_position_embeddings=self.max_position_embeddings,
372
+ base=self.rope_theta,
373
+ )
374
+ else:
375
+ scaling_type = self.config.rope_scaling['rope_type']
376
+ scaling_factor = self.config.rope_scaling.get('factor', None)
377
+ if scaling_type == 'linear':
378
+ self.rotary_emb = MiniCPMLinearScalingRotaryEmbedding(
379
+ self.head_dim,
380
+ max_position_embeddings=self.max_position_embeddings,
381
+ scaling_factor=scaling_factor,
382
+ base=self.rope_theta,
383
+ )
384
+ elif scaling_type == 'dynamic':
385
+ self.rotary_emb = MiniCPMDynamicNTKScalingRotaryEmbedding(
386
+ self.head_dim,
387
+ max_position_embeddings=self.max_position_embeddings,
388
+ scaling_factor=scaling_factor,
389
+ base=self.rope_theta,
390
+ )
391
+ elif scaling_type == 'longrope':
392
+ self.rotary_emb = MiniCPMLongRoPE(
393
+ self.head_dim,
394
+ max_position_embeddings=self.max_position_embeddings,
395
+ short_factor=self.config.rope_scaling['short_factor'],
396
+ long_factor=self.config.rope_scaling['long_factor'],
397
+ base=self.rope_theta,
398
+ original_max_position_embeddings=self.config.rope_scaling['original_max_position_embeddings']
399
+ )
400
+ else:
401
+ raise ValueError(f'Unknown RoPE scaling type {scaling_type}')
402
+
403
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
404
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
405
+
406
+ def forward(
407
+ self,
408
+ hidden_states: torch.Tensor,
409
+ attention_mask: Optional[torch.Tensor] = None,
410
+ position_ids: Optional[torch.LongTensor] = None,
411
+ past_key_value: Optional[Cache] = None,
412
+ output_attentions: bool = False,
413
+ use_cache: bool = False,
414
+ **kwargs,
415
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
416
+ if 'padding_mask' in kwargs:
417
+ warnings.warn(
418
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
419
+ )
420
+
421
+ bsz, q_len, _ = hidden_states.size()
422
+
423
+ if self.config.pretraining_tp > 1:
424
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
425
+ query_slices = self.q_proj.weight.split(
426
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
427
+ )
428
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
429
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
430
+
431
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
432
+ query_states = torch.cat(query_states, dim=-1)
433
+
434
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
435
+ key_states = torch.cat(key_states, dim=-1)
436
+
437
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
438
+ value_states = torch.cat(value_states, dim=-1)
439
+
440
+ else:
441
+ query_states = self.q_proj(hidden_states)
442
+ key_states = self.k_proj(hidden_states)
443
+ value_states = self.v_proj(hidden_states)
444
+
445
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
446
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
447
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
448
+
449
+ kv_seq_len = position_ids.max().item() + 1
450
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
451
+
452
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
453
+
454
+ if past_key_value is not None:
455
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
456
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
457
+
458
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
459
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
460
+
461
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
462
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
463
+ raise ValueError(
464
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
465
+ f' {attn_weights.size()}'
466
+ )
467
+
468
+ if attention_mask is not None:
469
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
470
+ raise ValueError(
471
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
472
+ )
473
+ attn_weights = attn_weights + attention_mask
474
+
475
+ # upcast attention to fp32
476
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
477
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
478
+ attn_output = torch.matmul(attn_weights, value_states)
479
+
480
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
481
+ raise ValueError(
482
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
483
+ f' {attn_output.size()}'
484
+ )
485
+
486
+ attn_output = attn_output.transpose(1, 2).contiguous()
487
+
488
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
489
+
490
+ if self.config.pretraining_tp > 1:
491
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
492
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
493
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
494
+ else:
495
+ attn_output = self.o_proj(attn_output)
496
+
497
+ if not output_attentions:
498
+ attn_weights = None
499
+
500
+ return attn_output, attn_weights, past_key_value
501
+
502
+
503
+ class MiniCPMFlashAttention2(MiniCPMAttention):
504
+ """
505
+ MiniCPM flash attention module. This module inherits from `MiniCPMAttention` as the weights of the module stays
506
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
507
+ flash attention and deal with padding tokens in case the input contains any of them.
508
+ """
509
+
510
+ def __init__(self, *args, **kwargs):
511
+ super().__init__(*args, **kwargs)
512
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
513
+ # 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.
514
+ # 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).
515
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
516
+
517
+ def forward(
518
+ self,
519
+ hidden_states: torch.Tensor,
520
+ attention_mask: Optional[torch.LongTensor] = None,
521
+ position_ids: Optional[torch.LongTensor] = None,
522
+ past_key_value: Optional[Cache] = None,
523
+ output_attentions: bool = False,
524
+ use_cache: bool = False,
525
+ **kwargs,
526
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
527
+ # MiniCPMFlashAttention2 attention does not support output_attentions
528
+ if 'padding_mask' in kwargs:
529
+ warnings.warn(
530
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
531
+ )
532
+
533
+ # overwrite attention_mask with padding_mask
534
+ attention_mask = kwargs.pop('padding_mask')
535
+
536
+ output_attentions = False
537
+
538
+ bsz, q_len, _ = hidden_states.size()
539
+
540
+ query_states = self.q_proj(hidden_states)
541
+ key_states = self.k_proj(hidden_states)
542
+ value_states = self.v_proj(hidden_states)
543
+
544
+ # Flash attention requires the input to have the shape
545
+ # batch_size x seq_length x head_dim x hidden_dim
546
+ # therefore we just need to keep the original shape
547
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
548
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
549
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
550
+
551
+ kv_seq_len = position_ids.max().item() + 1
552
+ cos, sin = self.rotary_emb(value_states.to(torch.float32), seq_len=kv_seq_len)
553
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
554
+
555
+ if past_key_value is not None:
556
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
557
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
558
+
559
+ # 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
560
+ # to be able to avoid many of these transpose/reshape/view.
561
+ query_states = query_states.transpose(1, 2)
562
+ key_states = key_states.transpose(1, 2)
563
+ value_states = value_states.transpose(1, 2)
564
+
565
+ dropout_rate = self.attention_dropout if self.training else 0.0
566
+
567
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
568
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
569
+ # cast them back in the correct dtype just to be sure everything works as expected.
570
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
571
+ # in fp32. (MiniCPMRMSNorm handles it correctly)
572
+
573
+ input_dtype = query_states.dtype
574
+ if input_dtype == torch.float32:
575
+ # Handle the case where the model is quantized
576
+ if hasattr(self.config, '_pre_quantization_dtype'):
577
+ target_dtype = self.config._pre_quantization_dtype
578
+ else:
579
+ target_dtype = self.q_proj.weight.dtype
580
+
581
+ logger.warning_once(
582
+ f'The input hidden states seems to be silently casted in float32, this might be related to'
583
+ f' the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in'
584
+ f' {target_dtype}.'
585
+ )
586
+
587
+ query_states = query_states.to(target_dtype)
588
+ key_states = key_states.to(target_dtype)
589
+ value_states = value_states.to(target_dtype)
590
+
591
+ attn_output = self._flash_attention_forward(
592
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
593
+ )
594
+
595
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
596
+ attn_output = self.o_proj(attn_output)
597
+
598
+ if not output_attentions:
599
+ attn_weights = None
600
+
601
+ return attn_output, attn_weights, past_key_value
602
+
603
+ def _flash_attention_forward(
604
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
605
+ ):
606
+ """
607
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
608
+ first unpad the input, then computes the attention scores and pad the final attention scores.
609
+
610
+ Args:
611
+ query_states (`torch.Tensor`):
612
+ Input query states to be passed to Flash Attention API
613
+ key_states (`torch.Tensor`):
614
+ Input key states to be passed to Flash Attention API
615
+ value_states (`torch.Tensor`):
616
+ Input value states to be passed to Flash Attention API
617
+ attention_mask (`torch.Tensor`):
618
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
619
+ position of padding tokens and 1 for the position of non-padding tokens.
620
+ dropout (`int`, *optional*):
621
+ Attention dropout
622
+ softmax_scale (`float`, *optional*):
623
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
624
+ """
625
+ if not self._flash_attn_uses_top_left_mask:
626
+ causal = self.is_causal
627
+ else:
628
+ # 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__.
629
+ causal = self.is_causal and query_length != 1
630
+ # Contains at least one padding token in the sequence
631
+ if attention_mask is not None:
632
+ batch_size = query_states.shape[0]
633
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
634
+ query_states, key_states, value_states, attention_mask, query_length
635
+ )
636
+
637
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
638
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
639
+ attn_output_unpad = flash_attn_varlen_func(
640
+ query_states,
641
+ key_states,
642
+ value_states,
643
+ cu_seqlens_q=cu_seqlens_q,
644
+ cu_seqlens_k=cu_seqlens_k,
645
+ max_seqlen_q=max_seqlen_in_batch_q,
646
+ max_seqlen_k=max_seqlen_in_batch_k,
647
+ dropout_p=dropout,
648
+ softmax_scale=softmax_scale,
649
+ causal=causal,
650
+ )
651
+
652
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
653
+ else:
654
+ attn_output = flash_attn_func(
655
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
656
+ )
657
+
658
+ return attn_output
659
+
660
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
661
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
662
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
663
+
664
+ key_layer = index_first_axis(
665
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
666
+ )
667
+ value_layer = index_first_axis(
668
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
669
+ )
670
+ if query_length == kv_seq_len:
671
+ query_layer = index_first_axis(
672
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
673
+ )
674
+ cu_seqlens_q = cu_seqlens_k
675
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
676
+ indices_q = indices_k
677
+ elif query_length == 1:
678
+ max_seqlen_in_batch_q = 1
679
+ cu_seqlens_q = torch.arange(
680
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
681
+ ) # There is a memcpy here, that is very bad.
682
+ indices_q = cu_seqlens_q[:-1]
683
+ query_layer = query_layer.squeeze(1)
684
+ else:
685
+ # The -q_len: slice assumes left padding.
686
+ attention_mask = attention_mask[:, -query_length:]
687
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
688
+
689
+ return (
690
+ query_layer,
691
+ key_layer,
692
+ value_layer,
693
+ indices_q,
694
+ (cu_seqlens_q, cu_seqlens_k),
695
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
696
+ )
697
+
698
+
699
+ class MiniCPMSdpaAttention(MiniCPMAttention):
700
+ """
701
+ MiniCPM attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
702
+ `MiniCPMAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
703
+ SDPA API.
704
+ """
705
+
706
+ # Adapted from MiniCPMAttention.forward
707
+ def forward(
708
+ self,
709
+ hidden_states: torch.Tensor,
710
+ attention_mask: Optional[torch.Tensor] = None,
711
+ position_ids: Optional[torch.LongTensor] = None,
712
+ past_key_value: Optional[Cache] = None,
713
+ output_attentions: bool = False,
714
+ use_cache: bool = False,
715
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
716
+ if output_attentions:
717
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
718
+ logger.warning_once(
719
+ '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, '
720
+ '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.'
721
+ )
722
+ return super().forward(
723
+ hidden_states=hidden_states,
724
+ attention_mask=attention_mask,
725
+ position_ids=position_ids,
726
+ past_key_value=past_key_value,
727
+ output_attentions=output_attentions,
728
+ use_cache=use_cache,
729
+ )
730
+
731
+ bsz, q_len, _ = hidden_states.size()
732
+
733
+ query_states = self.q_proj(hidden_states)
734
+ key_states = self.k_proj(hidden_states)
735
+ value_states = self.v_proj(hidden_states)
736
+
737
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
738
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
739
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
740
+
741
+ kv_seq_len = position_ids.max().item() + 1
742
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
743
+
744
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
745
+
746
+ if past_key_value is not None:
747
+ cache_kwargs = {'sin': sin, 'cos': cos} # Specific to RoPE models
748
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
749
+
750
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
751
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
752
+
753
+ if attention_mask is not None:
754
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
755
+ raise ValueError(
756
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
757
+ )
758
+
759
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
760
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
761
+ if query_states.device.type == 'cuda' and attention_mask is not None:
762
+ query_states = query_states.contiguous()
763
+ key_states = key_states.contiguous()
764
+ value_states = value_states.contiguous()
765
+
766
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
767
+ query_states,
768
+ key_states,
769
+ value_states,
770
+ attn_mask=attention_mask,
771
+ dropout_p=self.attention_dropout if self.training else 0.0,
772
+ # 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.
773
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
774
+ )
775
+
776
+ attn_output = attn_output.transpose(1, 2).contiguous()
777
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
778
+
779
+ attn_output = self.o_proj(attn_output)
780
+
781
+ return attn_output, None, past_key_value
782
+
783
+
784
+ MINICPM_ATTENTION_CLASSES = {
785
+ 'eager': MiniCPMAttention,
786
+ 'flash_attention_2': MiniCPMFlashAttention2,
787
+ 'sdpa': MiniCPMSdpaAttention,
788
+ }
789
+
790
+
791
+ class MiniCPMDecoderLayer(nn.Module):
792
+ def __init__(self, config: MiniCPMConfig, layer_idx: int):
793
+ super().__init__()
794
+ self.hidden_size = config.hidden_size
795
+ self.self_attn = MINICPM_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
796
+
797
+ self.mlp = MiniCPMMLP(config)
798
+ self.input_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
799
+ self.post_attention_layernorm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
800
+
801
+ self.scale_depth = config.scale_depth
802
+ self.num_hidden_layers = config.num_hidden_layers
803
+
804
+ def forward(
805
+ self,
806
+ hidden_states: torch.Tensor,
807
+ attention_mask: Optional[torch.Tensor] = None,
808
+ position_ids: Optional[torch.LongTensor] = None,
809
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
810
+ output_attentions: Optional[bool] = False,
811
+ use_cache: Optional[bool] = False,
812
+ **kwargs,
813
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
814
+ """
815
+ Args:
816
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
817
+ attention_mask (`torch.FloatTensor`, *optional*):
818
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
819
+ query_sequence_length, key_sequence_length)` if default attention is used.
820
+ output_attentions (`bool`, *optional*):
821
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
822
+ returned tensors for more detail.
823
+ use_cache (`bool`, *optional*):
824
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
825
+ (see `past_key_values`).
826
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
827
+ """
828
+ if 'padding_mask' in kwargs:
829
+ warnings.warn(
830
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`'
831
+ )
832
+
833
+ residual = hidden_states
834
+ hidden_states = self.input_layernorm(hidden_states)
835
+ # Self Attention
836
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
837
+ hidden_states=hidden_states,
838
+ attention_mask=attention_mask,
839
+ position_ids=position_ids,
840
+ past_key_value=past_key_value,
841
+ output_attentions=output_attentions,
842
+ use_cache=use_cache,
843
+ **kwargs,
844
+ )
845
+
846
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
847
+
848
+ # Fully Connected
849
+ residual = hidden_states
850
+ hidden_states = self.post_attention_layernorm(hidden_states)
851
+
852
+ hidden_states = self.mlp(hidden_states)
853
+ hidden_states = residual + hidden_states * (self.scale_depth / math.sqrt(self.num_hidden_layers))
854
+
855
+ outputs = (hidden_states,)
856
+
857
+ if output_attentions:
858
+ outputs += (self_attn_weights,)
859
+
860
+ if use_cache:
861
+ outputs += (present_key_value,)
862
+
863
+ return outputs
864
+
865
+
866
+ MINICPM_START_DOCSTRING = r"""
867
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
868
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
869
+ etc.)
870
+
871
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
872
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
873
+ and behavior.
874
+
875
+ Parameters:
876
+ config ([`MiniCPMConfig`]):
877
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
878
+ load the weights associated with the model, only the configuration. Check out the
879
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
880
+ """
881
+
882
+
883
+ @add_start_docstrings(
884
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
885
+ MINICPM_START_DOCSTRING,
886
+ )
887
+ class MiniCPMPreTrainedModel(PreTrainedModel):
888
+ config_class = MiniCPMConfig
889
+ base_model_prefix = 'model'
890
+ supports_gradient_checkpointing = True
891
+ _no_split_modules = ['MiniCPMDecoderLayer']
892
+ _skip_keys_device_placement = 'past_key_values'
893
+ _supports_flash_attn_2 = True
894
+ _supports_sdpa = True
895
+ _supports_cache_class = True
896
+
897
+ def _init_weights(self, module):
898
+ std = self.config.initializer_range
899
+ if isinstance(module, nn.Linear):
900
+ module.weight.data.normal_(mean=0.0, std=std)
901
+ if module.bias is not None:
902
+ module.bias.data.zero_()
903
+ elif isinstance(module, nn.Embedding):
904
+ module.weight.data.normal_(mean=0.0, std=std)
905
+ if module.padding_idx is not None:
906
+ module.weight.data[module.padding_idx].zero_()
907
+
908
+
909
+ MINICPM_INPUTS_DOCSTRING = r"""
910
+ Args:
911
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
912
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
913
+ it.
914
+
915
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
916
+ [`PreTrainedTokenizer.__call__`] for details.
917
+
918
+ [What are input IDs?](../glossary#input-ids)
919
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
920
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
921
+
922
+ - 1 for tokens that are **not masked**,
923
+ - 0 for tokens that are **masked**.
924
+
925
+ [What are attention masks?](../glossary#attention-mask)
926
+
927
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
928
+ [`PreTrainedTokenizer.__call__`] for details.
929
+
930
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
931
+ `past_key_values`).
932
+
933
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
934
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
935
+ information on the default strategy.
936
+
937
+ - 1 indicates the head is **not masked**,
938
+ - 0 indicates the head is **masked**.
939
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
940
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
941
+ config.n_positions - 1]`.
942
+
943
+ [What are position IDs?](../glossary#position-ids)
944
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
945
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
946
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
947
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
948
+
949
+ Two formats are allowed:
950
+ - a [`~cache_utils.Cache`] instance;
951
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
952
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
953
+ cache format.
954
+
955
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
956
+ legacy cache format will be returned.
957
+
958
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
959
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
960
+ of shape `(batch_size, sequence_length)`.
961
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
962
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
963
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
964
+ model's internal embedding lookup matrix.
965
+ use_cache (`bool`, *optional*):
966
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
967
+ `past_key_values`).
968
+ output_attentions (`bool`, *optional*):
969
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
970
+ tensors for more detail.
971
+ output_hidden_states (`bool`, *optional*):
972
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
973
+ more detail.
974
+ return_dict (`bool`, *optional*):
975
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
976
+ """
977
+
978
+
979
+ @add_start_docstrings(
980
+ 'The bare MiniCPM Model outputting raw hidden-states without any specific head on top.',
981
+ MINICPM_START_DOCSTRING,
982
+ )
983
+ class MiniCPMModel(MiniCPMPreTrainedModel):
984
+ """
985
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MiniCPMDecoderLayer`]
986
+
987
+ Args:
988
+ config: MiniCPMConfig
989
+ """
990
+
991
+ def __init__(self, config: MiniCPMConfig):
992
+ super().__init__(config)
993
+ self.padding_idx = config.pad_token_id
994
+ self.vocab_size = config.vocab_size
995
+
996
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
997
+ self.layers = nn.ModuleList(
998
+ [MiniCPMDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
999
+ )
1000
+ self._use_sdpa = config._attn_implementation == 'sdpa'
1001
+ self._use_flash_attention_2 = config._attn_implementation == 'flash_attention_2'
1002
+
1003
+ self.norm = MiniCPMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1004
+
1005
+ self.gradient_checkpointing = False
1006
+ # Initialize weights and apply final processing
1007
+ self.post_init()
1008
+
1009
+ def get_input_embeddings(self):
1010
+ return self.embed_tokens
1011
+
1012
+ def set_input_embeddings(self, value):
1013
+ self.embed_tokens = value
1014
+
1015
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1016
+ def forward(
1017
+ self,
1018
+ input_ids: torch.LongTensor = None,
1019
+ attention_mask: Optional[torch.Tensor] = None,
1020
+ position_ids: Optional[torch.LongTensor] = None,
1021
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1022
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1023
+ use_cache: Optional[bool] = None,
1024
+ output_attentions: Optional[bool] = None,
1025
+ output_hidden_states: Optional[bool] = None,
1026
+ return_dict: Optional[bool] = None,
1027
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1028
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1029
+ output_hidden_states = (
1030
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1031
+ )
1032
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1033
+
1034
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1035
+
1036
+ # retrieve input_ids and inputs_embeds
1037
+ if input_ids is not None and inputs_embeds is not None:
1038
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
1039
+ elif input_ids is not None:
1040
+ batch_size, seq_length = input_ids.shape[:2]
1041
+ elif inputs_embeds is not None:
1042
+ batch_size, seq_length = inputs_embeds.shape[:2]
1043
+ else:
1044
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
1045
+
1046
+ if self.gradient_checkpointing and self.training:
1047
+ if use_cache:
1048
+ logger.warning_once(
1049
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
1050
+ )
1051
+ use_cache = False
1052
+
1053
+ past_key_values_length = 0
1054
+
1055
+ if use_cache:
1056
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1057
+ if use_legacy_cache:
1058
+ raise ValueError(
1059
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1060
+ )
1061
+
1062
+ # Calculate the usable length of past key values
1063
+ past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, Cache) else 0
1064
+
1065
+
1066
+ if position_ids is None:
1067
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1068
+ position_ids = torch.arange(
1069
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1070
+ )
1071
+ position_ids = position_ids.unsqueeze(0)
1072
+
1073
+ if inputs_embeds is None:
1074
+ inputs_embeds = self.embed_tokens(input_ids) * self.config.scale_emb
1075
+
1076
+ if self._use_flash_attention_2:
1077
+ # 2d mask is passed through the layers
1078
+ # attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1079
+ if attention_mask is None:
1080
+ raise ValueError(
1081
+ f'need attention_mask for flash attention, but got {attention_mask}.'
1082
+ )
1083
+ elif self._use_sdpa and not output_attentions:
1084
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1085
+ # the manual implementation that requires a 4D causal mask in all cases.
1086
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1087
+ attention_mask,
1088
+ (batch_size, seq_length),
1089
+ inputs_embeds,
1090
+ past_key_values_length,
1091
+ )
1092
+ else:
1093
+ # 4d mask is passed through the layers
1094
+ attention_mask = _prepare_4d_causal_attention_mask(
1095
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1096
+ )
1097
+
1098
+ # embed positions
1099
+ hidden_states = inputs_embeds
1100
+
1101
+ # decoder layers
1102
+ all_hidden_states = () if output_hidden_states else None
1103
+ all_self_attns = () if output_attentions else None
1104
+ next_decoder_cache = None
1105
+
1106
+ for decoder_layer in self.layers:
1107
+ if output_hidden_states:
1108
+ all_hidden_states += (hidden_states,)
1109
+
1110
+ if self.gradient_checkpointing and self.training:
1111
+ layer_outputs = self._gradient_checkpointing_func(
1112
+ decoder_layer.__call__,
1113
+ hidden_states,
1114
+ attention_mask,
1115
+ position_ids,
1116
+ past_key_values,
1117
+ output_attentions,
1118
+ use_cache,
1119
+ )
1120
+ else:
1121
+ layer_outputs = decoder_layer(
1122
+ hidden_states,
1123
+ attention_mask=attention_mask,
1124
+ position_ids=position_ids,
1125
+ past_key_value=past_key_values,
1126
+ output_attentions=output_attentions,
1127
+ use_cache=use_cache,
1128
+ )
1129
+
1130
+ hidden_states = layer_outputs[0]
1131
+
1132
+ if use_cache:
1133
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1134
+
1135
+ if output_attentions:
1136
+ all_self_attns += (layer_outputs[1],)
1137
+
1138
+ hidden_states = self.norm(hidden_states)
1139
+
1140
+ # add hidden states from the last decoder layer
1141
+ if output_hidden_states:
1142
+ all_hidden_states += (hidden_states,)
1143
+
1144
+ next_cache = None
1145
+ if use_cache:
1146
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1147
+ if not return_dict:
1148
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1149
+ return BaseModelOutputWithPast(
1150
+ last_hidden_state=hidden_states,
1151
+ past_key_values=next_cache,
1152
+ hidden_states=all_hidden_states,
1153
+ attentions=all_self_attns,
1154
+ )
1155
+
1156
+
1157
+ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
1158
+ _tied_weights_keys = ['lm_head.weight']
1159
+
1160
+ def __init__(self, config):
1161
+ super().__init__(config)
1162
+ self.model = MiniCPMModel(config)
1163
+ self.vocab_size = config.vocab_size
1164
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1165
+
1166
+ # Initialize weights and apply final processing
1167
+ self.post_init()
1168
+
1169
+ def get_input_embeddings(self):
1170
+ return self.model.embed_tokens
1171
+
1172
+ def set_input_embeddings(self, value):
1173
+ self.model.embed_tokens = value
1174
+
1175
+ def get_output_embeddings(self):
1176
+ return self.lm_head
1177
+
1178
+ def set_output_embeddings(self, new_embeddings):
1179
+ self.lm_head = new_embeddings
1180
+
1181
+ def set_decoder(self, decoder):
1182
+ self.model = decoder
1183
+
1184
+ def get_decoder(self):
1185
+ return self.model
1186
+
1187
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1188
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1189
+ def forward(
1190
+ self,
1191
+ input_ids: torch.LongTensor = None,
1192
+ attention_mask: Optional[torch.Tensor] = None,
1193
+ position_ids: Optional[torch.LongTensor] = None,
1194
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1195
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1196
+ labels: Optional[torch.LongTensor] = None,
1197
+ use_cache: Optional[bool] = None,
1198
+ output_attentions: Optional[bool] = None,
1199
+ output_hidden_states: Optional[bool] = None,
1200
+ return_dict: Optional[bool] = None,
1201
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1202
+ **kwargs,
1203
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1204
+ r"""
1205
+ Args:
1206
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1207
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1208
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1209
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1210
+
1211
+ Returns:
1212
+
1213
+ Example:
1214
+
1215
+ ```python
1216
+ >>> from transformers import AutoTokenizer, MiniCPMForCausalLM
1217
+
1218
+ >>> model = MiniCPMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1219
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1220
+
1221
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1222
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1223
+
1224
+ >>> # Generate
1225
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1226
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1227
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1228
+ ```"""
1229
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1230
+ output_hidden_states = (
1231
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1232
+ )
1233
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1234
+
1235
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1236
+ outputs = self.model(
1237
+ input_ids=input_ids,
1238
+ attention_mask=attention_mask,
1239
+ position_ids=position_ids,
1240
+ past_key_values=past_key_values,
1241
+ inputs_embeds=inputs_embeds,
1242
+ use_cache=use_cache,
1243
+ output_attentions=output_attentions,
1244
+ output_hidden_states=output_hidden_states,
1245
+ return_dict=return_dict,
1246
+ )
1247
+
1248
+ hidden_states = outputs[0]
1249
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1250
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1251
+ hidden_states = hidden_states[:, slice_indices, :].contiguous()
1252
+ if self.config.pretraining_tp > 1:
1253
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1254
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1255
+ logits = torch.cat(logits, dim=-1)
1256
+ else:
1257
+ logits = self.lm_head(hidden_states / (self.config.hidden_size / self.config.dim_model_base))
1258
+ logits = logits.float()
1259
+
1260
+ loss = None
1261
+ if labels is not None:
1262
+ # Shift so that tokens < n predict n
1263
+ shift_logits = logits[..., :-1, :].contiguous()
1264
+ shift_labels = labels[..., 1:].contiguous()
1265
+ # Flatten the tokens
1266
+ loss_fct = CrossEntropyLoss()
1267
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1268
+ shift_labels = shift_labels.view(-1)
1269
+ # Enable model parallelism
1270
+ shift_labels = shift_labels.to(shift_logits.device)
1271
+ loss = loss_fct(shift_logits, shift_labels)
1272
+
1273
+ if not return_dict:
1274
+ output = (logits,) + outputs[1:]
1275
+ return (loss,) + output if loss is not None else output
1276
+
1277
+ return CausalLMOutputWithPast(
1278
+ loss=loss,
1279
+ logits=logits,
1280
+ past_key_values=outputs.past_key_values,
1281
+ hidden_states=outputs.hidden_states,
1282
+ attentions=outputs.attentions,
1283
+ )
1284
+
1285
+ def prepare_inputs_for_generation(
1286
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1287
+ ):
1288
+ if past_key_values is not None:
1289
+ if isinstance(past_key_values, Cache):
1290
+ # Use the new Cache class methods
1291
+ cache_length = past_key_values.get_seq_length()
1292
+
1293
+
1294
+ past_length = cache_length
1295
+ max_cache_length = None
1296
+ else:
1297
+ raise ValueError(
1298
+ 'You must use the new past_key_values format, such as the Cache class, instead of the old tuple format.'
1299
+ )
1300
+
1301
+ # Keep only the unprocessed tokens:
1302
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1303
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1304
+ # input)
1305
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1306
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1307
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1308
+ # input_ids based on the past_length.
1309
+ elif past_length < input_ids.shape[1]:
1310
+ input_ids = input_ids[:, past_length:]
1311
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1312
+
1313
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1314
+ if (
1315
+ max_cache_length is not None
1316
+ and attention_mask is not None
1317
+ and cache_length + input_ids.shape[1] > max_cache_length
1318
+ ):
1319
+ attention_mask = attention_mask[:, -max_cache_length:]
1320
+
1321
+ position_ids = kwargs.get('position_ids', None)
1322
+ if attention_mask is not None and position_ids is None:
1323
+ # create position_ids on the fly for batch generation
1324
+ position_ids = attention_mask.long().cumsum(-1) - 1
1325
+ position_ids.masked_fill_(attention_mask == 0, 1)
1326
+ if past_key_values:
1327
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1328
+
1329
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1330
+ if inputs_embeds is not None and past_key_values is None:
1331
+ model_inputs = {'inputs_embeds': inputs_embeds}
1332
+ else:
1333
+ model_inputs = {'input_ids': input_ids}
1334
+
1335
+ model_inputs.update(
1336
+ {
1337
+ 'position_ids': position_ids,
1338
+ 'past_key_values': past_key_values,
1339
+ 'use_cache': kwargs.get('use_cache'),
1340
+ 'attention_mask': attention_mask,
1341
+ }
1342
+ )
1343
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
1344
+ for key, value in kwargs.items():
1345
+ if key not in model_inputs:
1346
+ model_inputs[key] = value
1347
+ return model_inputs
1348
+
1349
+ @staticmethod
1350
+ def _reorder_cache(past_key_values, beam_idx):
1351
+ reordered_past = ()
1352
+ for layer_past in past_key_values:
1353
+ reordered_past += (
1354
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1355
+ )
1356
+ return reordered_past
1357
+
1358
+ @torch.inference_mode()
1359
+ def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = 'user',
1360
+ max_length: int = 4096, num_beams=1, do_sample=True, top_p=0.8, temperature=0.3, logits_processor=None,
1361
+ **kwargs):
1362
+ if history is None:
1363
+ history = []
1364
+ if logits_processor:
1365
+ gen_kwargs = {
1366
+ 'max_length': max_length,
1367
+ 'num_beams': num_beams,
1368
+ 'do_sample': do_sample,
1369
+ 'top_p': top_p,
1370
+ 'temperature': temperature,
1371
+ 'logits_processor': logits_processor,
1372
+ **kwargs
1373
+ }
1374
+ else:
1375
+ gen_kwargs = {
1376
+ 'max_length': max_length,
1377
+ 'num_beams': num_beams,
1378
+ 'do_sample': do_sample,
1379
+ 'top_p': top_p,
1380
+ 'temperature': temperature,
1381
+ 'logits_processor': logits_processor,
1382
+ **kwargs
1383
+ }
1384
+
1385
+ history.append({'role': role, 'content': query})
1386
+ history_str = tokenizer.apply_chat_template(history, tokenize=False, add_generation_prompt=False)
1387
+ inputs = tokenizer(history_str, return_tensors='pt').to(self.device)
1388
+ outputs = self.generate(**inputs, **gen_kwargs)
1389
+ outputs = outputs.tolist()[0][len(inputs['input_ids'][0]):-1]
1390
+ response = tokenizer.decode(outputs)
1391
+ pattern = re.compile(r'.*?(?=<AI>|<用户>)', re.DOTALL)
1392
+ matches = pattern.findall(response)
1393
+ if len(matches) > 0:
1394
+ response = matches[0]
1395
+ history.append({'role': 'assistant', 'content': response})
1396
+ return response, history
1397
+
1398
+
1399
+ @add_start_docstrings(
1400
+ """
1401
+ The MiniCPM Model transformer with a sequence classification head on top (linear layer).
1402
+
1403
+ [`MiniCPMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1404
+ (e.g. GPT-2) do.
1405
+
1406
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1407
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1408
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1409
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1410
+ each row of the batch).
1411
+ """,
1412
+ MINICPM_START_DOCSTRING,
1413
+ )
1414
+ class MiniCPMForSequenceClassification(MiniCPMPreTrainedModel):
1415
+ def __init__(self, config):
1416
+ super().__init__(config)
1417
+ self.num_labels = config.num_labels
1418
+ self.model = MiniCPMModel(config)
1419
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1420
+
1421
+ # Initialize weights and apply final processing
1422
+ self.post_init()
1423
+
1424
+ def get_input_embeddings(self):
1425
+ return self.model.embed_tokens
1426
+
1427
+ def set_input_embeddings(self, value):
1428
+ self.model.embed_tokens = value
1429
+
1430
+ @add_start_docstrings_to_model_forward(MINICPM_INPUTS_DOCSTRING)
1431
+ def forward(
1432
+ self,
1433
+ input_ids: torch.LongTensor = None,
1434
+ attention_mask: Optional[torch.Tensor] = None,
1435
+ position_ids: Optional[torch.LongTensor] = None,
1436
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1437
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1438
+ labels: Optional[torch.LongTensor] = None,
1439
+ use_cache: Optional[bool] = None,
1440
+ output_attentions: Optional[bool] = None,
1441
+ output_hidden_states: Optional[bool] = None,
1442
+ return_dict: Optional[bool] = None,
1443
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1444
+ r"""
1445
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1446
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1447
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1448
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1449
+ """
1450
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1451
+
1452
+ transformer_outputs = self.model(
1453
+ input_ids,
1454
+ attention_mask=attention_mask,
1455
+ position_ids=position_ids,
1456
+ past_key_values=past_key_values,
1457
+ inputs_embeds=inputs_embeds,
1458
+ use_cache=use_cache,
1459
+ output_attentions=output_attentions,
1460
+ output_hidden_states=output_hidden_states,
1461
+ return_dict=return_dict,
1462
+ )
1463
+ hidden_states = transformer_outputs[0]
1464
+ logits = self.score(hidden_states)
1465
+
1466
+ if input_ids is not None:
1467
+ batch_size = input_ids.shape[0]
1468
+ else:
1469
+ batch_size = inputs_embeds.shape[0]
1470
+
1471
+ if self.config.pad_token_id is None and batch_size != 1:
1472
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1473
+ if self.config.pad_token_id is None:
1474
+ sequence_lengths = -1
1475
+ else:
1476
+ if input_ids is not None:
1477
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1478
+ logits.device
1479
+ )
1480
+ else:
1481
+ sequence_lengths = -1
1482
+
1483
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1484
+
1485
+ loss = None
1486
+ if labels is not None:
1487
+ labels = labels.to(logits.device)
1488
+ if self.config.problem_type is None:
1489
+ if self.num_labels == 1:
1490
+ self.config.problem_type = 'regression'
1491
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1492
+ self.config.problem_type = 'single_label_classification'
1493
+ else:
1494
+ self.config.problem_type = 'multi_label_classification'
1495
+
1496
+ if self.config.problem_type == 'regression':
1497
+ loss_fct = MSELoss()
1498
+ if self.num_labels == 1:
1499
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1500
+ else:
1501
+ loss = loss_fct(pooled_logits, labels)
1502
+ elif self.config.problem_type == 'single_label_classification':
1503
+ loss_fct = CrossEntropyLoss()
1504
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1505
+ elif self.config.problem_type == 'multi_label_classification':
1506
+ loss_fct = BCEWithLogitsLoss()
1507
+ loss = loss_fct(pooled_logits, labels)
1508
+ if not return_dict:
1509
+ output = (pooled_logits,) + transformer_outputs[1:]
1510
+ return ((loss,) + output) if loss is not None else output
1511
+
1512
+ return SequenceClassifierOutputWithPast(
1513
+ loss=loss,
1514
+ logits=pooled_logits,
1515
+ past_key_values=transformer_outputs.past_key_values,
1516
+ hidden_states=transformer_outputs.hidden_states,
1517
+ attentions=transformer_outputs.attentions,
1518
+ )
modeling_robottrack.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ widths = (max(hidden_dim * 4, 32), max(hidden_dim * 2, 32), hidden_dim, hidden_dim, hidden_dim)
97
+ blocks = [nn.LayerNorm(hidden_dim)]
98
+ previous = hidden_dim
99
+ for width in widths:
100
+ blocks.extend((nn.Linear(previous, width), nn.GELU(), nn.Dropout(dropout)))
101
+ previous = width
102
+ blocks.extend((nn.LayerNorm(previous), nn.Linear(previous, output_dim)))
103
+ self.layers = nn.Sequential(*blocks)
104
+
105
+ def forward(self, control_state: torch.Tensor) -> torch.Tensor:
106
+ trajectory = self.layers(control_state)
107
+ if self.use_tanh:
108
+ trajectory = torch.tanh(trajectory)
109
+ return trajectory.view(-1, self.num_waypoints, self.action_dim)
110
+
111
+
112
+ @dataclass
113
+ class MiniCPMRobotTrackOutput(ModelOutput):
114
+ """Output of MiniCPM-RobotTrack."""
115
+
116
+ loss: Optional[torch.FloatTensor] = None
117
+ trajectories: Optional[torch.FloatTensor] = None
118
+
119
+
120
+ class MiniCPMRobotTrackModel(PreTrainedModel):
121
+ """MiniCPM visual tracking policy with a funnel trajectory head."""
122
+
123
+ config_class = MiniCPMRobotTrackConfig
124
+ base_model_prefix = "backbone"
125
+ main_input_name = "input_ids"
126
+ supports_gradient_checkpointing = True
127
+ _supports_sdpa = True
128
+ _supports_flash_attn_2 = True
129
+ _no_split_modules = ["MiniCPMDecoderLayer"]
130
+
131
+ def __init__(self, config: MiniCPMRobotTrackConfig) -> None:
132
+ super().__init__(config)
133
+
134
+ backbone_config = MiniCPMConfig(**config.backbone_config)
135
+ attention_implementation = getattr(config, "_attn_implementation", None)
136
+ if attention_implementation is not None:
137
+ backbone_config._attn_implementation = attention_implementation
138
+ backbone_config.use_cache = False
139
+
140
+ backbone_dtype = _dtype_from_name(config.backbone_dtype)
141
+ with _default_dtype(backbone_dtype):
142
+ self.backbone = MiniCPMModel(backbone_config)
143
+
144
+ hidden_dim = int(backbone_config.hidden_size)
145
+ self.vision_projector = VisionProjector(config.vision_feature_dim, hidden_dim)
146
+ self.temporal_markers = TemporalMarkerEncoder(hidden_dim, config.max_time_steps)
147
+ self.control_query = nn.Parameter(torch.empty(1, 1, hidden_dim))
148
+ nn.init.normal_(self.control_query, mean=0.0, std=0.02)
149
+ self.trajectory_head = FunnelTrajectoryHead(
150
+ hidden_dim=hidden_dim,
151
+ num_waypoints=config.num_waypoints,
152
+ action_dim=config.action_dim,
153
+ dropout=config.trajectory_dropout,
154
+ use_tanh=config.use_tanh_actions,
155
+ )
156
+
157
+ output_scale = torch.ones(1, 1, config.action_dim, dtype=torch.float32)
158
+ output_scale[..., :2] = config.xy_scale
159
+ self.register_buffer("output_scale", output_scale)
160
+ # Transformers >=5 reads this compatibility map during from_pretrained().
161
+ self.all_tied_weights_keys = {}
162
+
163
+ def get_input_embeddings(self) -> nn.Module:
164
+ return self.backbone.get_input_embeddings()
165
+
166
+ def set_input_embeddings(self, value: nn.Module) -> None:
167
+ self.backbone.set_input_embeddings(value)
168
+
169
+ def _insert_temporal_markers(
170
+ self,
171
+ tokens: torch.Tensor,
172
+ time_indices: torch.Tensor,
173
+ stream_id: int,
174
+ ) -> torch.Tensor:
175
+ if tokens.ndim != 3 or time_indices.ndim != 2:
176
+ raise ValueError("visual tokens and time indices must have shapes [B, N, C] and [B, N]")
177
+ if tokens.shape[:2] != time_indices.shape:
178
+ raise ValueError("visual token and time-index shapes do not match")
179
+ if tokens.size(1) == 0:
180
+ return tokens
181
+
182
+ packed_rows: List[torch.Tensor] = []
183
+ time_rows = time_indices.detach().to("cpu").tolist()
184
+ for batch_index, time_row in enumerate(time_rows):
185
+ pieces: List[torch.Tensor] = []
186
+ start = 0
187
+ while start < len(time_row):
188
+ time_step = int(time_row[start])
189
+ if not 0 <= time_step < self.config.max_time_steps:
190
+ raise ValueError(f"time index {time_step} is outside the configured range")
191
+ end = start + 1
192
+ while end < len(time_row) and int(time_row[end]) == time_step:
193
+ end += 1
194
+ marker = self.temporal_markers(time_step, stream_id, tokens.device)
195
+ pieces.extend((marker.unsqueeze(0), tokens[batch_index, start:end]))
196
+ start = end
197
+ packed_rows.append(torch.cat(pieces, dim=0))
198
+
199
+ packed_lengths = {row.size(0) for row in packed_rows}
200
+ if len(packed_lengths) != 1:
201
+ raise ValueError("each batch item must contain the same number of represented frames")
202
+ return torch.stack(packed_rows, dim=0)
203
+
204
+ def _build_sequence(
205
+ self,
206
+ input_ids: torch.LongTensor,
207
+ attention_mask: Optional[torch.Tensor],
208
+ coarse_tokens: torch.Tensor,
209
+ coarse_time_indices: torch.Tensor,
210
+ fine_tokens: torch.Tensor,
211
+ fine_time_indices: torch.Tensor,
212
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
213
+ device = self.control_query.device
214
+ input_ids = input_ids.to(device)
215
+ if attention_mask is None:
216
+ attention_mask = torch.ones_like(input_ids, dtype=torch.long)
217
+ else:
218
+ attention_mask = attention_mask.to(device)
219
+
220
+ batch_size = coarse_tokens.size(0)
221
+ if fine_tokens.size(0) != batch_size or input_ids.size(0) != batch_size:
222
+ raise ValueError("batch dimensions do not match")
223
+
224
+ projector_dtype = _module_dtype(self.vision_projector)
225
+ history = self.vision_projector(coarse_tokens.to(device=device, dtype=projector_dtype))
226
+ current = self.vision_projector(fine_tokens.to(device=device, dtype=projector_dtype))
227
+ history = self._insert_temporal_markers(
228
+ history, coarse_time_indices.to(device), stream_id=0
229
+ )
230
+ current = self._insert_temporal_markers(
231
+ current, fine_time_indices.to(device), stream_id=1
232
+ )
233
+ text = self.backbone.get_input_embeddings()(input_ids)
234
+
235
+ control_query = self.control_query.expand(batch_size, -1, -1)
236
+ sequence = torch.cat((text, history, current, control_query), dim=1)
237
+ sequence = sequence.to(dtype=_module_dtype(self.backbone))
238
+
239
+ full_attention_mask = torch.cat(
240
+ (
241
+ attention_mask,
242
+ torch.ones(batch_size, history.size(1), dtype=torch.long, device=device),
243
+ torch.ones(batch_size, current.size(1), dtype=torch.long, device=device),
244
+ torch.ones(batch_size, 1, dtype=torch.long, device=device),
245
+ ),
246
+ dim=1,
247
+ )
248
+ return sequence, full_attention_mask
249
+
250
+ def normalize_trajectory(self, trajectory: torch.Tensor) -> torch.Tensor:
251
+ return trajectory / self.output_scale.to(device=trajectory.device, dtype=trajectory.dtype)
252
+
253
+ def forward(
254
+ self,
255
+ input_ids: torch.LongTensor,
256
+ coarse_tokens: torch.Tensor,
257
+ coarse_time_indices: torch.Tensor,
258
+ fine_tokens: torch.Tensor,
259
+ fine_time_indices: torch.Tensor,
260
+ attention_mask: Optional[torch.Tensor] = None,
261
+ labels: Optional[torch.Tensor] = None,
262
+ valid_mask: Optional[torch.Tensor] = None,
263
+ return_dict: Optional[bool] = None,
264
+ ) -> Union[MiniCPMRobotTrackOutput, Tuple[torch.Tensor, ...]]:
265
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
266
+ sequence, full_attention_mask = self._build_sequence(
267
+ input_ids=input_ids,
268
+ attention_mask=attention_mask,
269
+ coarse_tokens=coarse_tokens,
270
+ coarse_time_indices=coarse_time_indices,
271
+ fine_tokens=fine_tokens,
272
+ fine_time_indices=fine_time_indices,
273
+ )
274
+ output = self.backbone(
275
+ inputs_embeds=sequence,
276
+ attention_mask=full_attention_mask,
277
+ use_cache=False,
278
+ return_dict=True,
279
+ )
280
+ control_state = output.last_hidden_state[:, -1].to(
281
+ dtype=_module_dtype(self.trajectory_head)
282
+ )
283
+ normalized_trajectory = self.trajectory_head(control_state)
284
+ trajectories = normalized_trajectory * self.output_scale.to(
285
+ normalized_trajectory.dtype
286
+ )
287
+
288
+ loss = None
289
+ if labels is not None:
290
+ labels = labels.to(device=trajectories.device, dtype=trajectories.dtype)
291
+ if labels.shape != trajectories.shape:
292
+ raise ValueError("labels and predicted trajectories must have identical shapes")
293
+ normalized_labels = self.normalize_trajectory(labels)
294
+ squared_error = (normalized_trajectory - normalized_labels).square()
295
+ if valid_mask is None:
296
+ loss = squared_error.mean()
297
+ else:
298
+ mask = valid_mask.to(
299
+ device=trajectories.device, dtype=trajectories.dtype
300
+ ).unsqueeze(-1)
301
+ denominator = mask.sum() * trajectories.size(-1)
302
+ loss = (
303
+ squared_error.mul(mask).sum() / denominator
304
+ if denominator.item() > 0
305
+ else trajectories.sum() * 0.0
306
+ )
307
+
308
+ if not return_dict:
309
+ return (trajectories,) if loss is None else (loss, trajectories)
310
+ return MiniCPMRobotTrackOutput(loss=loss, trajectories=trajectories)
311
+
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
+ }