hexoy commited on
Commit
f897353
·
verified ·
1 Parent(s): 3eaffd2

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Gemma 4 E2B Monarch model
2
+
3
+ This model is derived from google/gemma-4-E2B-it.
4
+
5
+ Modifications:
6
+ - Replaced language-model MLP layers 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 with two-factor rectangular
7
+ Monarch linear maps.
8
+ - Initialized factors by rank-one SVD projection of each dense Monarch slice.
9
+ - Distilled the modified layers against the original model.
10
+
11
+ The original and modified files are distributed under the Apache License 2.0.
README.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: google/gemma-4-E2B-it
4
+ library_name: transformers
5
+ pipeline_tag: image-text-to-text
6
+ tags:
7
+ - gemma4
8
+ - monarch-matrices
9
+ - model-compression
10
+ ---
11
+
12
+ # Gemma 4 E2B Monarch 35-MLP
13
+
14
+ Experimental Gemma 4 E2B model in which language-model MLP layers 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 are
15
+ replaced by two-factor rectangular Monarch linear maps. The factors were initialized
16
+ with dense-to-Monarch SVD projection and trained with activation alignment followed by
17
+ full-model logit distillation.
18
+
19
+ The exported model contains 3,682,268,704 parameters and preserves the original
20
+ Gemma 4 multimodal processor and architecture outside the selected MLPs.
21
+
22
+ ## Usage
23
+
24
+ ```python
25
+ from transformers import AutoModelForImageTextToText, AutoProcessor
26
+
27
+ model_id = "hexoy/gemma-4-e2b-monarch-35mlp"
28
+ processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
29
+ model = AutoModelForImageTextToText.from_pretrained(
30
+ model_id,
31
+ trust_remote_code=True,
32
+ dtype="auto",
33
+ device_map="auto",
34
+ )
35
+ ```
36
+
37
+ This repository contains custom modeling code, so review it before enabling
38
+ `trust_remote_code=True`.
39
+
40
+ ## Limitations
41
+
42
+ - This is an experimental compression artifact, not an official Google model.
43
+ - Only 35 of the 35 language-model MLPs are compressed.
44
+ - Quality and inference speed have not been established on broad downstream benchmarks.
45
+ - The model should be evaluated for the intended task before deployment.
46
+
47
+ ## Attribution
48
+
49
+ Derived from [google/gemma-4-E2B-it](https://huggingface.co/google/gemma-4-E2B-it). See `NOTICE` for
50
+ the modification summary.
chat_template.jinja ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#
2
+ Template: Google Gemma 4 Canonical Chat Template
3
+ Author: Google Gemma Engineering Team
4
+ Published: 2026-07-09
5
+ Context: Fixed tool-calling loops, turn closures, and thinking content-ordering.
6
+ #}
7
+ {%- macro format_parameters(properties, required, filter_keys=false) -%}
8
+ {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}
9
+ {%- set ns = namespace(found_first=false) -%}
10
+ {%- for key, value in properties | dictsort -%}
11
+ {%- set add_comma = false -%}
12
+ {%- if not filter_keys or key not in standard_keys -%}
13
+ {%- if ns.found_first %},{% endif -%}
14
+ {%- set ns.found_first = true -%}
15
+ {{ key }}:{
16
+ {%- if value['description'] -%}
17
+ description:<|"|>{{ value['description'] }}<|"|>
18
+ {%- set add_comma = true -%}
19
+ {%- endif -%}
20
+ {%- if value['type'] | upper == 'STRING' -%}
21
+ {%- if value['enum'] -%}
22
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
23
+ enum:{{ format_argument(value['enum']) }}
24
+ {%- endif -%}
25
+ {%- elif value['type'] | upper == 'ARRAY' -%}
26
+ {%- if value['items'] is mapping and value['items'] -%}
27
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
28
+ items:{
29
+ {%- set ns_items = namespace(found_first=false) -%}
30
+ {%- for item_key, item_value in value['items'] | dictsort -%}
31
+ {%- if item_value is not none -%}
32
+ {%- if ns_items.found_first %},{% endif -%}
33
+ {%- set ns_items.found_first = true -%}
34
+ {%- if item_key == 'properties' -%}
35
+ properties:{
36
+ {%- if item_value is mapping -%}
37
+ {{- format_parameters(item_value, value['items']['required'] | default([])) -}}
38
+ {%- endif -%}
39
+ }
40
+ {%- elif item_key == 'required' -%}
41
+ required:[
42
+ {%- for req_item in item_value -%}
43
+ <|"|>{{- req_item -}}<|"|>
44
+ {%- if not loop.last %},{% endif -%}
45
+ {%- endfor -%}
46
+ ]
47
+ {%- elif item_key == 'type' -%}
48
+ {%- if item_value is string -%}
49
+ type:{{ format_argument(item_value | upper) }}
50
+ {%- else -%}
51
+ type:{{ format_argument(item_value | map('upper') | list) }}
52
+ {%- endif -%}
53
+ {%- else -%}
54
+ {{ item_key }}:{{ format_argument(item_value) }}
55
+ {%- endif -%}
56
+ {%- endif -%}
57
+ {%- endfor -%}
58
+ }
59
+ {%- endif -%}
60
+ {%- endif -%}
61
+ {%- if value['nullable'] %}
62
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
63
+ nullable:true
64
+ {%- endif -%}
65
+ {%- if value['type'] | upper == 'OBJECT' -%}
66
+ {%- if value['properties'] is defined and value['properties'] is mapping -%}
67
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
68
+ properties:{
69
+ {{- format_parameters(value['properties'], value['required'] | default([])) -}}
70
+ }
71
+ {%- elif value is mapping -%}
72
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
73
+ properties:{
74
+ {{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}}
75
+ }
76
+ {%- endif -%}
77
+ {%- if value['required'] -%}
78
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
79
+ required:[
80
+ {%- for item in value['required'] | default([]) -%}
81
+ <|"|>{{- item -}}<|"|>
82
+ {%- if not loop.last %},{% endif -%}
83
+ {%- endfor -%}
84
+ ]
85
+ {%- endif -%}
86
+ {%- endif -%}
87
+ {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
88
+ type:<|"|>{{ value['type'] | upper }}<|"|>}
89
+ {%- endif -%}
90
+ {%- endfor -%}
91
+ {%- endmacro -%}
92
+ {%- macro format_function_declaration(tool_data) -%}
93
+ declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|>
94
+ {%- set params = tool_data['function']['parameters'] -%}
95
+ {%- if params -%}
96
+ ,parameters:{
97
+ {%- if params['properties'] -%}
98
+ properties:{ {{- format_parameters(params['properties'], params['required']) -}} },
99
+ {%- endif -%}
100
+ {%- if params['required'] -%}
101
+ required:[
102
+ {%- for item in params['required'] -%}
103
+ <|"|>{{- item -}}<|"|>
104
+ {{- ',' if not loop.last -}}
105
+ {%- endfor -%}
106
+ ],
107
+ {%- endif -%}
108
+ {%- if params['type'] -%}
109
+ type:<|"|>{{- params['type'] | upper -}}<|"|>}
110
+ {%- endif -%}
111
+ {%- endif -%}
112
+ {%- if 'response' in tool_data['function'] -%}
113
+ {%- set response_declaration = tool_data['function']['response'] -%}
114
+ ,response:{
115
+ {%- if response_declaration['description'] -%}
116
+ description:<|"|>{{- response_declaration['description'] -}}<|"|>,
117
+ {%- endif -%}
118
+ {%- if response_declaration['type'] | upper == 'OBJECT' -%}
119
+ type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>}
120
+ {%- endif -%}
121
+ {%- endif -%}
122
+ }
123
+ {%- endmacro -%}
124
+ {%- macro format_argument(argument, escape_keys=True) -%}
125
+ {%- if argument is none -%}
126
+ {{- 'null' -}}
127
+ {%- elif argument is string -%}
128
+ {{- '<|"|>' + argument + '<|"|>' -}}
129
+ {%- elif argument is boolean -%}
130
+ {{- 'true' if argument else 'false' -}}
131
+ {%- elif argument is mapping -%}
132
+ {{- '{' -}}
133
+ {%- set ns = namespace(found_first=false) -%}
134
+ {%- for key, value in argument | dictsort -%}
135
+ {%- if ns.found_first %},{% endif -%}
136
+ {%- set ns.found_first = true -%}
137
+ {%- if escape_keys -%}
138
+ {{- '<|"|>' + key + '<|"|>' -}}
139
+ {%- else -%}
140
+ {{- key -}}
141
+ {%- endif -%}
142
+ :{{- format_argument(value, escape_keys=escape_keys) -}}
143
+ {%- endfor -%}
144
+ {{- '}' -}}
145
+ {%- elif argument is sequence -%}
146
+ {{- '[' -}}
147
+ {%- for item in argument -%}
148
+ {{- format_argument(item, escape_keys=escape_keys) -}}
149
+ {%- if not loop.last %},{% endif -%}
150
+ {%- endfor -%}
151
+ {{- ']' -}}
152
+ {%- else -%}
153
+ {{- argument -}}
154
+ {%- endif -%}
155
+ {%- endmacro -%}
156
+ {%- macro strip_thinking(text) -%}
157
+ {%- set ns = namespace(result='') -%}
158
+ {%- for part in text.split('<channel|>') -%}
159
+ {%- if '<|channel>' in part -%}
160
+ {%- set ns.result = ns.result + part.split('<|channel>')[0] -%}
161
+ {%- else -%}
162
+ {%- set ns.result = ns.result + part -%}
163
+ {%- endif -%}
164
+ {%- endfor -%}
165
+ {{- ns.result | trim -}}
166
+ {%- endmacro -%}
167
+
168
+ {%- macro format_tool_response_block(tool_name, response) -%}
169
+ {{- '<|tool_response>' -}}
170
+ {%- if response is mapping -%}
171
+ {{- 'response:' + tool_name + '{' -}}
172
+ {%- for key, value in response | dictsort -%}
173
+ {{- key -}}:{{- format_argument(value, escape_keys=False) -}}
174
+ {%- if not loop.last %},{% endif -%}
175
+ {%- endfor -%}
176
+ {{- '}' -}}
177
+ {%- else -%}
178
+ {{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}}
179
+ {%- endif -%}
180
+ {{- '<tool_response|>' -}}
181
+ {%- endmacro -%}
182
+
183
+ {#- ===== SETUP ===== -#}
184
+ {%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}
185
+ {%- set loop_messages = messages -%}
186
+ {%- set enable_thinking = enable_thinking | default(false) -%}
187
+ {%- set preserve_thinking = preserve_thinking | default(false) -%}
188
+ {{- bos_token -}}
189
+ {#- Handle System/Tool Definitions Block -#}
190
+ {%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%}
191
+ {{- '<|turn>system\n' -}}
192
+ {#- Inject Thinking token at the very top of the FIRST system turn -#}
193
+ {%- if enable_thinking -%}
194
+ {{- '<|think|>\n' -}}
195
+ {%- set ns.prev_message_type = 'think' -%}
196
+ {%- endif -%}
197
+ {%- if messages and messages[0]['role'] in ['system', 'developer'] -%}
198
+ {%- if messages[0]['content'] is string -%}
199
+ {{- messages[0]['content'] | trim -}}
200
+ {%- elif messages[0]['content'] is sequence -%}
201
+ {%- for item in messages[0]['content'] -%}
202
+ {{- item['text'] | trim + ' '-}}
203
+ {%- endfor -%}
204
+ {%- endif -%}
205
+ {%- set loop_messages = messages[1:] -%}
206
+ {%- endif -%}
207
+ {%- if tools -%}
208
+ {%- for tool in tools %}
209
+ {{- '<|tool>' -}}
210
+ {{- format_function_declaration(tool) | trim -}}
211
+ {{- '<tool|>' -}}
212
+ {%- endfor %}
213
+ {%- set ns.prev_message_type = 'tool' -%}
214
+ {%- endif -%}
215
+ {{- '<turn|>\n' -}}
216
+ {%- endif %}
217
+
218
+ {#- Pre-scan: find last user message index for reasoning guard -#}
219
+ {%- set ns_turn = namespace(last_user_idx=-1) -%}
220
+ {%- for i in range(loop_messages | length) -%}
221
+ {%- if loop_messages[i]['role'] == 'user' -%}
222
+ {%- set ns_turn.last_user_idx = i -%}
223
+ {%- endif -%}
224
+ {%- endfor -%}
225
+
226
+ {#- Loop through messages -#}
227
+ {%- for message in loop_messages -%}
228
+ {%- if message['role'] != 'tool' -%}
229
+ {%- set ns.prev_message_type = None -%}
230
+ {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}
231
+ {#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#}
232
+ {%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%}
233
+ {%- if not continue_same_model_turn -%}
234
+ {{- '<|turn>' + role + '\n' }}
235
+ {%- endif -%}
236
+
237
+ {#- Render reasoning/reasoning_content as thinking channel -#}
238
+ {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}
239
+ {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%}
240
+ {%- if thinking_text and thinking_gate -%}
241
+ {{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}}
242
+ {%- endif -%}
243
+
244
+ {%- if message.get('tool_calls') -%}
245
+ {%- for tool_call in message.get('tool_calls') -%}
246
+ {%- set function = tool_call['function'] -%}
247
+ {{- '<|tool_call>call:' + function['name'] + '{' -}}
248
+ {%- if function['arguments'] is mapping -%}
249
+ {%- set ns_args = namespace(found_first=false) -%}
250
+ {%- for key, value in function['arguments'] | dictsort -%}
251
+ {%- if ns_args.found_first %},{% endif -%}
252
+ {%- set ns_args.found_first = true -%}
253
+ {{- key -}}:{{- format_argument(value, escape_keys=False) -}}
254
+ {%- endfor -%}
255
+ {%- elif function['arguments'] is none -%}
256
+ {%- else -%}
257
+ {{- raise_exception(
258
+ "chat_template: tool_calls[].function.arguments must be a "
259
+ "JSON object (mapping), not a string. Deserialize arguments "
260
+ "before passing to the template."
261
+ ) -}}
262
+ {%- endif -%}
263
+ {{- '}<tool_call|>' -}}
264
+ {%- endfor -%}
265
+ {%- set ns.prev_message_type = 'tool_call' -%}
266
+ {%- endif -%}
267
+
268
+ {%- set ns_tr_out = namespace(flag=false) -%}
269
+ {%- if message.get('tool_responses') -%}
270
+ {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#}
271
+ {%- for tool_response in message.get('tool_responses') -%}
272
+ {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}}
273
+ {%- set ns_tr_out.flag = true -%}
274
+ {%- set ns.prev_message_type = 'tool_response' -%}
275
+ {%- endfor -%}
276
+ {%- elif message.get('tool_calls') -%}
277
+ {#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#}
278
+ {%- set ns_tool_scan = namespace(stopped=false) -%}
279
+ {%- for k in range(loop.index0 + 1, loop_messages | length) -%}
280
+ {%- if ns_tool_scan.stopped -%}
281
+ {%- elif loop_messages[k]['role'] != 'tool' -%}
282
+ {%- set ns_tool_scan.stopped = true -%}
283
+ {%- else -%}
284
+ {%- set follow = loop_messages[k] -%}
285
+ {#- Resolve tool_call_id to function name -#}
286
+ {%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%}
287
+ {%- for tc in message.get('tool_calls') -%}
288
+ {%- if tc.get('id') == follow.get('tool_call_id') -%}
289
+ {%- set ns_tname.name = tc['function']['name'] -%}
290
+ {%- endif -%}
291
+ {%- endfor -%}
292
+ {#- Handle content as string or content-parts array -#}
293
+ {%- set tool_body = follow.get('content') -%}
294
+ {%- if tool_body is string -%}
295
+ {{- format_tool_response_block(ns_tname.name, tool_body) -}}
296
+ {%- elif tool_body is sequence and tool_body is not string -%}
297
+ {%- set ns_txt = namespace(s='') -%}
298
+ {%- for part in tool_body -%}
299
+ {%- if part.get('type') == 'text' -%}
300
+ {%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%}
301
+ {%- endif -%}
302
+ {%- endfor -%}
303
+ {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}}
304
+ {%- for part in tool_body -%}
305
+ {%- if part.get('type') in ['image', 'image_url'] -%}
306
+ {{- '<|image|>' -}}
307
+ {%- elif part.get('type') in ['audio', 'input_audio'] -%}
308
+ {{- '<|audio|>' -}}
309
+ {%- elif part.get('type') == 'video' -%}
310
+ {{- '<|video|>' -}}
311
+ {%- endif -%}
312
+ {%- endfor -%}
313
+ {%- else -%}
314
+ {{- format_tool_response_block(ns_tname.name, tool_body) -}}
315
+ {%- endif -%}
316
+ {%- set ns_tr_out.flag = true -%}
317
+ {%- set ns.prev_message_type = 'tool_response' -%}
318
+ {%- endif -%}
319
+ {%- endfor -%}
320
+ {%- endif -%}
321
+
322
+ {%- set captured_content -%}
323
+ {%- if message.get('content') is string -%}
324
+ {%- if role == 'model' -%}
325
+ {{- strip_thinking(message['content']) -}}
326
+ {%- else -%}
327
+ {{- message['content'] | trim -}}
328
+ {%- endif -%}
329
+ {%- elif message.get('content') is sequence -%}
330
+ {%- for item in message['content'] -%}
331
+ {%- if item.get('type') == 'text' -%}
332
+ {%- if role == 'model' -%}
333
+ {{- strip_thinking(item['text']) -}}
334
+ {%- else -%}
335
+ {{- item['text'] | trim -}}
336
+ {%- endif -%}
337
+ {%- elif item.get('type') in ['image', 'image_url'] -%}
338
+ {{- '<|image|>' -}}
339
+ {%- elif item.get('type') in ['audio', 'input_audio'] -%}
340
+ {{- '<|audio|>' -}}
341
+ {%- elif item.get('type') == 'video' -%}
342
+ {{- '<|video|>' -}}
343
+ {%- endif -%}
344
+ {%- endfor -%}
345
+ {%- endif -%}
346
+ {%- endset -%}
347
+
348
+ {{- captured_content -}}
349
+ {%- set has_content = captured_content | trim | length > 0 -%}
350
+
351
+ {#- Forward-scan: find next non-tool message role for continuation detection -#}
352
+ {%- set next_nt = namespace(role=None, found=false) -%}
353
+ {%- for j in range(loop.index0 + 1, loop_messages | length) -%}
354
+ {%- if not next_nt.found -%}
355
+ {%- if loop_messages[j]['role'] != 'tool' -%}
356
+ {%- set next_nt.role = loop_messages[j]['role'] -%}
357
+ {%- set next_nt.found = true -%}
358
+ {%- endif -%}
359
+ {%- endif -%}
360
+ {%- endfor -%}
361
+
362
+ {%- set continues_into_next = (
363
+ role == 'model'
364
+ and next_nt.role == 'assistant'
365
+ and (not message.get('tool_calls') or ns_tr_out.flag)
366
+ ) -%}
367
+
368
+ {%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}
369
+ {{- '<|tool_response>' -}}
370
+ {%- elif continues_into_next -%}
371
+ {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%}
372
+ {{- '<turn|>\n' -}}
373
+ {%- endif -%}
374
+
375
+ {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#}
376
+ {%- set ns.prev_non_tool_role = message['role'] -%}
377
+ {%- endif -%}
378
+ {%- endfor -%}
379
+
380
+ {%- if add_generation_prompt -%}
381
+ {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}
382
+ {{- '<|turn>model\n' -}}
383
+ {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%}
384
+ {{- '<|channel>thought\n' -}}
385
+ {%- endif -%}
386
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MonarchGemma4ForConditionalGeneration"
4
+ ],
5
+ "audio_config": {
6
+ "_name_or_path": "",
7
+ "architectures": null,
8
+ "attention_chunk_size": 12,
9
+ "attention_context_left": 13,
10
+ "attention_context_right": 0,
11
+ "attention_invalid_logits_value": -1000000000.0,
12
+ "attention_logit_cap": 50.0,
13
+ "chunk_size_feed_forward": 0,
14
+ "conv_kernel_size": 5,
15
+ "dtype": "bfloat16",
16
+ "gradient_clipping": 10000000000.0,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 1024,
19
+ "id2label": {
20
+ "0": "LABEL_0",
21
+ "1": "LABEL_1"
22
+ },
23
+ "initializer_range": 0.02,
24
+ "is_encoder_decoder": false,
25
+ "label2id": {
26
+ "LABEL_0": 0,
27
+ "LABEL_1": 1
28
+ },
29
+ "model_type": "gemma4_audio",
30
+ "num_attention_heads": 8,
31
+ "num_hidden_layers": 12,
32
+ "output_attentions": false,
33
+ "output_hidden_states": false,
34
+ "output_proj_dims": 1536,
35
+ "problem_type": null,
36
+ "residual_weight": 0.5,
37
+ "return_dict": true,
38
+ "rms_norm_eps": 1e-06,
39
+ "subsampling_conv_channels": [
40
+ 128,
41
+ 32
42
+ ],
43
+ "use_clipped_linears": true
44
+ },
45
+ "audio_token_id": 258881,
46
+ "auto_map": {
47
+ "AutoConfig": "configuration_monarch_gemma4.MonarchGemma4Config",
48
+ "AutoModelForImageTextToText": "modeling_monarch_gemma4.MonarchGemma4ForConditionalGeneration"
49
+ },
50
+ "boa_token_id": 256000,
51
+ "boi_token_id": 255999,
52
+ "dtype": "bfloat16",
53
+ "eoa_token_id": 258883,
54
+ "eoa_token_index": 258883,
55
+ "eoi_token_id": 258882,
56
+ "eos_token_id": [
57
+ 1,
58
+ 106
59
+ ],
60
+ "image_token_id": 258880,
61
+ "initializer_range": 0.02,
62
+ "model_type": "monarch_gemma4",
63
+ "monarch_base_model": "google/gemma-4-E2B-it",
64
+ "monarch_blocks_weights": 128,
65
+ "monarch_compressed_layers": [
66
+ 34,
67
+ 33,
68
+ 32,
69
+ 31,
70
+ 30,
71
+ 29,
72
+ 28,
73
+ 27,
74
+ 26,
75
+ 25,
76
+ 24,
77
+ 23,
78
+ 22,
79
+ 21,
80
+ 20,
81
+ 19,
82
+ 18,
83
+ 17,
84
+ 16,
85
+ 15,
86
+ 14,
87
+ 13,
88
+ 12,
89
+ 11,
90
+ 10,
91
+ 9,
92
+ 8,
93
+ 7,
94
+ 6,
95
+ 5,
96
+ 4,
97
+ 3,
98
+ 2,
99
+ 1,
100
+ 0
101
+ ],
102
+ "monarch_factor_count": 2,
103
+ "monarch_format_version": 1,
104
+ "text_config": {
105
+ "attention_bias": false,
106
+ "attention_dropout": 0.0,
107
+ "attention_k_eq_v": false,
108
+ "bos_token_id": 2,
109
+ "dtype": "bfloat16",
110
+ "enable_moe_block": false,
111
+ "eos_token_id": 1,
112
+ "expert_intermediate_size": null,
113
+ "final_logit_softcapping": 30.0,
114
+ "global_head_dim": 512,
115
+ "head_dim": 256,
116
+ "hidden_activation": "gelu_pytorch_tanh",
117
+ "hidden_size": 1536,
118
+ "hidden_size_per_layer_input": 256,
119
+ "initializer_range": 0.02,
120
+ "intermediate_size": 6144,
121
+ "layer_types": [
122
+ "sliding_attention",
123
+ "sliding_attention",
124
+ "sliding_attention",
125
+ "sliding_attention",
126
+ "full_attention",
127
+ "sliding_attention",
128
+ "sliding_attention",
129
+ "sliding_attention",
130
+ "sliding_attention",
131
+ "full_attention",
132
+ "sliding_attention",
133
+ "sliding_attention",
134
+ "sliding_attention",
135
+ "sliding_attention",
136
+ "full_attention",
137
+ "sliding_attention",
138
+ "sliding_attention",
139
+ "sliding_attention",
140
+ "sliding_attention",
141
+ "full_attention",
142
+ "sliding_attention",
143
+ "sliding_attention",
144
+ "sliding_attention",
145
+ "sliding_attention",
146
+ "full_attention",
147
+ "sliding_attention",
148
+ "sliding_attention",
149
+ "sliding_attention",
150
+ "sliding_attention",
151
+ "full_attention",
152
+ "sliding_attention",
153
+ "sliding_attention",
154
+ "sliding_attention",
155
+ "sliding_attention",
156
+ "full_attention"
157
+ ],
158
+ "max_position_embeddings": 131072,
159
+ "model_type": "gemma4_text",
160
+ "moe_intermediate_size": null,
161
+ "num_attention_heads": 8,
162
+ "num_experts": null,
163
+ "num_global_key_value_heads": null,
164
+ "num_hidden_layers": 35,
165
+ "num_key_value_heads": 1,
166
+ "num_kv_shared_layers": 20,
167
+ "pad_token_id": 0,
168
+ "rms_norm_eps": 1e-06,
169
+ "rope_parameters": {
170
+ "full_attention": {
171
+ "partial_rotary_factor": 0.25,
172
+ "rope_theta": 1000000.0,
173
+ "rope_type": "proportional"
174
+ },
175
+ "sliding_attention": {
176
+ "rope_theta": 10000.0,
177
+ "rope_type": "default"
178
+ }
179
+ },
180
+ "sliding_window": 512,
181
+ "tie_word_embeddings": true,
182
+ "top_k_experts": null,
183
+ "use_bidirectional_attention": null,
184
+ "use_cache": true,
185
+ "use_double_wide_mlp": true,
186
+ "vocab_size": 262144,
187
+ "vocab_size_per_layer_input": 262144
188
+ },
189
+ "tie_word_embeddings": true,
190
+ "transformers_version": "5.13.1",
191
+ "video_token_id": 258884,
192
+ "vision_config": {
193
+ "_name_or_path": "",
194
+ "architectures": null,
195
+ "attention_bias": false,
196
+ "attention_dropout": 0.0,
197
+ "chunk_size_feed_forward": 0,
198
+ "default_output_length": 280,
199
+ "dtype": "bfloat16",
200
+ "global_head_dim": 64,
201
+ "head_dim": 64,
202
+ "hidden_activation": "gelu_pytorch_tanh",
203
+ "hidden_size": 768,
204
+ "id2label": {
205
+ "0": "LABEL_0",
206
+ "1": "LABEL_1"
207
+ },
208
+ "initializer_range": 0.02,
209
+ "intermediate_size": 3072,
210
+ "is_encoder_decoder": false,
211
+ "label2id": {
212
+ "LABEL_0": 0,
213
+ "LABEL_1": 1
214
+ },
215
+ "max_position_embeddings": 131072,
216
+ "model_type": "gemma4_vision",
217
+ "num_attention_heads": 12,
218
+ "num_hidden_layers": 16,
219
+ "num_key_value_heads": 12,
220
+ "output_attentions": false,
221
+ "output_hidden_states": false,
222
+ "patch_size": 16,
223
+ "pooling_kernel_size": 3,
224
+ "position_embedding_size": 10240,
225
+ "problem_type": null,
226
+ "return_dict": true,
227
+ "rms_norm_eps": 1e-06,
228
+ "rope_parameters": {
229
+ "rope_theta": 100.0,
230
+ "rope_type": "default"
231
+ },
232
+ "standardize": false,
233
+ "use_clipped_linears": true
234
+ },
235
+ "vision_soft_tokens_per_image": 280
236
+ }
configuration_monarch_gemma4.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Gemma4Config
2
+
3
+
4
+ class MonarchGemma4Config(Gemma4Config):
5
+ """Gemma 4 configuration with selected MLPs replaced by Monarch factors."""
6
+
7
+ model_type = "monarch_gemma4"
8
+
9
+ def __init__(
10
+ self,
11
+ monarch_compressed_layers=None,
12
+ monarch_blocks_weights=128,
13
+ monarch_factor_count=2,
14
+ monarch_format_version=1,
15
+ monarch_base_model="google/gemma-4-E2B-it",
16
+ **kwargs,
17
+ ):
18
+ super().__init__(**kwargs)
19
+ self.monarch_compressed_layers = list(monarch_compressed_layers or [])
20
+ self.monarch_blocks_weights = int(monarch_blocks_weights)
21
+ self.monarch_factor_count = int(monarch_factor_count)
22
+ self.monarch_format_version = int(monarch_format_version)
23
+ self.monarch_base_model = str(monarch_base_model)
24
+
25
+ if self.monarch_factor_count != 2:
26
+ raise ValueError("this model format supports exactly two Monarch factors")
27
+ if len(set(self.monarch_compressed_layers)) != len(self.monarch_compressed_layers):
28
+ raise ValueError("monarch_compressed_layers contains duplicate layer indices")
export_manifest.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "google/gemma-4-E2B-it",
3
+ "compressed_layers": [
4
+ 34,
5
+ 33,
6
+ 32,
7
+ 31,
8
+ 30,
9
+ 29,
10
+ 28,
11
+ 27,
12
+ 26,
13
+ 25,
14
+ 24,
15
+ 23,
16
+ 22,
17
+ 21,
18
+ 20,
19
+ 19,
20
+ 18,
21
+ 17,
22
+ 16,
23
+ 15,
24
+ 14,
25
+ 13,
26
+ 12,
27
+ 11,
28
+ 10,
29
+ 9,
30
+ 8,
31
+ 7,
32
+ 6,
33
+ 5,
34
+ 4,
35
+ 3,
36
+ 2,
37
+ 1,
38
+ 0
39
+ ],
40
+ "monarch_blocks_weights": 128,
41
+ "monarch_factor_count": 2,
42
+ "parameter_count": 3682268704,
43
+ "checkpoint": "monarch_checkpoints_b8_all35mlp_400p1_800p2_seq512_projinit_p2lr3e4/step_034_model_language_model_layers_0_mlp/unfrozen_weights.pt"
44
+ }
generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 2,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 1,
6
+ 106,
7
+ 50
8
+ ],
9
+ "pad_token_id": 0,
10
+ "temperature": 1.0,
11
+ "top_k": 64,
12
+ "top_p": 0.95,
13
+ "transformers_version": "5.13.1"
14
+ }
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ea02bad44856b48a53786446e9d32217ea9c377b26d16032919b8785c2b87be
3
+ size 4697620648
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5edeb987bdf1f8fa2ab6f82144790a5131236f746ad38289c9940e9f643b94eb
3
+ size 2667187158
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_monarch_gemma4.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import Gemma4ForConditionalGeneration
2
+
3
+ from .configuration_monarch_gemma4 import MonarchGemma4Config
4
+ from .monarch import replace_linear_with_monarch
5
+
6
+
7
+ class MonarchGemma4ForConditionalGeneration(Gemma4ForConditionalGeneration):
8
+ """Gemma 4 with configured language-model MLPs stored as Monarch factors."""
9
+
10
+ config_class = MonarchGemma4Config
11
+
12
+ def __init__(self, config: MonarchGemma4Config):
13
+ super().__init__(config)
14
+ layers = self.model.language_model.layers
15
+ for layer_index in config.monarch_compressed_layers:
16
+ if layer_index < 0 or layer_index >= len(layers):
17
+ raise ValueError(
18
+ f"compressed layer index {layer_index} is outside the language model's "
19
+ f"0..{len(layers) - 1} range"
20
+ )
21
+ replace_linear_with_monarch(
22
+ layers[layer_index].mlp,
23
+ config.monarch_blocks_weights,
24
+ init_method="identity_noise",
25
+ module_path=f"model.language_model.layers.{layer_index}.mlp",
26
+ )
monarch.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ class MonarchLinear(nn.Module):
8
+ def __init__(self, in_features, out_features, n_blocks, bias=True):
9
+ super().__init__()
10
+ self.in_features = in_features
11
+ self.out_features = out_features
12
+ self.is_down_proj = out_features < in_features
13
+
14
+ if not self.is_down_proj:
15
+ self.n1 = n_blocks
16
+ assert in_features % self.n1 == 0, f"in_features ({in_features}) must be divisible by n_blocks ({n_blocks})"
17
+ self.n2 = in_features // self.n1
18
+ assert out_features % self.n2 == 0, f"out_features ({out_features}) must be divisible by in_block_size ({self.n2})"
19
+ self.n3 = out_features // self.n2
20
+ else:
21
+ self.n3 = n_blocks
22
+ assert out_features % self.n3 == 0, f"out_features ({out_features}) must be divisible by n_blocks ({n_blocks})"
23
+ self.n2 = out_features // self.n3
24
+ assert in_features % self.n2 == 0, f"in_features ({in_features}) must be divisible by out_block_size ({self.n2})"
25
+ self.n1 = in_features // self.n2
26
+
27
+ self.blk1 = nn.Parameter(torch.empty(self.n1, self.n2, self.n2))
28
+ self.blk2 = nn.Parameter(torch.empty(self.n2, self.n1, self.n3))
29
+ self.bias = nn.Parameter(torch.empty(out_features)) if bias else None
30
+ self.reset_parameters()
31
+
32
+ def reset_parameters(self):
33
+ # Hugging Face constructs modules on the meta device for low-memory loading.
34
+ # The serialized factors materialize them later, so there is nothing to initialize yet.
35
+ if self.blk1.is_meta:
36
+ return
37
+
38
+ nn.init.zeros_(self.blk1)
39
+ nn.init.zeros_(self.blk2)
40
+
41
+ for i in range(self.blk1.shape[0]):
42
+ self.blk1.data[i].copy_(torch.eye(self.blk1.shape[1]))
43
+
44
+ for i in range(self.blk2.shape[0]):
45
+ min_dim = min(self.blk2.shape[1], self.blk2.shape[2])
46
+ self.blk2.data[i, :min_dim, :min_dim].copy_(torch.eye(min_dim))
47
+
48
+ if self.blk2.shape[1] != self.blk2.shape[2]:
49
+ with torch.no_grad():
50
+ bound = 1.0 / (min_dim ** 0.5)
51
+ noise = torch.FloatTensor(self.blk2.shape[1], self.blk2.shape[2]).uniform_(-bound, bound)
52
+ mask = torch.ones(self.blk2.shape[1], self.blk2.shape[2])
53
+ mask[:min_dim, :min_dim] -= torch.eye(min_dim)
54
+ self.blk2.data[i] += (noise * mask).to(self.blk2.device)
55
+
56
+ if self.bias is not None:
57
+ nn.init.zeros_(self.bias)
58
+
59
+ @torch.no_grad()
60
+ def initialize_from_dense(self, dense_layer: nn.Linear) -> float:
61
+ """Project a dense linear map onto this rectangular Monarch layout."""
62
+ if dense_layer.in_features != self.in_features or dense_layer.out_features != self.out_features:
63
+ raise ValueError(
64
+ "dense layer shape does not match Monarch layer: "
65
+ f"got ({dense_layer.out_features}, {dense_layer.in_features}), "
66
+ f"expected ({self.out_features}, {self.in_features})"
67
+ )
68
+
69
+ weight = dense_layer.weight.detach().to(device=self.blk1.device, dtype=torch.float32)
70
+ slices = (
71
+ weight.reshape(self.n3, self.n2, self.n1, self.n2)
72
+ .permute(1, 2, 0, 3)
73
+ .contiguous()
74
+ )
75
+ left_vectors, singular_values, right_vectors_h = torch.linalg.svd(slices, full_matrices=False)
76
+
77
+ scales = singular_values[..., 0].clamp_min(0.0).sqrt()
78
+ projected_blk2 = left_vectors[..., :, 0] * scales.unsqueeze(-1)
79
+ projected_blk1 = right_vectors_h[..., 0, :] * scales.unsqueeze(-1)
80
+
81
+ self.blk1.copy_(projected_blk1.permute(1, 2, 0).to(dtype=self.blk1.dtype))
82
+ self.blk2.copy_(projected_blk2.to(dtype=self.blk2.dtype))
83
+
84
+ if self.bias is not None:
85
+ if dense_layer.bias is None:
86
+ self.bias.zero_()
87
+ else:
88
+ self.bias.copy_(dense_layer.bias.detach().to(device=self.bias.device, dtype=self.bias.dtype))
89
+
90
+ squared_singular_values = singular_values.square()
91
+ total_energy = squared_singular_values.sum()
92
+ residual_energy = squared_singular_values[..., 1:].sum()
93
+ if total_energy.item() == 0.0:
94
+ return 0.0
95
+ return (residual_energy / total_energy).clamp_min(0.0).sqrt().item()
96
+
97
+ def forward(self, x):
98
+ orig_shape = x.shape
99
+ x = x.contiguous().view(-1, self.n1, self.n2)
100
+ x = torch.einsum("bij, ijk -> bik", x, self.blk1)
101
+ x = x.transpose(1, 2).contiguous()
102
+ x = torch.einsum("bij, ijk -> bik", x, self.blk2)
103
+ x = x.transpose(1, 2).contiguous()
104
+ x = x.view(*orig_shape[:-1], self.out_features)
105
+
106
+ if self.bias is not None:
107
+ x = x + self.bias
108
+
109
+ return x
110
+
111
+
112
+ class MonarchEmbedding(nn.Module):
113
+ def __init__(self, num_embeddings, embedding_dim, n_blocks):
114
+ super().__init__()
115
+ self.num_embeddings = num_embeddings
116
+ self.embedding_dim = embedding_dim
117
+
118
+ self.n1 = n_blocks
119
+ assert num_embeddings % self.n1 == 0, "num_embeddings must be divisible by n_blocks"
120
+ self.n2 = num_embeddings // self.n1
121
+
122
+ assert embedding_dim % self.n2 == 0, f"embedding_dim ({embedding_dim}) must be divisible by in_block_size ({self.n2})"
123
+ self.n3 = embedding_dim // self.n2
124
+
125
+ self.blk1 = nn.Parameter(torch.empty(self.n1, self.n2, self.n2))
126
+ self.blk2 = nn.Parameter(torch.empty(self.n2, self.n1, self.n3))
127
+ self.reset_parameters()
128
+
129
+ def reset_parameters(self):
130
+ nn.init.normal_(self.blk1, mean=0, std=1 / math.sqrt(self.n2))
131
+ nn.init.normal_(self.blk2, mean=0, std=1 / math.sqrt(self.n1))
132
+
133
+ def forward(self, x):
134
+ blk1_flat = self.blk1.view(self.num_embeddings, self.n2)
135
+ v1 = blk1_flat[x]
136
+
137
+ block_idx = x // self.n2
138
+ blk2_transposed = self.blk2.transpose(0, 1)
139
+ w2_selected = blk2_transposed[block_idx]
140
+
141
+ out_matrix = v1.unsqueeze(-1) * w2_selected
142
+ out = out_matrix.transpose(-1, -2).contiguous()
143
+ out = out.view(*x.shape, self.embedding_dim)
144
+ return out
145
+
146
+
147
+ def replace_linear_with_monarch(module, blocks, init_method="identity_noise", module_path=""):
148
+ for name, child in module.named_children():
149
+ child_path = f"{module_path}.{name}" if module_path else name
150
+ if isinstance(child, nn.Linear):
151
+ device = child.weight.device
152
+ dtype = child.weight.dtype
153
+ monarch_layer = MonarchLinear(child.in_features, child.out_features, blocks, bias=child.bias is not None)
154
+ monarch_layer = monarch_layer.to(device=device, dtype=dtype)
155
+ if init_method == "dense_projection":
156
+ relative_error = monarch_layer.initialize_from_dense(child)
157
+ print(f"[Projection] {child_path} | relative Frobenius error: {relative_error:.6f}")
158
+ elif init_method != "identity_noise":
159
+ raise ValueError(f"unsupported Monarch initialization method: {init_method}")
160
+ setattr(module, name, monarch_layer)
161
+ else:
162
+ replace_linear_with_monarch(child, blocks, init_method=init_method, module_path=child_path)
163
+ return module
164
+
165
+
166
+ def replace_with_monarch(
167
+ student_model,
168
+ module_path: str,
169
+ blocks_weights: int,
170
+ blocks_head: int,
171
+ init_method: str = "identity_noise",
172
+ ):
173
+ parent_path = ".".join(module_path.split(".")[:-1])
174
+ child_name = module_path.split(".")[-1]
175
+
176
+ parent_module = student_model if parent_path == "" else student_model.get_submodule(parent_path)
177
+ old_module = getattr(parent_module, child_name)
178
+
179
+ if module_path == "lm_head":
180
+ device, dtype = old_module.weight.device, old_module.weight.dtype
181
+ new_head = MonarchLinear(old_module.in_features, old_module.out_features, blocks_head, bias=old_module.bias is not None)
182
+ new_head = new_head.to(device=device, dtype=dtype)
183
+ if init_method == "dense_projection":
184
+ relative_error = new_head.initialize_from_dense(old_module)
185
+ print(f"[Projection] {module_path} | relative Frobenius error: {relative_error:.6f}")
186
+ elif init_method != "identity_noise":
187
+ raise ValueError(f"unsupported Monarch initialization method: {init_method}")
188
+ setattr(parent_module, child_name, new_head)
189
+ return getattr(parent_module, child_name)
190
+
191
+ if "embed_tokens" in module_path:
192
+ device, dtype = old_module.weight.device, old_module.weight.dtype
193
+ new_embed = MonarchEmbedding(old_module.num_embeddings, old_module.embedding_dim, blocks_head)
194
+ setattr(parent_module, child_name, new_embed.to(device=device, dtype=dtype))
195
+ return getattr(parent_module, child_name)
196
+
197
+ replace_linear_with_monarch(
198
+ old_module,
199
+ blocks_weights,
200
+ init_method=init_method,
201
+ module_path=module_path,
202
+ )
203
+ return old_module
processor_config.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "audio_ms_per_token": 40,
3
+ "audio_seq_length": 750,
4
+ "feature_extractor": {
5
+ "dither": 0.0,
6
+ "feature_extractor_type": "Gemma4AudioFeatureExtractor",
7
+ "feature_size": 128,
8
+ "fft_length": 512,
9
+ "fft_overdrive": false,
10
+ "frame_length": 320,
11
+ "hop_length": 160,
12
+ "input_scale_factor": 1.0,
13
+ "max_frequency": 8000.0,
14
+ "mel_floor": 0.001,
15
+ "min_frequency": 0.0,
16
+ "padding_side": "right",
17
+ "padding_value": 0.0,
18
+ "per_bin_mean": null,
19
+ "per_bin_stddev": null,
20
+ "preemphasis": 0.0,
21
+ "preemphasis_htk_flavor": true,
22
+ "return_attention_mask": true,
23
+ "sampling_rate": 16000
24
+ },
25
+ "image_processor": {
26
+ "do_convert_rgb": true,
27
+ "do_normalize": false,
28
+ "do_rescale": true,
29
+ "do_resize": true,
30
+ "image_mean": [
31
+ 0.0,
32
+ 0.0,
33
+ 0.0
34
+ ],
35
+ "image_processor_type": "Gemma4ImageProcessor",
36
+ "image_seq_length": 280,
37
+ "image_std": [
38
+ 1.0,
39
+ 1.0,
40
+ 1.0
41
+ ],
42
+ "max_soft_tokens": 280,
43
+ "patch_size": 16,
44
+ "pooling_kernel_size": 3,
45
+ "resample": 3,
46
+ "rescale_factor": 0.00392156862745098
47
+ },
48
+ "image_seq_length": 280,
49
+ "processor_class": "Gemma4Processor",
50
+ "video_processor": {
51
+ "do_convert_rgb": true,
52
+ "do_normalize": true,
53
+ "do_rescale": true,
54
+ "do_resize": true,
55
+ "do_sample_frames": true,
56
+ "image_mean": [
57
+ 0.0,
58
+ 0.0,
59
+ 0.0
60
+ ],
61
+ "image_std": [
62
+ 1.0,
63
+ 1.0,
64
+ 1.0
65
+ ],
66
+ "max_soft_tokens": 70,
67
+ "num_frames": 32,
68
+ "patch_size": 16,
69
+ "pooling_kernel_size": 3,
70
+ "resample": 3,
71
+ "rescale_factor": 0.00392156862745098,
72
+ "return_metadata": false,
73
+ "video_processor_type": "Gemma4VideoProcessor"
74
+ }
75
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f
3
+ size 32169626
tokenizer_config.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "audio_token": "<|audio|>",
3
+ "backend": "tokenizers",
4
+ "boa_token": "<|audio>",
5
+ "boi_token": "<|image>",
6
+ "bos_token": "<bos>",
7
+ "eoa_token": "<audio|>",
8
+ "eoc_token": "<channel|>",
9
+ "eoi_token": "<image|>",
10
+ "eos_token": "<eos>",
11
+ "eot_token": "<turn|>",
12
+ "escape_token": "<|\"|>",
13
+ "etc_token": "<tool_call|>",
14
+ "etd_token": "<tool|>",
15
+ "etr_token": "<tool_response|>",
16
+ "extra_special_tokens": [
17
+ "<|video|>"
18
+ ],
19
+ "image_token": "<|image|>",
20
+ "is_local": false,
21
+ "local_files_only": false,
22
+ "mask_token": "<mask>",
23
+ "model_max_length": 1000000000000000019884624838656,
24
+ "model_specific_special_tokens": {
25
+ "audio_token": "<|audio|>",
26
+ "boa_token": "<|audio>",
27
+ "boi_token": "<|image>",
28
+ "eoa_token": "<audio|>",
29
+ "eoc_token": "<channel|>",
30
+ "eoi_token": "<image|>",
31
+ "eot_token": "<turn|>",
32
+ "escape_token": "<|\"|>",
33
+ "etc_token": "<tool_call|>",
34
+ "etd_token": "<tool|>",
35
+ "etr_token": "<tool_response|>",
36
+ "image_token": "<|image|>",
37
+ "soc_token": "<|channel>",
38
+ "sot_token": "<|turn>",
39
+ "stc_token": "<|tool_call>",
40
+ "std_token": "<|tool>",
41
+ "str_token": "<|tool_response>",
42
+ "think_token": "<|think|>"
43
+ },
44
+ "pad_token": "<pad>",
45
+ "padding_side": "left",
46
+ "processor_class": "Gemma4Processor",
47
+ "response_schema": {
48
+ "properties": {
49
+ "content": {
50
+ "type": "string"
51
+ },
52
+ "role": {
53
+ "const": "assistant"
54
+ },
55
+ "thinking": {
56
+ "type": "string"
57
+ },
58
+ "tool_calls": {
59
+ "items": {
60
+ "properties": {
61
+ "function": {
62
+ "properties": {
63
+ "arguments": {
64
+ "additionalProperties": {},
65
+ "type": "object",
66
+ "x-parser": "gemma4-tool-call"
67
+ },
68
+ "name": {
69
+ "type": "string"
70
+ }
71
+ },
72
+ "type": "object",
73
+ "x-regex": "call\\:(?P<name>\\w+)(?P<arguments>\\{.*\\})"
74
+ },
75
+ "type": {
76
+ "const": "function"
77
+ }
78
+ },
79
+ "type": "object"
80
+ },
81
+ "type": "array",
82
+ "x-regex-iterator": "<\\|tool_call>(.*?)<tool_call\\|>"
83
+ }
84
+ },
85
+ "type": "object",
86
+ "x-regex": "(\\<\\|channel\\>thought\\n(?P<thinking>.*?)\\<channel\\|\\>)?(?P<tool_calls>\\<\\|tool_call\\>.*\\<tool_call\\|\\>)?(?P<content>(?:(?!\\<turn\\|\\>)(?!\\<\\|tool_response\\>).)+)?(?:\\<turn\\|\\>|\\<\\|tool_response\\>)?"
87
+ },
88
+ "soc_token": "<|channel>",
89
+ "sot_token": "<|turn>",
90
+ "stc_token": "<|tool_call>",
91
+ "std_token": "<|tool>",
92
+ "str_token": "<|tool_response>",
93
+ "think_token": "<|think|>",
94
+ "tokenizer_class": "GemmaTokenizer",
95
+ "unk_token": "<unk>"
96
+ }