Initial release: Gemma 4 E2B INT4 .pte for Pi 5 via ExecuTorch
Browse files- .gitattributes +2 -0
- LICENSE +202 -0
- README.md +135 -0
- gemma4_e2b_text_int4_extcache.pte +3 -0
- gemma4_terminal_chat.py +325 -0
- pi_runner.py +209 -0
- tokenizer/chat_template.jinja +360 -0
- tokenizer/tokenizer.json +3 -0
- tokenizer/tokenizer_config.json +74 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ 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 |
+
gemma4_e2b_text_int4_extcache.pte filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
tokenizer/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
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.
|
README.md
CHANGED
|
@@ -1,3 +1,138 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
base_model: google/gemma-4-e2b-it
|
| 6 |
+
tags:
|
| 7 |
+
- executorch
|
| 8 |
+
- quantized
|
| 9 |
+
- int4
|
| 10 |
+
- raspberry-pi
|
| 11 |
+
- on-device
|
| 12 |
+
- edge
|
| 13 |
+
pipeline_tag: text-generation
|
| 14 |
---
|
| 15 |
+
|
| 16 |
+
# Gemma 4 E2B — INT4 ExecuTorch `.pte` for Raspberry Pi 5
|
| 17 |
+
|
| 18 |
+
INT4-quantized, ExecuTorch-lowered `.pte` of [`google/gemma-4-e2b-it`](https://huggingface.co/google/gemma-4-e2b-it), packaged for **Raspberry Pi 5 (Cortex-A76, 8 GB)** deployment via the [ExecuTorch](https://pytorch.org/executorch) 1.2.0 Python runtime with the XNNPACK backend.
|
| 19 |
+
|
| 20 |
+
This artifact is the deployable output of the full export → quantize → lower → runtime recipe documented at:
|
| 21 |
+
|
| 22 |
+
**Source code & full recipe:** https://github.com/bamb00boy/Gemma4_executorch_deployment
|
| 23 |
+
|
| 24 |
+
## Contents
|
| 25 |
+
|
| 26 |
+
| File | Size | Purpose |
|
| 27 |
+
|---|---|---|
|
| 28 |
+
| `gemma4_e2b_text_int4_extcache.pte` | 5.14 GB | The ExecuTorch program — load + run with `executorch==1.2.0` |
|
| 29 |
+
| `tokenizer/tokenizer.json` | ~5 MB | HF fast tokenizer for Gemma 4 |
|
| 30 |
+
| `tokenizer/tokenizer_config.json` | small | Tokenizer config (special tokens, chat template ref) |
|
| 31 |
+
| `tokenizer/chat_template.jinja` | small | Gemma 4 chat template (used by `gemma4_terminal_chat.py`) |
|
| 32 |
+
| `pi_runner.py` | ~250 lines | Self-contained one-shot runner: tokenize → generate → exit |
|
| 33 |
+
| `gemma4_terminal_chat.py` | ~325 lines | Interactive multi-turn REPL with KV-cache reuse across turns |
|
| 34 |
+
| `LICENSE` | — | Apache 2.0 (covers the weights; see [License](#license) below) |
|
| 35 |
+
|
| 36 |
+
## Measured performance
|
| 37 |
+
|
| 38 |
+
Identical 14-token prompt + 9-token decode for `"The capital of France is"`, bit-exact output across all rows.
|
| 39 |
+
|
| 40 |
+
| Host | Role | Prompt feed | Decode | Total wall |
|
| 41 |
+
|---|---|---|---|---|
|
| 42 |
+
| **Raspberry Pi 5** — 8 GB, Cortex-A76 @ 2.4 GHz, Ubuntu Server 24.04 LTS, microSD | deployment target | 0.77 tok/s | **0.87 tok/s** | 28.6 s |
|
| 43 |
+
| **MacBook Pro 14"** — Apple M1 Pro (6P+2E), 16 GB unified, macOS 26.3.1 | development reference | 7.20 tok/s | **8.66 tok/s** | 2.99 s |
|
| 44 |
+
| [potato-os/core llama.cpp on Pi 5](https://github.com/potato-os/core/blob/main/docs/benchmarks/gemma4-pi-benchmark-2026-04-04.md) | external reference (different runtime) | n/a | **6.71 tok/s** | n/a |
|
| 45 |
+
|
| 46 |
+
**Output quality:** bit-exact 9/9 token match against the FP32 reference on the canonical prompt.
|
| 47 |
+
|
| 48 |
+
The Pi 5 decode is approximately 7.7× slower than `llama.cpp` on identical hardware. The cause is fully attributable to a known ARM-side XNNPACK bug in ExecuTorch 1.2.0 that forces the `XnnpackPartitioner(per_op_mode=True)` workaround, which neutralizes the fused-subgraph path that KleidiAI's INT4 matmul fast-path depends on. Full diagnosis at [KNOWN_ISSUES.md #1](https://github.com/bamb00boy/Gemma4_executorch_deployment/blob/master/KNOWN_ISSUES.md) in the source repo. If maximum Pi 5 decode throughput is the priority, `llama.cpp` is the appropriate tool today.
|
| 49 |
+
|
| 50 |
+
## Quick use on a Raspberry Pi 5
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
# 1. Download the bundle (~5.2 GB)
|
| 54 |
+
pip install --user huggingface_hub
|
| 55 |
+
hf download bamb00boy/gemma4-e2b-int4-executorch-pi5 --local-dir ~/gemma4
|
| 56 |
+
|
| 57 |
+
# 2. Set up the runtime environment
|
| 58 |
+
cd ~/gemma4
|
| 59 |
+
python3 -m venv .venv && source .venv/bin/activate
|
| 60 |
+
pip install --upgrade pip
|
| 61 |
+
pip install torch==2.11.0 executorch==1.2.0 transformers==5.5.3
|
| 62 |
+
|
| 63 |
+
# 3. Verify (should print "RESULT: PASS" and "The capital of France is **Paris**.")
|
| 64 |
+
python pi_runner.py --verify
|
| 65 |
+
|
| 66 |
+
# 4a. One-shot generation
|
| 67 |
+
python pi_runner.py "Your prompt here" --max-new-tokens 50
|
| 68 |
+
|
| 69 |
+
# 4b. Or an interactive multi-turn chat (KV-cache reused across turns)
|
| 70 |
+
python gemma4_terminal_chat.py
|
| 71 |
+
# Type a message + Enter. /help for commands. Ctrl+C or Ctrl+D to exit.
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
The Pi setup guide (OS install, performance tuning, SSH) lives in [docs/pi5_setup.md](https://github.com/bamb00boy/Gemma4_executorch_deployment/blob/master/docs/pi5_setup.md) in the source repo.
|
| 75 |
+
|
| 76 |
+
## Use on other hosts
|
| 77 |
+
|
| 78 |
+
The `.pte` runs on any host with ExecuTorch 1.2.0 + XNNPACK. It has been validated on:
|
| 79 |
+
|
| 80 |
+
- aarch64 Linux (Raspberry Pi 5, Ubuntu Server 24.04)
|
| 81 |
+
- macOS arm64 (Apple Silicon, used as the development reference)
|
| 82 |
+
|
| 83 |
+
x86_64 Linux is expected to work (XNNPACK supports it) but is untested by this project.
|
| 84 |
+
|
| 85 |
+
## What's quantized, what's not
|
| 86 |
+
|
| 87 |
+
| Component | Treatment |
|
| 88 |
+
|---|---|
|
| 89 |
+
| `nn.Linear` weights (~3.1 B params) | INT4 weight-only via torchao's `Int8DynamicActivationIntxWeightConfig` (stored unpacked as INT8 bytes on disk) |
|
| 90 |
+
| `embed_tokens_per_layer` (~2.35 B params, the "E2B" trick) | INT8 per-row via a hand-rolled `Int8Embedding` module (see source repo's `scripts/_int8_embedding.py`) |
|
| 91 |
+
| `embed_tokens` (~0.4 B params) | FP32 — Gemma 4's model code performs direct weight slicing, which is incompatible with quantized tensor wrappers |
|
| 92 |
+
| Layer norms, RoPE buffers, biases | FP32 |
|
| 93 |
+
| Runtime K/V cache | FP32, externalized as program inputs/outputs (see source repo's `scripts/_external_cache.py`) |
|
| 94 |
+
|
| 95 |
+
Disk size: 5.14 GB. Runtime cache footprint: 18.9 MB across 15 layers (12 sliding-window @ `head_dim=256`, 3 full-attention @ `head_dim=512`).
|
| 96 |
+
|
| 97 |
+
## Architecture & shape constraints
|
| 98 |
+
|
| 99 |
+
- **Sequence length:** padded to 511 tokens at runtime (the `.pte` shape-specializes to the upper bound of the dynamic dim).
|
| 100 |
+
- **Decode:** token-by-token (no batched prefill in this build).
|
| 101 |
+
- **Maximum total context:** 511 tokens (prompt + generated combined).
|
| 102 |
+
- **Cache:** externalized — 90 cache tensors are passed as graph inputs and 45 are returned as graph outputs each call (one K + one V per layer × 15 layers + sentinel for prefill vs decode).
|
| 103 |
+
|
| 104 |
+
## License
|
| 105 |
+
|
| 106 |
+
The weights in this file are derived from [`google/gemma-4-e2b-it`](https://huggingface.co/google/gemma-4-e2b-it) and are licensed under **Apache License 2.0** by Google DeepMind. Use is subject to:
|
| 107 |
+
|
| 108 |
+
- [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) (text included in this repo as `LICENSE`)
|
| 109 |
+
- [Gemma Prohibited Use Policy](https://ai.google.dev/gemma/prohibited_use_policy)
|
| 110 |
+
- [Gemma 4 Apache 2.0 announcement](https://ai.google.dev/gemma/apache_2)
|
| 111 |
+
|
| 112 |
+
This is a derivative work: INT4 weight-only quantization of `nn.Linear` weights and INT8 per-row quantization of `embed_tokens_per_layer`, followed by ExecuTorch program lowering with the XNNPACK backend. No additional fine-tuning has been performed.
|
| 113 |
+
|
| 114 |
+
The packaging code (`pi_runner.py`, `gemma4_terminal_chat.py`, and the export/quantize/lower pipeline) is released under **MIT** — see the [source GitHub repo](https://github.com/bamb00boy/Gemma4_executorch_deployment).
|
| 115 |
+
|
| 116 |
+
## Attribution
|
| 117 |
+
|
| 118 |
+
```
|
| 119 |
+
Original Gemma 4 weights © Google DeepMind, released under Apache 2.0.
|
| 120 |
+
INT4 quantization + ExecuTorch lowering: derivative work by the
|
| 121 |
+
Gemma4_executorch_deployment contributors (https://github.com/bamb00boy/Gemma4_executorch_deployment).
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
## Citation
|
| 125 |
+
|
| 126 |
+
If this artifact is useful in research, please cite both the original Gemma 4 release and this packaging:
|
| 127 |
+
|
| 128 |
+
```bibtex
|
| 129 |
+
@misc{gemma4-e2b-int4-executorch-pi5,
|
| 130 |
+
title = {Gemma 4 E2B INT4 ExecuTorch for Raspberry Pi 5},
|
| 131 |
+
author = {bamb00boy and Gemma4_executorch_deployment contributors},
|
| 132 |
+
year = {2026},
|
| 133 |
+
url = {https://huggingface.co/bamb00boy/gemma4-e2b-int4-executorch-pi5},
|
| 134 |
+
note = {Source recipe: https://github.com/bamb00boy/Gemma4_executorch_deployment}
|
| 135 |
+
}
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
For the upstream Gemma 4 model, see [`google/gemma-4-e2b-it`](https://huggingface.co/google/gemma-4-e2b-it).
|
gemma4_e2b_text_int4_extcache.pte
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cb5b414c8dda8624a36be998dc3e9816c798bb953f160deee70889867c230543
|
| 3 |
+
size 5139050496
|
gemma4_terminal_chat.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gemma 4 E2B — interactive terminal chat.
|
| 3 |
+
|
| 4 |
+
Self-contained chat REPL that runs the same .pte as pi_runner.py but in
|
| 5 |
+
multi-turn mode. KV-cache is reused across turns — only the *new* tokens
|
| 6 |
+
in each chat round are fed to the model, so latency stays bounded by the
|
| 7 |
+
size of each new user message + the response, not by the cumulative
|
| 8 |
+
conversation length (until cache fills).
|
| 9 |
+
|
| 10 |
+
Dependencies (install once on the deployment host):
|
| 11 |
+
pip install torch==2.11.0 executorch==1.2.0 transformers==5.5.3
|
| 12 |
+
|
| 13 |
+
Expected files in the same directory (or pass --pte / --tokenizer paths):
|
| 14 |
+
gemma4_e2b_text_int4_extcache.pte
|
| 15 |
+
tokenizer/ # tokenizer.json + tokenizer_config.json + chat_template.jinja
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
python gemma4_terminal_chat.py
|
| 19 |
+
python gemma4_terminal_chat.py --max-new-tokens 200
|
| 20 |
+
python gemma4_terminal_chat.py --pte /path/to/.pte --tokenizer /path/to/tokenizer/
|
| 21 |
+
|
| 22 |
+
Controls:
|
| 23 |
+
Type a message + Enter → model replies
|
| 24 |
+
Ctrl+C or Ctrl+D → exit
|
| 25 |
+
/reset → wipe cache + history, start fresh
|
| 26 |
+
/help → show controls
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import os
|
| 31 |
+
import signal
|
| 32 |
+
import sys
|
| 33 |
+
import time
|
| 34 |
+
|
| 35 |
+
import torch
|
| 36 |
+
from transformers import AutoTokenizer
|
| 37 |
+
from executorch.runtime import Runtime, Verification
|
| 38 |
+
|
| 39 |
+
# -------------------- paths + model layout (must match pi_runner.py) --------------------
|
| 40 |
+
|
| 41 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 42 |
+
DEFAULT_PTE = os.path.join(HERE, "gemma4_e2b_text_int4_extcache.pte")
|
| 43 |
+
DEFAULT_TOK = os.path.join(HERE, "tokenizer")
|
| 44 |
+
|
| 45 |
+
MAX_CACHE_LEN = 512
|
| 46 |
+
MASK_LEN = MAX_CACHE_LEN - 1 # 511; .pte specialized to this upper bound
|
| 47 |
+
DTYPE = torch.float32
|
| 48 |
+
|
| 49 |
+
# Same hardcoded layout as pi_runner.py — must match what 04_quantize.py exported.
|
| 50 |
+
GEMMA4_E2B_LAYER_SHAPES = [
|
| 51 |
+
# (head_dim, is_sliding)
|
| 52 |
+
(256, True), (256, True), (256, True), (256, True), (512, False), # 0..4
|
| 53 |
+
(256, True), (256, True), (256, True), (256, True), (512, False), # 5..9
|
| 54 |
+
(256, True), (256, True), (256, True), (256, True), (512, False), # 10..14
|
| 55 |
+
]
|
| 56 |
+
NUM_KV_HEADS = 1
|
| 57 |
+
BATCH = 1
|
| 58 |
+
|
| 59 |
+
# Gemma 4 end-of-turn / EOS tokens — stop generation when we see any of these
|
| 60 |
+
EOS_TOKEN_IDS = {106, 1, 2} # <end_of_turn>, <eos>, <bos>-as-sentinel
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# -------------------- ExecuTorch-side helpers --------------------
|
| 64 |
+
|
| 65 |
+
def allocate_cache_tensors():
|
| 66 |
+
"""One set of K, V, cumulative_length tensors per cache layer (zero-filled)."""
|
| 67 |
+
k_caches, v_caches, cumlen_caches = [], [], []
|
| 68 |
+
for head_dim, _is_sliding in GEMMA4_E2B_LAYER_SHAPES:
|
| 69 |
+
shape = (BATCH, NUM_KV_HEADS, MAX_CACHE_LEN, head_dim)
|
| 70 |
+
k_caches.append(torch.zeros(shape, dtype=DTYPE))
|
| 71 |
+
v_caches.append(torch.zeros(shape, dtype=DTYPE))
|
| 72 |
+
cumlen_caches.append(torch.zeros(1, dtype=torch.int64))
|
| 73 |
+
return k_caches, v_caches, cumlen_caches
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def step(method, token_id, pos, k_caches, v_caches, cumlen_caches):
|
| 77 |
+
"""One forward call: feed `token_id` at position `pos`, return (logits, updated caches)."""
|
| 78 |
+
input_ids = torch.tensor([[token_id]], dtype=torch.long)
|
| 79 |
+
attention_mask = torch.zeros(1, MASK_LEN, dtype=torch.long)
|
| 80 |
+
attention_mask[:, :pos + 1] = 1
|
| 81 |
+
position_ids = torch.tensor([[pos]], dtype=torch.long)
|
| 82 |
+
cache_position = torch.tensor([pos], dtype=torch.long)
|
| 83 |
+
|
| 84 |
+
args = (input_ids, attention_mask, position_ids, cache_position,
|
| 85 |
+
*k_caches, *v_caches, *cumlen_caches)
|
| 86 |
+
outputs = method.execute(args)
|
| 87 |
+
|
| 88 |
+
# See pi_runner.py for the .pte's 91-output layout. We use indices [46..90].
|
| 89 |
+
n = len(GEMMA4_E2B_LAYER_SHAPES)
|
| 90 |
+
logits = outputs[45]
|
| 91 |
+
base = 46
|
| 92 |
+
k_new = list(outputs[base:base + n])
|
| 93 |
+
v_new = list(outputs[base + n:base + 2 * n])
|
| 94 |
+
cumlen_new = list(outputs[base + 2 * n:base + 3 * n])
|
| 95 |
+
return logits, k_new, v_new, cumlen_new
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# -------------------- chat session state --------------------
|
| 99 |
+
|
| 100 |
+
class ChatSession:
|
| 101 |
+
"""Tracks conversation history + the tokens already fed to the .pte cache.
|
| 102 |
+
|
| 103 |
+
Key trick: every turn, we re-render the full conversation via the chat
|
| 104 |
+
template, find the longest common prefix with `fed_ids` (what's already
|
| 105 |
+
in the cache), and only feed the new tail. Avoids paying token-by-token
|
| 106 |
+
cost for the same context twice.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
def __init__(self, tokenizer, method, max_new_tokens):
|
| 110 |
+
self.tokenizer = tokenizer
|
| 111 |
+
self.method = method
|
| 112 |
+
self.max_new_tokens = max_new_tokens
|
| 113 |
+
self.history = [] # list of {"role": "user"/"model", "content": "..."}
|
| 114 |
+
self.fed_ids = [] # tokens already in cache
|
| 115 |
+
self.k, self.v, self.cumlen = allocate_cache_tensors()
|
| 116 |
+
|
| 117 |
+
def reset(self):
|
| 118 |
+
"""Wipe cache and history."""
|
| 119 |
+
self.history = []
|
| 120 |
+
self.fed_ids = []
|
| 121 |
+
self.k, self.v, self.cumlen = allocate_cache_tensors()
|
| 122 |
+
|
| 123 |
+
def _render(self):
|
| 124 |
+
"""Render the full conversation (with chat template + generation prompt)."""
|
| 125 |
+
messages = [
|
| 126 |
+
{"role": h["role"], "content": [{"type": "text", "text": h["content"]}]}
|
| 127 |
+
for h in self.history
|
| 128 |
+
]
|
| 129 |
+
enc = self.tokenizer.apply_chat_template(
|
| 130 |
+
messages, add_generation_prompt=True, tokenize=True,
|
| 131 |
+
return_dict=True, return_tensors="pt",
|
| 132 |
+
)
|
| 133 |
+
return enc["input_ids"][0].tolist()
|
| 134 |
+
|
| 135 |
+
def _feed(self, token_ids, start_pos):
|
| 136 |
+
"""Feed a sequence of tokens to the model, updating cache as we go.
|
| 137 |
+
Returns the logits from the LAST token (for next-token prediction)."""
|
| 138 |
+
last_logits = None
|
| 139 |
+
for i, tok in enumerate(token_ids):
|
| 140 |
+
last_logits, self.k, self.v, self.cumlen = step(
|
| 141 |
+
self.method, tok, start_pos + i,
|
| 142 |
+
self.k, self.v, self.cumlen,
|
| 143 |
+
)
|
| 144 |
+
return last_logits
|
| 145 |
+
|
| 146 |
+
def turn(self, user_text):
|
| 147 |
+
"""Process one user message → assistant response. Returns (response_text, timing_dict)."""
|
| 148 |
+
self.history.append({"role": "user", "content": user_text})
|
| 149 |
+
|
| 150 |
+
# Render full conversation + find what's new
|
| 151 |
+
full_ids = self._render()
|
| 152 |
+
# Verify the existing cache is still a prefix of the new render
|
| 153 |
+
# (chat template should always extend, not modify earlier tokens).
|
| 154 |
+
n_existing = len(self.fed_ids)
|
| 155 |
+
prefix_match = (n_existing <= len(full_ids)
|
| 156 |
+
and full_ids[:n_existing] == self.fed_ids)
|
| 157 |
+
if not prefix_match:
|
| 158 |
+
# Shouldn't happen with normal chat use, but if it does, reset.
|
| 159 |
+
print("\n [warn] chat template re-rendered prefix differently; resetting cache.",
|
| 160 |
+
file=sys.stderr)
|
| 161 |
+
self.k, self.v, self.cumlen = allocate_cache_tensors()
|
| 162 |
+
self.fed_ids = []
|
| 163 |
+
n_existing = 0
|
| 164 |
+
|
| 165 |
+
new_tail = full_ids[n_existing:]
|
| 166 |
+
|
| 167 |
+
# Cache overflow check
|
| 168 |
+
if n_existing + len(new_tail) + self.max_new_tokens > MASK_LEN:
|
| 169 |
+
tokens_left = MASK_LEN - (n_existing + len(new_tail))
|
| 170 |
+
if tokens_left < 4:
|
| 171 |
+
raise RuntimeError(
|
| 172 |
+
f"context window full (cache holds {n_existing + len(new_tail)}/{MASK_LEN}). "
|
| 173 |
+
f"Type /reset to start a new conversation."
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# Feed the new tokens
|
| 177 |
+
t_prefill = time.time()
|
| 178 |
+
last_logits = self._feed(new_tail, start_pos=n_existing)
|
| 179 |
+
self.fed_ids.extend(new_tail)
|
| 180 |
+
t_prefill = time.time() - t_prefill
|
| 181 |
+
n_prefill = len(new_tail)
|
| 182 |
+
|
| 183 |
+
# Greedy decode loop
|
| 184 |
+
next_id = int(last_logits[0, -1].argmax())
|
| 185 |
+
generated = []
|
| 186 |
+
t_decode = time.time()
|
| 187 |
+
for step_idx in range(self.max_new_tokens):
|
| 188 |
+
if next_id in EOS_TOKEN_IDS:
|
| 189 |
+
# Don't add the EOS to history's text, but include in fed_ids
|
| 190 |
+
# so cache_position stays aligned.
|
| 191 |
+
self.fed_ids.append(next_id)
|
| 192 |
+
# Feed the EOS so the cache reflects model's own output marker
|
| 193 |
+
_, self.k, self.v, self.cumlen = step(
|
| 194 |
+
self.method, next_id, len(self.fed_ids) - 1,
|
| 195 |
+
self.k, self.v, self.cumlen,
|
| 196 |
+
)
|
| 197 |
+
break
|
| 198 |
+
generated.append(next_id)
|
| 199 |
+
pos = len(self.fed_ids)
|
| 200 |
+
last_logits, self.k, self.v, self.cumlen = step(
|
| 201 |
+
self.method, next_id, pos,
|
| 202 |
+
self.k, self.v, self.cumlen,
|
| 203 |
+
)
|
| 204 |
+
self.fed_ids.append(next_id)
|
| 205 |
+
next_id = int(last_logits[0, -1].argmax())
|
| 206 |
+
t_decode = time.time() - t_decode
|
| 207 |
+
|
| 208 |
+
response_text = self.tokenizer.decode(generated, skip_special_tokens=True)
|
| 209 |
+
self.history.append({"role": "model", "content": response_text})
|
| 210 |
+
|
| 211 |
+
return response_text, {
|
| 212 |
+
"prefill_ms": t_prefill * 1000,
|
| 213 |
+
"prefill_tokens": n_prefill,
|
| 214 |
+
"prefill_tok_s": (n_prefill / t_prefill) if t_prefill > 0 else 0,
|
| 215 |
+
"decode_ms": t_decode * 1000,
|
| 216 |
+
"decode_tokens": len(generated),
|
| 217 |
+
"decode_tok_s": (len(generated) / t_decode) if t_decode > 0 else 0,
|
| 218 |
+
"context_used": len(self.fed_ids),
|
| 219 |
+
"context_max": MASK_LEN,
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# -------------------- terminal UI --------------------
|
| 224 |
+
|
| 225 |
+
HELP_TEXT = """
|
| 226 |
+
Commands:
|
| 227 |
+
(just type) send a message to the model
|
| 228 |
+
/reset wipe conversation history + cache, start fresh
|
| 229 |
+
/stats show timing for the last turn
|
| 230 |
+
/help show this help
|
| 231 |
+
Ctrl+C/D exit
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def main():
|
| 236 |
+
parser = argparse.ArgumentParser(
|
| 237 |
+
description="Interactive terminal chat with Gemma 4 E2B (ExecuTorch .pte runtime)",
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument("--pte", default=DEFAULT_PTE, help="path to .pte (default: alongside this script)")
|
| 240 |
+
parser.add_argument("--tokenizer", default=DEFAULT_TOK, help="path to tokenizer dir")
|
| 241 |
+
parser.add_argument("--max-new-tokens", type=int, default=200,
|
| 242 |
+
help="max tokens to generate per response (default 200)")
|
| 243 |
+
parser.add_argument("--quiet", action="store_true",
|
| 244 |
+
help="don't print per-turn timing")
|
| 245 |
+
args = parser.parse_args()
|
| 246 |
+
|
| 247 |
+
# Validate files
|
| 248 |
+
for path, label in [(args.pte, ".pte"), (args.tokenizer, "tokenizer dir")]:
|
| 249 |
+
if not os.path.exists(path):
|
| 250 |
+
print(f"error: {label} not found at {path}", file=sys.stderr)
|
| 251 |
+
sys.exit(1)
|
| 252 |
+
|
| 253 |
+
print(f"loading tokenizer from {args.tokenizer}...")
|
| 254 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
|
| 255 |
+
|
| 256 |
+
print(f"loading .pte from {args.pte}...")
|
| 257 |
+
t0 = time.time()
|
| 258 |
+
rt = Runtime.get()
|
| 259 |
+
program = rt.load_program(args.pte, verification=Verification.Minimal)
|
| 260 |
+
method = program.load_method("forward")
|
| 261 |
+
print(f" loaded in {time.time() - t0:.1f}s")
|
| 262 |
+
|
| 263 |
+
session = ChatSession(tokenizer, method, args.max_new_tokens)
|
| 264 |
+
last_stats = None
|
| 265 |
+
|
| 266 |
+
print()
|
| 267 |
+
print("=" * 60)
|
| 268 |
+
print(" Gemma 4 E2B — terminal chat")
|
| 269 |
+
print(" /help for commands · Ctrl+C or Ctrl+D to exit")
|
| 270 |
+
print("=" * 60)
|
| 271 |
+
|
| 272 |
+
def goodbye(*_args):
|
| 273 |
+
print("\nbye.")
|
| 274 |
+
sys.exit(0)
|
| 275 |
+
signal.signal(signal.SIGINT, goodbye)
|
| 276 |
+
|
| 277 |
+
while True:
|
| 278 |
+
try:
|
| 279 |
+
user = input("\nyou> ").strip()
|
| 280 |
+
except EOFError:
|
| 281 |
+
goodbye()
|
| 282 |
+
|
| 283 |
+
if not user:
|
| 284 |
+
continue
|
| 285 |
+
|
| 286 |
+
# Commands
|
| 287 |
+
if user.startswith("/"):
|
| 288 |
+
cmd = user.lower()
|
| 289 |
+
if cmd == "/help":
|
| 290 |
+
print(HELP_TEXT)
|
| 291 |
+
elif cmd == "/reset":
|
| 292 |
+
session.reset()
|
| 293 |
+
print(" (history + cache reset)")
|
| 294 |
+
elif cmd == "/stats":
|
| 295 |
+
if last_stats is None:
|
| 296 |
+
print(" (no turn yet)")
|
| 297 |
+
else:
|
| 298 |
+
s = last_stats
|
| 299 |
+
print(f" prefill: {s['prefill_ms']:.0f} ms / {s['prefill_tokens']} tok "
|
| 300 |
+
f"= {s['prefill_tok_s']:.2f} tok/s")
|
| 301 |
+
print(f" decode: {s['decode_ms']:.0f} ms / {s['decode_tokens']} tok "
|
| 302 |
+
f"= {s['decode_tok_s']:.2f} tok/s")
|
| 303 |
+
print(f" context: {s['context_used']}/{s['context_max']} tokens used")
|
| 304 |
+
else:
|
| 305 |
+
print(f" unknown command: {user}. type /help for the list.")
|
| 306 |
+
continue
|
| 307 |
+
|
| 308 |
+
# Normal turn
|
| 309 |
+
try:
|
| 310 |
+
response, stats = session.turn(user)
|
| 311 |
+
except RuntimeError as e:
|
| 312 |
+
print(f" [error] {e}")
|
| 313 |
+
continue
|
| 314 |
+
except KeyboardInterrupt:
|
| 315 |
+
goodbye()
|
| 316 |
+
|
| 317 |
+
last_stats = stats
|
| 318 |
+
print(f"\nmodel> {response}")
|
| 319 |
+
if not args.quiet:
|
| 320 |
+
print(f" [{stats['decode_tokens']} tok @ {stats['decode_tok_s']:.2f} tok/s · "
|
| 321 |
+
f"context {stats['context_used']}/{stats['context_max']}]")
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
if __name__ == "__main__":
|
| 325 |
+
main()
|
pi_runner.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Self-contained Gemma 4 E2B INT4 runner for Raspberry Pi 5 (or any ARM64).
|
| 3 |
+
|
| 4 |
+
Loads ONE .pte (external-cache variant), tokenizes a prompt with the
|
| 5 |
+
Gemma chat template, runs token-by-token (prompt feed + decode) threading
|
| 6 |
+
KV cache tensors across calls, prints generated text + timing.
|
| 7 |
+
|
| 8 |
+
Designed to run on the Pi with NO project codebase — just the .pte,
|
| 9 |
+
the tokenizer files, and this script. Only Python deps:
|
| 10 |
+
pip install executorch transformers
|
| 11 |
+
|
| 12 |
+
Files expected next to this script (or pass paths via flags):
|
| 13 |
+
gemma4_e2b_text_int4_extcache.pte
|
| 14 |
+
tokenizer/ # dir with tokenizer.json + tokenizer_config.json + chat_template.jinja
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
python pi_runner.py "The capital of France is"
|
| 18 |
+
python pi_runner.py "Why is the sky blue?" --max-new-tokens 50
|
| 19 |
+
python pi_runner.py "Hello" --verify # asserts output matches reference
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import os
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
from transformers import AutoTokenizer
|
| 28 |
+
from executorch.runtime import Runtime, Verification
|
| 29 |
+
|
| 30 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 31 |
+
DEFAULT_PTE = os.path.join(HERE, "gemma4_e2b_text_int4_extcache.pte")
|
| 32 |
+
DEFAULT_TOK = os.path.join(HERE, "tokenizer")
|
| 33 |
+
|
| 34 |
+
MAX_CACHE_LEN = 512
|
| 35 |
+
MASK_LEN = MAX_CACHE_LEN - 1 # 511; .pte specialized to this upper bound
|
| 36 |
+
DTYPE = torch.float32 # matches the model's quantize-time dtype
|
| 37 |
+
|
| 38 |
+
# Hardcoded cache layout for Gemma 4 E2B. Matches what
|
| 39 |
+
# scripts/_external_cache.py:compute_layer_specs derives from the model
|
| 40 |
+
# config. 35 decoder layers minus num_kv_shared_layers=20 = 15 cache layers.
|
| 41 |
+
# Layer-type pattern (repeats every 5): [sliding, sliding, sliding, sliding, full].
|
| 42 |
+
# Sliding layers: head_dim=256. Full layers: global_head_dim=512.
|
| 43 |
+
GEMMA4_E2B_LAYER_SHAPES = [
|
| 44 |
+
# (head_dim, is_sliding)
|
| 45 |
+
(256, True), (256, True), (256, True), (256, True), (512, False), # layers 0-4
|
| 46 |
+
(256, True), (256, True), (256, True), (256, True), (512, False), # layers 5-9
|
| 47 |
+
(256, True), (256, True), (256, True), (256, True), (512, False), # layers 10-14
|
| 48 |
+
]
|
| 49 |
+
NUM_KV_HEADS = 1
|
| 50 |
+
BATCH = 1
|
| 51 |
+
|
| 52 |
+
# Reference for --verify mode (FP32/INT4 token-id sequence for "The capital of France is")
|
| 53 |
+
REFERENCE_PROMPT = "The capital of France is"
|
| 54 |
+
REFERENCE_IDS = [818, 5279, 529, 7001, 563, 5213, 50429, 84750, 106]
|
| 55 |
+
REFERENCE_TEXT = "The capital of France is **Paris**."
|
| 56 |
+
|
| 57 |
+
# Gemma 4 end-of-turn token id (model stops here in chat)
|
| 58 |
+
EOS_TOKEN_IDS = {106, 1, 2} # <end_of_turn>, <eos>, <bos>-as-sentinel
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def allocate_cache_tensors():
|
| 62 |
+
"""Allocate one set of K, V, cumulative_length tensors per cache layer."""
|
| 63 |
+
k_caches, v_caches, cumlen_caches = [], [], []
|
| 64 |
+
for head_dim, _is_sliding in GEMMA4_E2B_LAYER_SHAPES:
|
| 65 |
+
shape = (BATCH, NUM_KV_HEADS, MAX_CACHE_LEN, head_dim)
|
| 66 |
+
k_caches.append(torch.zeros(shape, dtype=DTYPE))
|
| 67 |
+
v_caches.append(torch.zeros(shape, dtype=DTYPE))
|
| 68 |
+
cumlen_caches.append(torch.zeros(1, dtype=torch.int64))
|
| 69 |
+
return k_caches, v_caches, cumlen_caches
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def step(method, token_id, pos, k_caches, v_caches, cumlen_caches):
|
| 73 |
+
"""One forward call: feed `token_id` at position `pos`, get logits +
|
| 74 |
+
updated cache tensors back."""
|
| 75 |
+
input_ids = torch.tensor([[token_id]], dtype=torch.long)
|
| 76 |
+
attention_mask = torch.zeros(1, MASK_LEN, dtype=torch.long)
|
| 77 |
+
attention_mask[:, :pos + 1] = 1
|
| 78 |
+
position_ids = torch.tensor([[pos]], dtype=torch.long)
|
| 79 |
+
cache_position = torch.tensor([pos], dtype=torch.long)
|
| 80 |
+
|
| 81 |
+
# The .pte's execute() takes flat positional inputs.
|
| 82 |
+
# Order matches the wrapper's forward signature:
|
| 83 |
+
# input_ids, attention_mask, position_ids, cache_position, *k_caches, *v_caches, *cumlen_caches
|
| 84 |
+
args = (input_ids, attention_mask, position_ids, cache_position,
|
| 85 |
+
*k_caches, *v_caches, *cumlen_caches)
|
| 86 |
+
if os.environ.get("DEBUG_SHAPES"):
|
| 87 |
+
for i, a in enumerate(args):
|
| 88 |
+
if hasattr(a, "shape"):
|
| 89 |
+
print(f" arg[{i:2d}]: shape={tuple(a.shape)} dtype={a.dtype}", flush=True)
|
| 90 |
+
outputs = method.execute(args)
|
| 91 |
+
# The .pte emits 91 outputs:
|
| 92 |
+
# [0..14] K mutations (auto-emitted by torch.export)
|
| 93 |
+
# [15..29] V mutations
|
| 94 |
+
# [30..44] cumlen mutations
|
| 95 |
+
# [45] logits
|
| 96 |
+
# [46..60] K (from wrapper's explicit return — same tensors)
|
| 97 |
+
# [61..75] V (from wrapper's explicit return)
|
| 98 |
+
# [76..90] cumlen (from wrapper's explicit return)
|
| 99 |
+
# Either copy works; we use the explicit-return half because indices
|
| 100 |
+
# align with the (logits, k, v, cumlen) ordering the wrapper declared.
|
| 101 |
+
n = len(GEMMA4_E2B_LAYER_SHAPES)
|
| 102 |
+
logits = outputs[45]
|
| 103 |
+
base = 46
|
| 104 |
+
k_new = list(outputs[base:base + n])
|
| 105 |
+
v_new = list(outputs[base + n:base + 2 * n])
|
| 106 |
+
cumlen_new = list(outputs[base + 2 * n:base + 3 * n])
|
| 107 |
+
return logits, k_new, v_new, cumlen_new
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def main():
|
| 111 |
+
parser = argparse.ArgumentParser()
|
| 112 |
+
parser.add_argument("prompt", nargs="?", default=REFERENCE_PROMPT,
|
| 113 |
+
help=f"Prompt text (default: {REFERENCE_PROMPT!r})")
|
| 114 |
+
parser.add_argument("--pte", default=DEFAULT_PTE, help="Path to .pte file")
|
| 115 |
+
parser.add_argument("--tokenizer", default=DEFAULT_TOK, help="Path to tokenizer dir")
|
| 116 |
+
parser.add_argument("--max-new-tokens", type=int, default=20)
|
| 117 |
+
parser.add_argument("--verify", action="store_true",
|
| 118 |
+
help="Assert prompt+output match the reference (smoke test)")
|
| 119 |
+
args = parser.parse_args()
|
| 120 |
+
|
| 121 |
+
if args.verify:
|
| 122 |
+
args.prompt = REFERENCE_PROMPT
|
| 123 |
+
args.max_new_tokens = max(args.max_new_tokens, len(REFERENCE_IDS))
|
| 124 |
+
|
| 125 |
+
print(f"Loading tokenizer from {args.tokenizer}...")
|
| 126 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
|
| 127 |
+
|
| 128 |
+
print(f"Tokenizing prompt: {args.prompt!r}")
|
| 129 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": args.prompt}]}]
|
| 130 |
+
enc = tokenizer.apply_chat_template(
|
| 131 |
+
messages, add_generation_prompt=True, tokenize=True,
|
| 132 |
+
return_dict=True, return_tensors="pt",
|
| 133 |
+
)
|
| 134 |
+
prompt_ids = enc["input_ids"][0].tolist()
|
| 135 |
+
n_prompt = len(prompt_ids)
|
| 136 |
+
if n_prompt + args.max_new_tokens > MASK_LEN:
|
| 137 |
+
raise SystemExit(
|
| 138 |
+
f"prompt ({n_prompt}) + max_new_tokens ({args.max_new_tokens}) "
|
| 139 |
+
f"exceeds mask_len ({MASK_LEN})"
|
| 140 |
+
)
|
| 141 |
+
print(f" prompt_len = {n_prompt}")
|
| 142 |
+
|
| 143 |
+
print(f"\nLoading {args.pte}...")
|
| 144 |
+
t0 = time.time()
|
| 145 |
+
rt = Runtime.get()
|
| 146 |
+
program = rt.load_program(args.pte, verification=Verification.Minimal)
|
| 147 |
+
method = program.load_method("forward")
|
| 148 |
+
print(f" loaded in {time.time() - t0:.1f}s")
|
| 149 |
+
|
| 150 |
+
print("Allocating cache tensors...")
|
| 151 |
+
k_caches, v_caches, cumlen_caches = allocate_cache_tensors()
|
| 152 |
+
cache_mb = sum(t.numel() * t.element_size() for t in k_caches + v_caches) / 1e6
|
| 153 |
+
print(f" total cache size: {cache_mb:.1f} MB across {len(k_caches)} layers")
|
| 154 |
+
|
| 155 |
+
# --- Prompt token-by-token feed ("slow prefill") ---
|
| 156 |
+
print(f"\nFeeding {n_prompt} prompt tokens (token-by-token; no batched prefill in this design)...")
|
| 157 |
+
t_prefill_start = time.time()
|
| 158 |
+
last_logits = None
|
| 159 |
+
for i, tok in enumerate(prompt_ids):
|
| 160 |
+
last_logits, k_caches, v_caches, cumlen_caches = step(
|
| 161 |
+
method, tok, i, k_caches, v_caches, cumlen_caches
|
| 162 |
+
)
|
| 163 |
+
t_prefill = time.time() - t_prefill_start
|
| 164 |
+
print(f" prompt feed: {t_prefill:.2f}s ({n_prompt} tokens, "
|
| 165 |
+
f"{n_prompt / t_prefill:.2f} tok/s, ttft equivalent)")
|
| 166 |
+
|
| 167 |
+
# Next-token prediction from last prompt position's logits
|
| 168 |
+
next_id = int(last_logits[0, -1].argmax())
|
| 169 |
+
generated = [next_id]
|
| 170 |
+
print(f" first generated token: id={next_id} text={tokenizer.decode([next_id])!r}")
|
| 171 |
+
|
| 172 |
+
# --- Decode loop ---
|
| 173 |
+
print(f"\nDecoding up to {args.max_new_tokens - 1} more tokens...")
|
| 174 |
+
t_decode_start = time.time()
|
| 175 |
+
n_decoded = 1
|
| 176 |
+
for step_idx in range(args.max_new_tokens - 1):
|
| 177 |
+
if next_id in EOS_TOKEN_IDS:
|
| 178 |
+
print(f" hit EOS (id={next_id}) at decode step {step_idx}")
|
| 179 |
+
break
|
| 180 |
+
pos = n_prompt + step_idx # position of the token we just produced
|
| 181 |
+
last_logits, k_caches, v_caches, cumlen_caches = step(
|
| 182 |
+
method, next_id, pos, k_caches, v_caches, cumlen_caches
|
| 183 |
+
)
|
| 184 |
+
next_id = int(last_logits[0, -1].argmax())
|
| 185 |
+
generated.append(next_id)
|
| 186 |
+
n_decoded += 1
|
| 187 |
+
t_decode = time.time() - t_decode_start
|
| 188 |
+
|
| 189 |
+
text = tokenizer.decode(generated, skip_special_tokens=True)
|
| 190 |
+
print(f"\nGenerated ({len(generated)} tokens): {text!r}")
|
| 191 |
+
print(f"\n=== Timing ===")
|
| 192 |
+
print(f" prompt feed: {t_prefill*1000:7.0f} ms ({n_prompt} tok @ {n_prompt/t_prefill:5.2f} tok/s)")
|
| 193 |
+
print(f" decode: {t_decode*1000:7.0f} ms ({n_decoded} tok @ {n_decoded/t_decode:5.2f} tok/s)")
|
| 194 |
+
print(f" total: {(t_prefill + t_decode)*1000:7.0f} ms")
|
| 195 |
+
|
| 196 |
+
if args.verify:
|
| 197 |
+
compare_len = min(len(generated), len(REFERENCE_IDS))
|
| 198 |
+
match = generated[:compare_len] == REFERENCE_IDS[:compare_len]
|
| 199 |
+
print(f"\n=== Verify ===")
|
| 200 |
+
print(f" reference text: {REFERENCE_TEXT!r}")
|
| 201 |
+
print(f" generated text: {text!r}")
|
| 202 |
+
print(f" reference ids: {REFERENCE_IDS[:compare_len]}")
|
| 203 |
+
print(f" generated ids: {generated[:compare_len]}")
|
| 204 |
+
print(f" RESULT: {'PASS' if match else 'FAIL'}")
|
| 205 |
+
raise SystemExit(0 if match else 1)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
if __name__ == "__main__":
|
| 209 |
+
main()
|
tokenizer/chat_template.jinja
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- macro format_parameters(properties, required, filter_keys=false) -%}
|
| 2 |
+
{%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}
|
| 3 |
+
{%- set ns = namespace(found_first=false) -%}
|
| 4 |
+
{%- for key, value in properties | dictsort -%}
|
| 5 |
+
{%- set add_comma = false -%}
|
| 6 |
+
{%- if not filter_keys or key not in standard_keys -%}
|
| 7 |
+
{%- if ns.found_first %},{% endif -%}
|
| 8 |
+
{%- set ns.found_first = true -%}
|
| 9 |
+
{{ key }}:{
|
| 10 |
+
{%- if value['description'] -%}
|
| 11 |
+
description:<|"|>{{ value['description'] }}<|"|>
|
| 12 |
+
{%- set add_comma = true -%}
|
| 13 |
+
{%- endif -%}
|
| 14 |
+
{%- if value['type'] | upper == 'STRING' -%}
|
| 15 |
+
{%- if value['enum'] -%}
|
| 16 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 17 |
+
enum:{{ format_argument(value['enum']) }}
|
| 18 |
+
{%- endif -%}
|
| 19 |
+
{%- elif value['type'] | upper == 'ARRAY' -%}
|
| 20 |
+
{%- if value['items'] is mapping and value['items'] -%}
|
| 21 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 22 |
+
items:{
|
| 23 |
+
{%- set ns_items = namespace(found_first=false) -%}
|
| 24 |
+
{%- for item_key, item_value in value['items'] | dictsort -%}
|
| 25 |
+
{%- if item_value is not none -%}
|
| 26 |
+
{%- if ns_items.found_first %},{% endif -%}
|
| 27 |
+
{%- set ns_items.found_first = true -%}
|
| 28 |
+
{%- if item_key == 'properties' -%}
|
| 29 |
+
properties:{
|
| 30 |
+
{%- if item_value is mapping -%}
|
| 31 |
+
{{- format_parameters(item_value, value['items']['required'] | default([])) -}}
|
| 32 |
+
{%- endif -%}
|
| 33 |
+
}
|
| 34 |
+
{%- elif item_key == 'required' -%}
|
| 35 |
+
required:[
|
| 36 |
+
{%- for req_item in item_value -%}
|
| 37 |
+
<|"|>{{- req_item -}}<|"|>
|
| 38 |
+
{%- if not loop.last %},{% endif -%}
|
| 39 |
+
{%- endfor -%}
|
| 40 |
+
]
|
| 41 |
+
{%- elif item_key == 'type' -%}
|
| 42 |
+
{%- if item_value is string -%}
|
| 43 |
+
type:{{ format_argument(item_value | upper) }}
|
| 44 |
+
{%- else -%}
|
| 45 |
+
type:{{ format_argument(item_value | map('upper') | list) }}
|
| 46 |
+
{%- endif -%}
|
| 47 |
+
{%- else -%}
|
| 48 |
+
{{ item_key }}:{{ format_argument(item_value) }}
|
| 49 |
+
{%- endif -%}
|
| 50 |
+
{%- endif -%}
|
| 51 |
+
{%- endfor -%}
|
| 52 |
+
}
|
| 53 |
+
{%- endif -%}
|
| 54 |
+
{%- endif -%}
|
| 55 |
+
{%- if value['nullable'] %}
|
| 56 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 57 |
+
nullable:true
|
| 58 |
+
{%- endif -%}
|
| 59 |
+
{%- if value['type'] | upper == 'OBJECT' -%}
|
| 60 |
+
{%- if value['properties'] is defined and value['properties'] is mapping -%}
|
| 61 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 62 |
+
properties:{
|
| 63 |
+
{{- format_parameters(value['properties'], value['required'] | default([])) -}}
|
| 64 |
+
}
|
| 65 |
+
{%- elif value is mapping -%}
|
| 66 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 67 |
+
properties:{
|
| 68 |
+
{{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}}
|
| 69 |
+
}
|
| 70 |
+
{%- endif -%}
|
| 71 |
+
{%- if value['required'] -%}
|
| 72 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 73 |
+
required:[
|
| 74 |
+
{%- for item in value['required'] | default([]) -%}
|
| 75 |
+
<|"|>{{- item -}}<|"|>
|
| 76 |
+
{%- if not loop.last %},{% endif -%}
|
| 77 |
+
{%- endfor -%}
|
| 78 |
+
]
|
| 79 |
+
{%- endif -%}
|
| 80 |
+
{%- endif -%}
|
| 81 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 82 |
+
type:<|"|>{{ value['type'] | upper }}<|"|>}
|
| 83 |
+
{%- endif -%}
|
| 84 |
+
{%- endfor -%}
|
| 85 |
+
{%- endmacro -%}
|
| 86 |
+
{%- macro format_function_declaration(tool_data) -%}
|
| 87 |
+
declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|>
|
| 88 |
+
{%- set params = tool_data['function']['parameters'] -%}
|
| 89 |
+
{%- if params -%}
|
| 90 |
+
,parameters:{
|
| 91 |
+
{%- if params['properties'] -%}
|
| 92 |
+
properties:{ {{- format_parameters(params['properties'], params['required']) -}} },
|
| 93 |
+
{%- endif -%}
|
| 94 |
+
{%- if params['required'] -%}
|
| 95 |
+
required:[
|
| 96 |
+
{%- for item in params['required'] -%}
|
| 97 |
+
<|"|>{{- item -}}<|"|>
|
| 98 |
+
{{- ',' if not loop.last -}}
|
| 99 |
+
{%- endfor -%}
|
| 100 |
+
],
|
| 101 |
+
{%- endif -%}
|
| 102 |
+
{%- if params['type'] -%}
|
| 103 |
+
type:<|"|>{{- params['type'] | upper -}}<|"|>}
|
| 104 |
+
{%- endif -%}
|
| 105 |
+
{%- endif -%}
|
| 106 |
+
{%- if 'response' in tool_data['function'] -%}
|
| 107 |
+
{%- set response_declaration = tool_data['function']['response'] -%}
|
| 108 |
+
,response:{
|
| 109 |
+
{%- if response_declaration['description'] -%}
|
| 110 |
+
description:<|"|>{{- response_declaration['description'] -}}<|"|>,
|
| 111 |
+
{%- endif -%}
|
| 112 |
+
{%- if response_declaration['type'] | upper == 'OBJECT' -%}
|
| 113 |
+
type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>}
|
| 114 |
+
{%- endif -%}
|
| 115 |
+
{%- endif -%}
|
| 116 |
+
}
|
| 117 |
+
{%- endmacro -%}
|
| 118 |
+
{%- macro format_argument(argument, escape_keys=True) -%}
|
| 119 |
+
{%- if argument is string -%}
|
| 120 |
+
{{- '<|"|>' + argument + '<|"|>' -}}
|
| 121 |
+
{%- elif argument is boolean -%}
|
| 122 |
+
{{- 'true' if argument else 'false' -}}
|
| 123 |
+
{%- elif argument is mapping -%}
|
| 124 |
+
{{- '{' -}}
|
| 125 |
+
{%- set ns = namespace(found_first=false) -%}
|
| 126 |
+
{%- for key, value in argument | dictsort -%}
|
| 127 |
+
{%- if ns.found_first %},{% endif -%}
|
| 128 |
+
{%- set ns.found_first = true -%}
|
| 129 |
+
{%- if escape_keys -%}
|
| 130 |
+
{{- '<|"|>' + key + '<|"|>' -}}
|
| 131 |
+
{%- else -%}
|
| 132 |
+
{{- key -}}
|
| 133 |
+
{%- endif -%}
|
| 134 |
+
:{{- format_argument(value, escape_keys=escape_keys) -}}
|
| 135 |
+
{%- endfor -%}
|
| 136 |
+
{{- '}' -}}
|
| 137 |
+
{%- elif argument is sequence -%}
|
| 138 |
+
{{- '[' -}}
|
| 139 |
+
{%- for item in argument -%}
|
| 140 |
+
{{- format_argument(item, escape_keys=escape_keys) -}}
|
| 141 |
+
{%- if not loop.last %},{% endif -%}
|
| 142 |
+
{%- endfor -%}
|
| 143 |
+
{{- ']' -}}
|
| 144 |
+
{%- else -%}
|
| 145 |
+
{{- argument -}}
|
| 146 |
+
{%- endif -%}
|
| 147 |
+
{%- endmacro -%}
|
| 148 |
+
{%- macro strip_thinking(text) -%}
|
| 149 |
+
{%- set ns = namespace(result='') -%}
|
| 150 |
+
{%- for part in text.split('<channel|>') -%}
|
| 151 |
+
{%- if '<|channel>' in part -%}
|
| 152 |
+
{%- set ns.result = ns.result + part.split('<|channel>')[0] -%}
|
| 153 |
+
{%- else -%}
|
| 154 |
+
{%- set ns.result = ns.result + part -%}
|
| 155 |
+
{%- endif -%}
|
| 156 |
+
{%- endfor -%}
|
| 157 |
+
{{- ns.result | trim -}}
|
| 158 |
+
{%- endmacro -%}
|
| 159 |
+
|
| 160 |
+
{%- macro format_tool_response_block(tool_name, response) -%}
|
| 161 |
+
{{- '<|tool_response>' -}}
|
| 162 |
+
{%- if response is mapping -%}
|
| 163 |
+
{{- 'response:' + tool_name + '{' -}}
|
| 164 |
+
{%- for key, value in response | dictsort -%}
|
| 165 |
+
{{- key -}}:{{- format_argument(value, escape_keys=False) -}}
|
| 166 |
+
{%- if not loop.last %},{% endif -%}
|
| 167 |
+
{%- endfor -%}
|
| 168 |
+
{{- '}' -}}
|
| 169 |
+
{%- else -%}
|
| 170 |
+
{{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}}
|
| 171 |
+
{%- endif -%}
|
| 172 |
+
{{- '<tool_response|>' -}}
|
| 173 |
+
{%- endmacro -%}
|
| 174 |
+
|
| 175 |
+
{%- set ns = namespace(prev_message_type=None) -%}
|
| 176 |
+
{%- set loop_messages = messages -%}
|
| 177 |
+
{{- bos_token -}}
|
| 178 |
+
{#- Handle System/Tool Definitions Block -#}
|
| 179 |
+
{%- if (enable_thinking is defined and enable_thinking) or tools or messages[0]['role'] in ['system', 'developer'] -%}
|
| 180 |
+
{{- '<|turn>system\n' -}}
|
| 181 |
+
{#- Inject Thinking token at the very top of the FIRST system turn -#}
|
| 182 |
+
{%- if enable_thinking is defined and enable_thinking -%}
|
| 183 |
+
{{- '<|think|>\n' -}}
|
| 184 |
+
{%- set ns.prev_message_type = 'think' -%}
|
| 185 |
+
{%- endif -%}
|
| 186 |
+
{%- if messages[0]['role'] in ['system', 'developer'] -%}
|
| 187 |
+
{%- if messages[0]['content'] is string -%}
|
| 188 |
+
{{- messages[0]['content'] | trim -}}
|
| 189 |
+
{%- elif messages[0]['content'] is sequence -%}
|
| 190 |
+
{%- for item in messages[0]['content'] -%}
|
| 191 |
+
{{- item['text'] | trim + ' '-}}
|
| 192 |
+
{%- endfor -%}
|
| 193 |
+
{%- endif -%}
|
| 194 |
+
{%- set loop_messages = messages[1:] -%}
|
| 195 |
+
{%- endif -%}
|
| 196 |
+
{%- if tools -%}
|
| 197 |
+
{%- for tool in tools %}
|
| 198 |
+
{{- '<|tool>' -}}
|
| 199 |
+
{{- format_function_declaration(tool) | trim -}}
|
| 200 |
+
{{- '<tool|>' -}}
|
| 201 |
+
{%- endfor %}
|
| 202 |
+
{%- set ns.prev_message_type = 'tool' -%}
|
| 203 |
+
{%- endif -%}
|
| 204 |
+
{{- '<turn|>\n' -}}
|
| 205 |
+
{%- endif %}
|
| 206 |
+
|
| 207 |
+
{#- Pre-scan: find last user message index for reasoning guard -#}
|
| 208 |
+
{%- set ns_turn = namespace(last_user_idx=-1) -%}
|
| 209 |
+
{%- for i in range(loop_messages | length) -%}
|
| 210 |
+
{%- if loop_messages[i]['role'] == 'user' -%}
|
| 211 |
+
{%- set ns_turn.last_user_idx = i -%}
|
| 212 |
+
{%- endif -%}
|
| 213 |
+
{%- endfor -%}
|
| 214 |
+
|
| 215 |
+
{#- Loop through messages -#}
|
| 216 |
+
{%- for message in loop_messages -%}
|
| 217 |
+
{%- if message['role'] != 'tool' -%}
|
| 218 |
+
{%- set ns.prev_message_type = None -%}
|
| 219 |
+
{%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}
|
| 220 |
+
{#- Detect continuation: suppress duplicate <|turn>model when previous non-tool message was also assistant -#}
|
| 221 |
+
{%- set prev_nt = namespace(role=None, found=false) -%}
|
| 222 |
+
{%- if loop.index0 > 0 -%}
|
| 223 |
+
{%- for j in range(loop.index0 - 1, -1, -1) -%}
|
| 224 |
+
{%- if not prev_nt.found -%}
|
| 225 |
+
{%- if loop_messages[j]['role'] != 'tool' -%}
|
| 226 |
+
{%- set prev_nt.role = loop_messages[j]['role'] -%}
|
| 227 |
+
{%- set prev_nt.found = true -%}
|
| 228 |
+
{%- endif -%}
|
| 229 |
+
{%- endif -%}
|
| 230 |
+
{%- endfor -%}
|
| 231 |
+
{%- endif -%}
|
| 232 |
+
{%- set continue_same_model_turn = (role == 'model' and prev_nt.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 |
+
{%- if thinking_text and loop.index0 > ns_turn.last_user_idx and message.get('tool_calls') -%}
|
| 240 |
+
{{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}}
|
| 241 |
+
{%- endif -%}
|
| 242 |
+
|
| 243 |
+
{%- if message['tool_calls'] -%}
|
| 244 |
+
{%- for tool_call in message['tool_calls'] -%}
|
| 245 |
+
{%- set function = tool_call['function'] -%}
|
| 246 |
+
{{- '<|tool_call>call:' + function['name'] + '{' -}}
|
| 247 |
+
{%- if function['arguments'] is mapping -%}
|
| 248 |
+
{%- set ns_args = namespace(found_first=false) -%}
|
| 249 |
+
{%- for key, value in function['arguments'] | dictsort -%}
|
| 250 |
+
{%- if ns_args.found_first %},{% endif -%}
|
| 251 |
+
{%- set ns_args.found_first = true -%}
|
| 252 |
+
{{- key -}}:{{- format_argument(value, escape_keys=False) -}}
|
| 253 |
+
{%- endfor -%}
|
| 254 |
+
{%- elif function['arguments'] is string -%}
|
| 255 |
+
{{- function['arguments'] -}}
|
| 256 |
+
{%- endif -%}
|
| 257 |
+
{{- '}<tool_call|>' -}}
|
| 258 |
+
{%- endfor -%}
|
| 259 |
+
{%- set ns.prev_message_type = 'tool_call' -%}
|
| 260 |
+
{%- endif -%}
|
| 261 |
+
|
| 262 |
+
{%- set ns_tr_out = namespace(flag=false) -%}
|
| 263 |
+
{%- if message.get('tool_responses') -%}
|
| 264 |
+
{#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#}
|
| 265 |
+
{%- for tool_response in message['tool_responses'] -%}
|
| 266 |
+
{{- format_tool_response_block(tool_response['name'] | default('unknown'), tool_response['response']) -}}
|
| 267 |
+
{%- set ns_tr_out.flag = true -%}
|
| 268 |
+
{%- set ns.prev_message_type = 'tool_response' -%}
|
| 269 |
+
{%- endfor -%}
|
| 270 |
+
{%- elif message.get('tool_calls') -%}
|
| 271 |
+
{#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#}
|
| 272 |
+
{%- set ns_tool_scan = namespace(stopped=false) -%}
|
| 273 |
+
{%- for k in range(loop.index0 + 1, loop_messages | length) -%}
|
| 274 |
+
{%- if ns_tool_scan.stopped -%}
|
| 275 |
+
{%- elif loop_messages[k]['role'] != 'tool' -%}
|
| 276 |
+
{%- set ns_tool_scan.stopped = true -%}
|
| 277 |
+
{%- else -%}
|
| 278 |
+
{%- set follow = loop_messages[k] -%}
|
| 279 |
+
{#- Resolve tool_call_id to function name -#}
|
| 280 |
+
{%- set ns_tname = namespace(name=follow.get('name') | default('unknown')) -%}
|
| 281 |
+
{%- for tc in message['tool_calls'] -%}
|
| 282 |
+
{%- if tc.get('id') == follow.get('tool_call_id') -%}
|
| 283 |
+
{%- set ns_tname.name = tc['function']['name'] -%}
|
| 284 |
+
{%- endif -%}
|
| 285 |
+
{%- endfor -%}
|
| 286 |
+
{#- Handle content as string or content-parts array -#}
|
| 287 |
+
{%- set tool_body = follow.get('content') -%}
|
| 288 |
+
{%- if tool_body is string -%}
|
| 289 |
+
{{- format_tool_response_block(ns_tname.name, tool_body) -}}
|
| 290 |
+
{%- elif tool_body is sequence and tool_body is not string -%}
|
| 291 |
+
{%- set ns_txt = namespace(s='') -%}
|
| 292 |
+
{%- for part in tool_body -%}
|
| 293 |
+
{%- if part.get('type') == 'text' -%}
|
| 294 |
+
{%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%}
|
| 295 |
+
{%- endif -%}
|
| 296 |
+
{%- endfor -%}
|
| 297 |
+
{{- format_tool_response_block(ns_tname.name, ns_txt.s) -}}
|
| 298 |
+
{%- for part in tool_body -%}
|
| 299 |
+
{%- if part.get('type') == 'image' -%}
|
| 300 |
+
{{- '<|image|>' -}}
|
| 301 |
+
{%- elif part.get('type') == 'audio' -%}
|
| 302 |
+
{{- '<|audio|>' -}}
|
| 303 |
+
{%- elif part.get('type') == 'video' -%}
|
| 304 |
+
{{- '<|video|>' -}}
|
| 305 |
+
{%- endif -%}
|
| 306 |
+
{%- endfor -%}
|
| 307 |
+
{%- else -%}
|
| 308 |
+
{{- format_tool_response_block(ns_tname.name, tool_body) -}}
|
| 309 |
+
{%- endif -%}
|
| 310 |
+
{%- set ns_tr_out.flag = true -%}
|
| 311 |
+
{%- set ns.prev_message_type = 'tool_response' -%}
|
| 312 |
+
{%- endif -%}
|
| 313 |
+
{%- endfor -%}
|
| 314 |
+
{%- endif -%}
|
| 315 |
+
|
| 316 |
+
{%- set captured_content -%}
|
| 317 |
+
{%- if message['content'] is string -%}
|
| 318 |
+
{%- if role == 'model' -%}
|
| 319 |
+
{{- strip_thinking(message['content']) -}}
|
| 320 |
+
{%- else -%}
|
| 321 |
+
{{- message['content'] | trim -}}
|
| 322 |
+
{%- endif -%}
|
| 323 |
+
{%- elif message['content'] is sequence -%}
|
| 324 |
+
{%- for item in message['content'] -%}
|
| 325 |
+
{%- if item['type'] == 'text' -%}
|
| 326 |
+
{%- if role == 'model' -%}
|
| 327 |
+
{{- strip_thinking(item['text']) -}}
|
| 328 |
+
{%- else -%}
|
| 329 |
+
{{- item['text'] | trim -}}
|
| 330 |
+
{%- endif -%}
|
| 331 |
+
{%- elif item['type'] == 'image' -%}
|
| 332 |
+
{{- '<|image|>' -}}
|
| 333 |
+
{%- set ns.prev_message_type = 'image' -%}
|
| 334 |
+
{%- elif item['type'] == 'audio' -%}
|
| 335 |
+
{{- '<|audio|>' -}}
|
| 336 |
+
{%- set ns.prev_message_type = 'audio' -%}
|
| 337 |
+
{%- elif item['type'] == 'video' -%}
|
| 338 |
+
{{- '<|video|>' -}}
|
| 339 |
+
{%- set ns.prev_message_type = 'video' -%}
|
| 340 |
+
{%- endif -%}
|
| 341 |
+
{%- endfor -%}
|
| 342 |
+
{%- endif -%}
|
| 343 |
+
{%- endset -%}
|
| 344 |
+
|
| 345 |
+
{{- captured_content -}}
|
| 346 |
+
{%- set has_content = captured_content | trim | length > 0 -%}
|
| 347 |
+
|
| 348 |
+
{%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}
|
| 349 |
+
{{- '<|tool_response>' -}}
|
| 350 |
+
{%- elif not (ns_tr_out.flag and not has_content) -%}
|
| 351 |
+
{{- '<turn|>\n' -}}
|
| 352 |
+
{%- endif -%}
|
| 353 |
+
{%- endif -%}
|
| 354 |
+
{%- endfor -%}
|
| 355 |
+
|
| 356 |
+
{%- if add_generation_prompt -%}
|
| 357 |
+
{%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}
|
| 358 |
+
{{- '<|turn>model\n' -}}
|
| 359 |
+
{%- endif -%}
|
| 360 |
+
{%- endif -%}
|
tokenizer/tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f
|
| 3 |
+
size 32169626
|
tokenizer/tokenizer_config.json
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"mask_token": "<mask>",
|
| 21 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 22 |
+
"pad_token": "<pad>",
|
| 23 |
+
"padding_side": "left",
|
| 24 |
+
"processor_class": "Gemma4Processor",
|
| 25 |
+
"response_schema": {
|
| 26 |
+
"type": "object",
|
| 27 |
+
"properties": {
|
| 28 |
+
"role": {
|
| 29 |
+
"const": "assistant"
|
| 30 |
+
},
|
| 31 |
+
"thinking": {
|
| 32 |
+
"type": "string"
|
| 33 |
+
},
|
| 34 |
+
"content": {
|
| 35 |
+
"type": "string"
|
| 36 |
+
},
|
| 37 |
+
"tool_calls": {
|
| 38 |
+
"x-regex-iterator": "<\\|tool_call>(.*?)<tool_call\\|>",
|
| 39 |
+
"type": "array",
|
| 40 |
+
"items": {
|
| 41 |
+
"type": "object",
|
| 42 |
+
"properties": {
|
| 43 |
+
"type": {
|
| 44 |
+
"const": "function"
|
| 45 |
+
},
|
| 46 |
+
"function": {
|
| 47 |
+
"type": "object",
|
| 48 |
+
"x-regex": "call\\:(?P<name>\\w+)(?P<arguments>\\{.*\\})",
|
| 49 |
+
"properties": {
|
| 50 |
+
"name": {
|
| 51 |
+
"type": "string"
|
| 52 |
+
},
|
| 53 |
+
"arguments": {
|
| 54 |
+
"type": "object",
|
| 55 |
+
"x-parser": "gemma4-tool-call",
|
| 56 |
+
"additionalProperties": {}
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
},
|
| 64 |
+
"x-regex": "(\\<\\|channel\\>thought\\n(?P<thinking>.*?)\\<channel\\|\\>)?(?P<tool_calls>\\<\\|tool_call\\>.*\\<tool_call\\|\\>)?(?P<content>(?:(?!\\<turn\\|\\>)(?!\\<\\|tool_response\\>).)+)?(?:\\<turn\\|\\>|\\<\\|tool_response\\>)?"
|
| 65 |
+
},
|
| 66 |
+
"soc_token": "<|channel>",
|
| 67 |
+
"sot_token": "<|turn>",
|
| 68 |
+
"stc_token": "<|tool_call>",
|
| 69 |
+
"std_token": "<|tool>",
|
| 70 |
+
"str_token": "<|tool_response>",
|
| 71 |
+
"think_token": "<|think|>",
|
| 72 |
+
"tokenizer_class": "GemmaTokenizer",
|
| 73 |
+
"unk_token": "<unk>"
|
| 74 |
+
}
|