Text Generation
Transformers
Safetensors
PEFT
English
gemma4
image-text-to-text
merged
lora
qlora
sft
trl
code
java
junit
unit-test-generation
mutation-testing
vllm
conversational
Eval Results (legacy)
Run this model with HF Jobs
Run SASVAAI/gemma-4-26b-jUnitTestGeneration on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/SASVAAI/gemma-4-26b-jUnitTestGeneration. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/SASVAAI/gemma-4-26b-jUnitTestGeneration on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/SASVAAI/gemma-4-26b-jUnitTestGeneration. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/SASVAAI/gemma-4-26b-jUnitTestGeneration. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use SASVAAI/gemma-4-26b-jUnitTestGeneration with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use SASVAAI/gemma-4-26b-jUnitTestGeneration with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="SASVAAI/gemma-4-26b-jUnitTestGeneration") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("SASVAAI/gemma-4-26b-jUnitTestGeneration") model = AutoModelForMultimodalLM.from_pretrained("SASVAAI/gemma-4-26b-jUnitTestGeneration", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - PEFT
How to use SASVAAI/gemma-4-26b-jUnitTestGeneration with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use SASVAAI/gemma-4-26b-jUnitTestGeneration with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "SASVAAI/gemma-4-26b-jUnitTestGeneration" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "SASVAAI/gemma-4-26b-jUnitTestGeneration", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/SASVAAI/gemma-4-26b-jUnitTestGeneration
- SGLang
How to use SASVAAI/gemma-4-26b-jUnitTestGeneration with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "SASVAAI/gemma-4-26b-jUnitTestGeneration" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "SASVAAI/gemma-4-26b-jUnitTestGeneration", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "SASVAAI/gemma-4-26b-jUnitTestGeneration" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "SASVAAI/gemma-4-26b-jUnitTestGeneration", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use SASVAAI/gemma-4-26b-jUnitTestGeneration with Docker Model Runner:
docker model run hf.co/SASVAAI/gemma-4-26b-jUnitTestGeneration
Add merged Gemma-4-26B-A4B JUnit test generator, LoRA adapter and model card
#1
by aaron-psl - opened
Files changed (32)
- .gitattributes+2
- LICENSEAdded+202
- README.md+622-1
- adapter/README.mdAdded+23
- adapter/adapter_config.jsonAdded+46
- adapter/adapter_model.safetensorsAdded+3
- adapter/all_results.jsonAdded+7
- adapter/chat_template.jinjaAdded+390
- adapter/eval_results.jsonAdded+11
- adapter/predictions.jsonlAdded
- adapter/tokenizer.jsonAdded+3
- adapter/tokenizer_config.jsonAdded+142
- adapter/train_results.jsonAdded+7
- adapter/trainer_state.jsonAdded+504
- chat_template.jinjaAdded+390
- config.jsonAdded+146
- generation_config.jsonAdded+14
- model-00001-of-00011.safetensorsAdded+3
- model-00002-of-00011.safetensorsAdded+3
- model-00003-of-00011.safetensorsAdded+3
- model-00004-of-00011.safetensorsAdded+3
- model-00005-of-00011.safetensorsAdded+3
- model-00006-of-00011.safetensorsAdded+3
- model-00007-of-00011.safetensorsAdded+3
- model-00008-of-00011.safetensorsAdded+3
- model-00009-of-00011.safetensorsAdded+3
- model-00010-of-00011.safetensorsAdded+3
- model-00011-of-00011.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- processor_config.jsonAdded+75
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+142
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textadapter/tokenizer.json filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Alibaba Cloud
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624---# ---- Identity -------------------------------------------------------------base_model: google/gemma-4-26B-A4B-itbase_model_relation: mergelibrary_name: transformerspipeline_tag: text-generationlanguage:- enlicense: apache-2.0 # verified: inherited from google/gemma-4-26B-A4B-it, whose# Hub metadata declares license:apache-2.0 (license_link# https://ai.google.dev/gemma/docs/gemma_4_license). The base# repo ships no LICENSE file; the Apache-2.0 text is included# here verbatim. Training data is methods2test (MIT); the# Java projects it was mined from carry their own licences# (see Training details).# ---- Discovery ------------------------------------------------------------tags:- merged- lora- qlora- sft- trl- peft- text-generation- code- java- junit- unit-test-generation- mutation-testing- vllmmetrics:- pass@k- accuracy# ---- Structured evaluation ------------------------------------------------model-index:- name: gemma-4-26b-jUnitTestGenerationresults:- task:type: text-generationname: Focal Java method to one JUnit test method (compile, pass, kill a PIT mutant)dataset:type: andstor/methods2test_runnablename: methods2test runnable test split, 332 harness-verified rows from 86 Maven projects (project-disjoint from training)split: testrevision: ed8cded666b2f7d101ba04a7a8d121b6249d8c39metrics:- type: pass@kname: pass@5 (greedy + 4 samples at T=0.8; any candidate compiles, passes and kills a PIT mutant) — the search metricvalue: 0.503012- type: pass@1name: pass@1, greedy (compiles, passes and kills a PIT mutant)value: 0.246988- type: accuracyname: Greedy compile rate (mvn test-compile succeeds with the method inserted)value: 0.421687- type: accuracyname: Greedy mean PIT kill fraction on the focal method's mutantsvalue: 0.206093---# Gemma-4-26B-A4B JUnit Test GeneratorGiven a Java focal method, a skeleton of its class, and the existing test classthe new test will be inserted into, emits **one JUnit test method** startingwith `@Test`. A test counts as correct only if it compiles in the real project,passes against the real implementation, and kills at least one[PIT](https://pitest.org/) mutant of the focal method.This repository holds **two forms of the same model**:| Where | What | Use it when ||---|---|---|| repository root | [google/gemma-4-26B-A4B-it](https://huggingface.co/google/gemma-4-26B-A4B-it) with the LoRA merged in, bfloat16, 11 safetensors shards (~51.6 GB) | you want one directory to load or serve, e.g. with vLLM || `adapter/` | the LoRA adapter itself (35.5 MiB, QLoRA-trained) plus the training run's state, results and every validation prediction with its harness verdict | you already have the base model, or need the base in 4-bit on one GPU |The adapter was trained with **QLoRA (4-bit NF4 base, bf16 compute)** via[TRL](https://github.com/huggingface/trl) SFT and merged with`PeftModel.merge_and_unload`. Every number in this card was measured on themerged weights at the root, served with vLLM, and graded by building andrunning each test inside its own Maven project.> **The headline number assumes you can run the tests.** 0.503 is **pass@5**:> the share of 332 held-out focal methods for which *at least one of five*> candidates (one greedy, four sampled at temperature 0.8) compiles, passes and> kills a mutant. A single greedy answer succeeds on **0.247**. Use 0.503 only> if your deployment generates several candidates, runs them, and keeps one> that passes; otherwise the honest figure is 0.247. The untuned base model was> never scored on these rows, so this card does not establish how much of> either number the fine-tune is responsible for. Read> [How these values were chosen](#how-these-values-were-chosen) and> [Evaluation](#evaluation) before quoting anything.## Model details| | ||---|---|| Developed by | SASVA AI Model Cognition Labs (MCL) Team || Base model | [`google/gemma-4-26B-A4B-it`](https://huggingface.co/google/gemma-4-26B-A4B-it) || Base revision | `4d7ae4984b7db7de8f8457170b3f1a419ee76d52` || Base parameters | 25,805,936,206 total (Hub safetensors metadata); mixture-of-experts, ~4B active per token || Architecture family | `gemma4` (`Gemma4ForConditionalGeneration`; text tower with 30 layers, 128 experts, hidden size 2816, vocabulary 262,144) || Adaptation | LoRA (`r=16`, `alpha=32`, `dropout=0.05`, rsLoRA off, DoRA off), merged into the root weights; adapter kept under `adapter/` || Trainable modules | `q_proj`, `k_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj` on all 30 layers; `v_proj` on the 25 sliding-window layers (see below) || Excluded modules | `.*vision_tower.*` (the vision tower is untouched; training and evaluation were text-only) || Training method | `qlora` (`--load-in-4bit`, run 14 / trial 1) || Refinement | none || Precision | training: 4-bit NF4 base with double quantisation, bf16 compute; adapter saved in bfloat16; root weights: bfloat16 merge || Language | English prompts, Java output || License | Apache-2.0 (inherited from the base model); training data methods2test is MIT |Trainable parameters: **18,585,600** across 205 modules, 0.072% of the basemodel's parameters. `adapter/adapter_model.safetensors` is 37,232,104 bytes(410 tensors, `lora_A` + `lora_B` per module, all bfloat16). Every tensor sitsunder `base_model.model.model.language_model`.**One Gemma 4 structural fact shapes the module list.** The 30 text layersalternate 5 sliding-window attention layers with one full-attention layer, solayers 5, 11, 17, 23 and 29 are global attention, and the global layers have**no `v_proj` weight**. PEFT therefore attached `v_proj` adapters to 25 layersand the other six projections to 30. The tensor counts match: 60 per projectionfor 30 layers × A/B, 50 for `v_proj`.## Intended use**Direct use.** Draft a unit test for one Java method, for a developer toreview, run and keep. The model is most useful inside a loop that compiles andruns its output: generate several candidates, run them, keep one that passes.That loop is what pass@5 measures.The model was trained on a specific prompt shape and that shape is part of thecontract:- System prompt (verbatim, from the training and evaluation command lines):*"You are a Java test generation expert. Given a focal method with its classskeleton and target test class, write a single JUnit test method (startingwith `@Test`) that compiles, passes against the correct implementation, andis designed to kill a PIT mutant by testing boundary conditions, edge cases,and specific logic branches. Output only the raw Java test method startingwith `@Test`, with no explanation or surrounding text."*- User turn: the instruction, a blank line, then the context block inside abare ```` ``` ```` fence (`instruction + "\n\n```\n" + context + "\n```"`).The instruction is, with the three names filled in:*"Write one JUnit test method for the focal method `{focal_method}` of class`{focal_class}`. The method will be inserted into the existing test class`{test_class}` shown after the focal class, so use only what is visible thereand in the focal class. Output only the Java test method, starting with@Test. No class declaration, no imports, no explanation."*- The context block is, in this order:1. `// Focal class: <path>` and the focal class skeleton: fields, everymethod's signature, and the full body of the focal method only.2. A blank line, `// Test class: <path>`.3. `// Java source level: <level>`, with a reminder of what the level forbidsfor 1.5 to 1.7 (for example `1.6 (no diamond operator <>, lambdas, methodreferences, try-with-resources, multi-catch or switch on String)`). Everyevaluation row has this line; 38% of training rows have no level becausetheir parent POMs no longer resolve.4. The test class's `import` lines as they are at the project's commit.5. The test class skeleton: its declaration and fields, no test methods.- Applied through the tokenizer's chat template (`chat_template.jinja`,shipped in this repo) with `add_generation_prompt=True`. Do not concatenatestrings by hand.- The output is one Java method starting with `@Test`, meant to be insertedinto the test class as-is. It may only use imports already in the testclass.- Greedy decoding for a single answer; the four extra pass@5 candidates weresampled at `temperature=0.8`, `top_p=0.95`. Scored with`max_new_tokens=1024`.**Out-of-scope use.** Generating whole test classes or test suites. Projectsthat are not Maven, or that need a JDK newer than the one you compile with.Accepting a generated test without running it. Using "the test passes" asevidence that the code under test is correct: the model writes tests that passagainst the current implementation, bugs included.## How to get startedThe prompt pieces are the same in every path. The example is validation row292 (`ArrayMatcher.matches`, from the `arquillian/algeron` project).```pythonSYSTEM = ("You are a Java test generation expert. Given a focal method with its class ""skeleton and target test class, write a single JUnit test method (starting with ""`@Test`) that compiles, passes against the correct implementation, and is designed ""to kill a PIT mutant by testing boundary conditions, edge cases, and specific logic ""branches. Output only the raw Java test method starting with `@Test`, with no ""explanation or surrounding text.")INSTRUCTION = ("Write one JUnit test method for the focal method `matches` of class `ArrayMatcher`. ""The method will be inserted into the existing test class `ArrayMatcherTest` shown ""after the focal class, so use only what is visible there and in the focal class. ""Output only the Java test method, starting with @Test. No class declaration, no ""imports, no explanation.")context = """// Focal class: pact/provider/core/src/main/java/org/arquillian/algeron/pact/provider/core/ArrayMatcher.javaclass ArrayMatcher {public static final Optional<String> firstMatch(String[] patternArray, String value);public static final boolean matches(String[] patternArray, String value) {return firstMatch(patternArray, value).isPresent();}}// Test class: pact/provider/core/src/test/java/org/arquillian/algeron/pact/provider/core/ArrayMatcherTest.java// Java source level: 1.8import org.junit.Test;import static org.assertj.core.api.Assertions.assertThat;class ArrayMatcherTest {}"""messages = [{"role": "system", "content": SYSTEM},{"role": "user", "content": f"{INSTRUCTION}\n\n```\n{context}\n```"},]```**1. Fused weights with transformers** (about 52 GB of accelerator memory inbfloat16):```pythonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizerREPO = "SASVAAI/gemma-4-26b-jUnitTestGeneration"tokenizer = AutoTokenizer.from_pretrained(REPO)model = AutoModelForCausalLM.from_pretrained(REPO, dtype=torch.bfloat16, device_map="auto")model.eval()inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device)out = model.generate(**inputs, max_new_tokens=1024, do_sample=False)print(tokenizer.decode(out[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True).strip())```**2. Fused weights with vLLM** (how the numbers below were produced; thetensor-parallel degree must divide the 16 attention heads):```bashpip install "vllm>=0.19.1"vllm serve SASVAAI/gemma-4-26b-jUnitTestGeneration --tensor-parallel-size 4 --max-model-len 10240``````pythonfrom openai import OpenAIclient = OpenAI(base_url="http://localhost:8000/v1", api_key="unused")# one greedy answerr = client.chat.completions.create(model="SASVAAI/gemma-4-26b-jUnitTestGeneration",messages=messages, temperature=0, max_tokens=1024,)# four more candidates, as in pass@5extra = client.chat.completions.create(model="SASVAAI/gemma-4-26b-jUnitTestGeneration",messages=messages, temperature=0.8, top_p=0.95, n=4, max_tokens=1024,)candidates = [r.choices[0].message.content] + [c.message.content for c in extra.choices]```**3. Adapter on the base model** (base in 4-bit fits one 24 GB-class GPU,about 16 GB):```pythonimport torchfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizerBASE = "google/gemma-4-26B-A4B-it"REPO = "SASVAAI/gemma-4-26b-jUnitTestGeneration"tokenizer = AutoTokenizer.from_pretrained(REPO, subfolder="adapter")model = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16, device_map="auto")model = PeftModel.from_pretrained(model, REPO, subfolder="adapter")model.eval()# then generate exactly as in path 1```For the 4-bit base pass `quantization_config=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.bfloat16)`, which reproduces the training-timenumerics. vLLM cannot attach a LoRA to this architecture (its`Gemma4ForConditionalGeneration` does not list LoRA support), which is why thefused weights are at the root.The greedy output recorded for this row during evaluation (vLLM, fusedweights). It compiled, passed, and killed 1 of the focal method's 2 mutants:```java@Testpublic void shouldMatchWhenValueIsPresentInPatternArray() {assertThat(ArrayMatcher.matches(new String[]{"a", "b", "c"}, "b")).isTrue();}```> Decoding matters. pass@1 was scored greedily and pass@5 added four samples> at T=0.8, top_p 0.95, all with `max_new_tokens=1024` through the chat> template. No other sampling setting was validated.## Training details**Data.** 5,488 training rows and 332 validation rows built from[methods2test](https://github.com/microsoft/methods2test) (MIT), through[`andstor/methods2test_raw`](https://huggingface.co/datasets/andstor/methods2test_raw)(revision `1a0f08c6`), `_meta` (`ae2bdff5`) and `_runnable` (`ed8cded6`), by adeterministic script (`autocatalyst.datagen.methods2test`, seed 0). No modelgenerated any training content: every target is a test a developer wrote inan open-source project.Row construction, as recorded in the builder's manifest:- **Training rows** come from methods2test's validation split: 44,298 rowsscanned, 26,752 eligible, at most 25 rows per project, 5,488 kept from 394projects. Dropped: 10,754 with no resolvable commit, 2,684 tests without anassertion, 225 constructor focal methods, 3,361 inputs over 7,000 characters,522 targets over 2,500 characters, 141 inputs that grew too long once thetest class's imports were added.- **Validation rows** come from methods2test's test split, restricted to the`_runnable` ids (Maven projects that build): 78,388 scanned, 2,903 eligible,at most 6 rows per project, 400 requested. Each candidate's reference testwas then run through the full harness below; 75 were rejected (23 did notcompile on the pinned toolchain, 24 killed no mutant, 9 failed, 19 PITerrors) and 332 kept from 86 projects. **Every validation reference passesall three gates**, so a perfect model scores 1.0.- **No project appears in both splits** (394 training projects, 86 validationprojects, overlap 0).- **Input** never contains the reference test or any other test method of thetest class.- **Java levels in validation:** 1.8 (149 rows), 1.7 (80), 1.6 (72), 1.5 (31).| | ||---|---|| Train samples | 5,488 (394 projects) || Validation samples | 332 (86 projects) || Project overlap | 0 || Prompt format | chat template + system prompt + instruction / fenced-context user turn (see Intended use) || Loss masking | answer tokens only; prompt tokens set to `-100` || Truncation | sequences cut to `max_seq_len` 4096; no sample was dropped for length |**Source-code licences.** methods2test is MIT, but each row's focal class andtest come from a third-party Java project with its own licence. The licencefield in `andstor/methods2test_raw` reads only `licensed` for 391 of the 394training projects (2 are Apache-2.0, 1 "Other") and for 85 of the 86validation projects (1 is GPL-3.0), so per-project licences were not verifiedfor this release. Review this before a public release.An LLM (Claude Opus 4.6, `claude-opus-4-6`, via an internal inference gateway)proposed the hyperparameters the search tried and wrote the system prompt fromthe project's problem statement. It generated no training content and computedno metric; every metric was computed by compiling and running Java.### Method| | ||---|---|| SFT method | `qlora` || Base quantisation during training | 4-bit NF4, double quantisation, bf16 compute (`bitsandbytes`) || Refinement stage | none || Auto class | `AutoModelForCausalLM` (resolves to `Gemma4ForConditionalGeneration`) || Hardware | 6x NVIDIA H100 80GB HBM3, `torchrun --nproc_per_node=6` |The project allowed one method (`qlora`). No refinement stage ran; thepublished adapter is the SFT adapter and the root weights are its merge.### Final hyperparameters| Hyperparameter | Value | Source ||---|---|---|| `learning_rate` | 0.0002 | `[TRAIN]` cmdline || `lr_scheduler_type` | cosine | `[TRAIN]` cmdline || `num_train_epochs` | 2 | platform hyperparameter record, `adapter/trainer_state.json` || `per_device_train_batch_size` | 1 | platform hyperparameter record, `adapter/trainer_state.json` || `gradient_accumulation_steps` | 4 | platform hyperparameter record || `max_seq_length` | 4096 | platform hyperparameter record || `warmup_ratio` | 0.05 | platform hyperparameter record || `weight_decay` | 0.01 | platform hyperparameter record || `loraplus_lr_ratio` | 1.0 (off) | platform hyperparameter record || `lora_r` / `lora_alpha` / `lora_dropout` | 16 / 32 / 0.05 | `[TRAIN]` cmdline, `adapter/adapter_config.json` || `use_rslora` / `use_dora` | `false` / `false` | `adapter/adapter_config.json` || `target_modules` | the 7 listed in Model details | `adapter/adapter_config.json` || `load_in_4bit` | `true` (NF4, double quant, bf16 compute) | `[TRAIN]` cmdline |**Effective batch size: 24** (`1 x 4 x 6`). Optimizer steps: 458 (229 perepoch).`neftune_noise_alpha` (0.0), `use_dora`, `use_rslora` and `lora_init`(`default`) were left at their no-op defaults. KD parameters are omitteddeliberately: this is a `qlora` run, not a distillation run.> Provenance note: every value above was recovered from the platform database> (`runs`, `experiments`, `events` tables for run 14) and cross-checked against> the `[TRAIN]` command line recorded in the run log and against the shipped> `adapter/adapter_config.json`. The logged command line is cut off after> `--epochs`; the values after it come from the run's recorded hyperparameter> JSON.### How these values were chosen> These hyperparameters were selected by an automated search> (`autocatalyst.cli.run_autoresearch`): an agent proposes one change at a> time, runs train then eval, and keeps or discards on `junit_pass_at_k`> (higher is better).Run 14 ran **6 trials in 12 h 25 m** (2026-10-09 18:09 to 2026-10-10 06:35UTC); all 6 scored. This checkpoint is **trial 1**, the search's startingconfiguration, and no later trial beat it. Every trial trained on the same5,488 rows and was scored on the same 332 validation rows.| # | r | Dropout | LR | Epochs | Train | Eval | pass@5 | Kept ||---|---|---|---|---|---|---|---|---|| **1** | **16** | **0.05** | **2e-4** | **2** | **92 m** | **29 m** | **0.503012** | **yes** || 2 | 16 | 0.05 | 2e-4 | 3 | 137 m | 30 m | 0.445783 | no || 3 | 16 | 0.05 | 1e-4 | 2 | 92 m | 14 m | 0.466867 | no || 4 | 32 | 0.05 | 2e-4 | 2 | 92 m | 15 m | 0.481928 | no || 5 | 16 | 0.10 | 2e-4 | 2 | 92 m | 15 m | 0.430723 | no || 6 | 16 | 0.05 | 3e-4 | 2 | 92 m | 43 m | 0.478916 | no |All trials: QLoRA, `lora_alpha = 2 x r`, cosine schedule, batch 1 per device,gradient accumulation 4, warmup 0.05, weight decay 0.01, `max_seq_len` 4096,LoRA+ off, rsLoRA and DoRA off.**What the search actually established: nothing beyond noise.** Five singlechanges from the starting point (one more epoch, half or 1.5x the learningrate, rank 32, dropout 0.10) all scored lower, between 0.431 and 0.482. pass@5mixes four temperature-0.8 samples into each row's result, so two evaluationsof the *same* weights differ from run to run; the spread of these six trials(0.43 to 0.50) is the best available estimate of that noise. Treat trialswithin about 0.05 of each other as tied, and read 0.503 as a high draw.**The previous search on this task.** Run 12 (2026-10-08) searched the samespace on an earlier version of the dataset (333 validation rows, no Java levelline in the prompt) and kept on greedy pass@1. Its best checkpoint scored pass@10.276. In a separate check that sampled it five times at temperature 0.8, itreached pass@5 0.486 (0.505 counting its greedy answer too). So thischeckpoint is not better than run 12's: its greedy pass@1 is lower (0.247), andits pass@5 is about level. The jump from "0.276" to "0.503" between the tworuns is the change of metric, not of model.**Search space.** Four knobs were varied (`LORA_R`, `LORA_DROPOUT`,`LEARNING_RATE`, `EPOCHS`). `LR_SCHEDULER`, `GRAD_ACCUM`, `WARMUP_RATIO`,`WEIGHT_DECAY`, `MAX_SEQ_LEN`, `LORAPLUS_LR_RATIO`, `USE_RSLORA`, `USE_DORA`,`BATCH_SIZE` and the training method were never moved.**Observed training metrics** (this checkpoint).| | ||---|---|| Final train loss (mean over the run) | 0.7416771020431185 || Last logged train loss (step 450) | 0.5607 (grad norm 0.31, token accuracy 0.864) || Final eval loss (teacher-forced, answer tokens) | 0.5725216269493103 || Eval mean token accuracy | 0.8667 || Train runtime | 5,444.8575 s || Total FLOPs | 1.6958247325338173e+18 || Throughput | 2.016 samples/s, 0.084 steps/s |458 optimizer steps ran. The logged train loss fell from 5.8956 at step 10(grad norm 8.0) to 0.5607 at step 450, with a minimum of 0.5260; the reportedtrain loss is the mean over the run, not a converged value.## Evaluation**Protocol.** All 332 validation rows, prompts rendered through the chattemplate, `max_new_tokens=1024`. The platform merged the adapter into the baseand generated with vLLM 0.19.1 in bfloat16 at tensor-parallel 4 on four H100s:one greedy answer per row, then four more sampled at temperature 0.8, top_p0.95. Generation plus grading took 1,722 s. The merged weights it served arethe ones at this repository's root.**The harness** (`junit_mutation` evaluator) grades each candidate inside itsown project, never by comparing text:1. Check out the project at the row's commit and insert the candidate methodinto the test class.2. **Compile:** `mvn test-compile` (JDK 8, Maven 3.6.3).3. **Pass:** run that one test method (`mvn test -Dtest=Class#method`); it mustpass against the real implementation.4. **Kill:** mutate the focal class with PIT 1.14.4 and run only the candidatetest against the mutants; it must kill at least one mutant of the focalmethod.A candidate scores 1 only if it clears all three gates. pass@1 is the greedycandidate's score; pass@5 counts a row as solved if any of the five candidatesscores 1.| Metric | Value ||---|---|| pass@5, greedy + 4 samples (**the search metric**) | 0.503012 (167 / 332) || pass@1, greedy | 0.246988 (82 / 332) || Greedy compile rate | 0.421687 (140 / 332) || Greedy test-pass rate | 0.246988 (82 / 332) || Greedy mean kill fraction (killed / mutants of the focal method) | 0.206093 |**Where the greedy answers fail** (from `adapter/predictions.jsonl`):| Greedy outcome | Rows | Share ||---|---|---|| Does not compile | 192 | 57.8% || …of which ran into the 1,024-token cap | 66 | 19.9% || Compiles but the test fails | 58 | 17.5% || Passes but kills no mutant | 0 | 0% || Clears all three gates | 82 | 24.7% |The 66 capped outputs are repetition loops; every one fails to compile. Themedian greedy answer is 119 tokens against a reference median of 105. Of the58 test failures, 35 are failed assertions (`AssertionError`,`ComparisonFailure`, `AssertionFailedError`): the test ran but expected adifferent value from the one the code returns. The rest are exceptions thrownduring the test. Every greedy test that passed also killed a mutant, so themutation gate rejected nothing here.**Where the other 85 pass@5 wins come from.** Of the 167 solved rows, 82 weresolved by the greedy answer and 85 only by a sampled one (attempt 2: 33, 3: 21,4: 15, 5: 16).**Baseline for comparison. Not measured.** The untuned`google/gemma-4-26B-A4B-it` was never scored on these 332 rows, so nothing herequantifies how much of the score the fine-tuning is responsible for. This isthe most important gap in this card.**This is a validation split the search selected against.** 6 trials werescored on these same 332 rows and the best was kept, so expect optimistic biason top of the sampling noise already described. The rows come from projectsthat do not appear in training, but from the same methods2test snapshot, sothey are unseen projects, not code written after the training data.**The evaluation set is reproducible.** `adapter/predictions.jsonl` holds everyone of the 332 rows: instruction, context, greedy prediction, reference test,and the harness verdict (`stage`, compiler or surefire error text, mutants,kills, per-attempt stages and the winning candidate). Local paths in errortext are replaced with `<project>/`.## Limitations and bias**pass@5 needs a test runner.** Without one, you get the greedy answer andpass@1 0.247: three of four single answers fail.**No baseline, so no established gain.** See Evaluation.**One in five greedy answers never stops.** Repetition loops consume the whole1,024-token budget and never compile. Treat a capped output as a failure.**Most failures are compile errors.** Using a class or method that is notvisible, an import the test class lacks, or a language feature above theproject's Java level. Keep the `// Java source level:` line and the test class'simports in the prompt; they are what the model uses to avoid this.**Passing tests encode current behaviour.** The model writes tests that passagainst the implementation as it is. If the method has a bug, a passing testlocks the bug in.**Killing one mutant is a low bar.** The gate needs one killed mutant, notall; the mean kill fraction is 0.21. A passing test is not evidence ofthorough coverage.**Prompt shape is the contract.** Change the system prompt, the instructionsentence, the context block's order, or the code fence, and you are evaluatinga model nobody measured.**Domain narrowness.** Maven projects from GitHub mined by methods2test, Java1.5 to 1.8 in evaluation (training also saw 9, 10 and 11), with the JUnit 4,JUnit 5 or TestNG setup and assertion libraries those projects use. Gradle builds, newer Java, Kotlinand non-English identifiers are unmeasured.**Inherits all biases and limitations of the base model.** This adapterchanges 0.07% of the parameters and was not evaluated for safety or fairness.The base model's own card governs those properties.## Merged-weights equivalenceThe root weights are `adapter/` merged into the base in bfloat16(`PeftModel.merge_and_unload` through `autocatalyst.serving.merge`,transformers 5.6.2). The merge was written as one 49 GB shard plus one 2.3 GBshard; for this release its tensors were copied unchanged into 11 shards of atmost 5 GB (same tensor names, dtypes and values; 26 sampled tensors werechecked equal to the source). They are the weights the evaluation above wasserved from, so the numbers in this card are the fused model's numbers. Themerged directory keeps the untouched vision tower and the processor config soit loads as the base does.## Environmental impact| | ||---|---|| Hardware | 6x NVIDIA H100 80GB HBM3 || Training time | 90.7 minutes (5,444.86 s) || Cloud provider / region | on-premise |Covers this trial only. The full 6-trial search that selected it took12 h 25 m on the same hardware.## Framework versions- PEFT 0.18.1- TRL: 1.0.0- Transformers: 5.7.0.dev0 (git main) for training; 5.6.2 for the merge- Pytorch: 2.5.1+cu121- bitsandbytes: 0.49.2- flash-attn: 2.8.3- vLLM: 0.19.1 (evaluation)- Evaluation toolchain: JDK 8, Maven 3.6.3, PIT 1.14.4- Python: 3.12.3PEFT's version is the one recorded in `adapter/adapter_config.json` at savetime; the rest are the pinned versions of the training and evaluationenvironments. `transformers` is a git-main build: the `gemma4` architecture isnot in the stable PyPI release used for training.## Citation```bibtex@misc{gemma4_junit_test_generation_2026,title = {Gemma-4-26B-A4B JUnit Test Generator},author = {{SASVA AI Model Cognition Labs}},year = {2026},url = {https://huggingface.co/SASVAAI/gemma-4-26b-jUnitTestGeneration}}```Training and evaluation data: methods2test, Tufano et al., "Methods2Test: Adataset of focal methods mapped to test cases", MSR 2022,https://github.com/microsoft/methods2test (MIT).
1234567891011121314151617181920212223# LoRA adapter (this subfolder)
The QLoRA adapter that was merged into the weights at the repository root.Same training, same evaluation, same numbers: everything is documented in theroot `README.md`. Load it on the base model instead of the fused weights whenmemory is tight (the base in 4-bit plus this adapter fits one 24 GB-class GPU):
```pythonfrom peft import PeftModelfrom transformers import AutoModelForCausalLM, AutoTokenizer
REPO = "SASVAAI/gemma-4-26b-jUnitTestGeneration"tokenizer = AutoTokenizer.from_pretrained(REPO, subfolder="adapter")model = AutoModelForCausalLM.from_pretrained("google/gemma-4-26B-A4B-it", dtype="bfloat16", device_map="auto")model = PeftModel.from_pretrained(model, REPO, subfolder="adapter")```
Files: `adapter_config.json`, `adapter_model.safetensors` (37,232,104 bytes,410 bfloat16 tensors), the tokenizer and chat template the adapter was trainedwith, and the training run's `trainer_state.json`, `all_results.json`,`train_results.json`, `eval_results.json` and `predictions.jsonl` (all 332validation rows with the greedy prediction, the reference test and the harnessverdict for every candidate).12345678910111213141516171819202122232425262728293031323334353637383940414243444546{ "alora_invocation_tokens": null, "alpha_pattern": {}, "arrow_config": null, "auto_mapping": null, "base_model_name_or_path": "google/gemma-4-26B-A4B-it", "bias": "none", "corda_config": null, "ensure_weight_tying": false, "eva_config": null, "exclude_modules": ".*vision_tower.*", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layer_replication": null, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 32, "lora_bias": false, "lora_dropout": 0.05, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "peft_version": "0.18.1", "qalora_group_size": 16, "r": 16, "rank_pattern": {}, "revision": null, "target_modules": [ "k_proj", "down_proj", "q_proj", "up_proj", "gate_proj", "o_proj", "v_proj" ], "target_parameters": null, "task_type": "CAUSAL_LM", "trainable_token_indices": null, "use_dora": false, "use_qalora": false, "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:d63a81f1a72e6ddb027c24afd3bb1ab5620dba46dd33f2b56f4265b5f4843423size 372321041234567{ "total_flos": 1.6958247325338173e+18, "train_loss": 0.7416771020431185, "train_runtime": 5444.8575, "train_samples_per_second": 2.016, "train_steps_per_second": 0.084}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390{# Template: Google Gemma 4 Canonical Chat Template Author: Google Gemma Engineering Team Published: 2026-07-09 Context: Fixed tool-calling loops, turn closures, and thinking content-ordering.#}{%- macro format_parameters(properties, required, filter_keys=false) -%} {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%} {%- set ns = namespace(found_first=false) -%} {%- for key, value in properties | dictsort -%} {%- set add_comma = false -%} {%- if not filter_keys or key not in standard_keys -%} {%- if ns.found_first %},{% endif -%} {%- set ns.found_first = true -%} {{ key }}:{ {%- if value['description'] -%} description:<|"|>{{ value['description'] }}<|"|> {%- set add_comma = true -%} {%- endif -%} {%- if value['type'] | upper == 'STRING' -%} {%- if value['enum'] -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} enum:{{ format_argument(value['enum']) }} {%- endif -%} {%- elif value['type'] | upper == 'ARRAY' -%} {%- if value['items'] is mapping and value['items'] -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} items:{ {%- set ns_items = namespace(found_first=false) -%} {%- for item_key, item_value in value['items'] | dictsort -%} {%- if item_value is not none -%} {%- if ns_items.found_first %},{% endif -%} {%- set ns_items.found_first = true -%} {%- if item_key == 'properties' -%} properties:{ {%- if item_value is mapping -%} {{- format_parameters(item_value, value['items']['required'] | default([])) -}} {%- endif -%} } {%- elif item_key == 'required' -%} required:[ {%- for req_item in item_value -%} <|"|>{{- req_item -}}<|"|> {%- if not loop.last %},{% endif -%} {%- endfor -%} ] {%- elif item_key == 'type' -%} {%- if item_value is string -%} type:{{ format_argument(item_value | upper) }} {%- else -%} type:{{ format_argument(item_value | map('upper') | list) }} {%- endif -%} {%- else -%} {{ item_key }}:{{ format_argument(item_value) }} {%- endif -%} {%- endif -%} {%- endfor -%} } {%- endif -%} {%- endif -%} {%- if value['nullable'] %} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} nullable:true {%- endif -%} {%- if value['type'] | upper == 'OBJECT' -%} {%- if value['properties'] is defined and value['properties'] is mapping -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} properties:{ {{- format_parameters(value['properties'], value['required'] | default([])) -}} } {%- elif value is mapping -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} properties:{ {{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}} } {%- endif -%} {%- if value['required'] -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} required:[ {%- for item in value['required'] | default([]) -%} <|"|>{{- item -}}<|"|> {%- if not loop.last %},{% endif -%} {%- endfor -%} ] {%- endif -%} {%- endif -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} type:<|"|>{{ value['type'] | upper }}<|"|>} {%- endif -%} {%- endfor -%}{%- endmacro -%}{%- macro format_function_declaration(tool_data) -%} declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|> {%- set params = tool_data['function']['parameters'] -%} {%- if params -%} ,parameters:{ {%- if params['properties'] -%} properties:{ {{- format_parameters(params['properties'], params['required']) -}} }, {%- endif -%} {%- if params['required'] -%} required:[ {%- for item in params['required'] -%} <|"|>{{- item -}}<|"|> {{- ',' if not loop.last -}} {%- endfor -%} ], {%- endif -%} {%- if params['type'] -%} type:<|"|>{{- params['type'] | upper -}}<|"|>} {%- endif -%} {%- endif -%} {%- if 'response' in tool_data['function'] -%} {%- set response_declaration = tool_data['function']['response'] -%} ,response:{ {%- if response_declaration['description'] -%} description:<|"|>{{- response_declaration['description'] -}}<|"|>, {%- endif -%} {%- if response_declaration['type'] | upper == 'OBJECT' -%} type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>} {%- endif -%} {%- endif -%} }{%- endmacro -%}{%- macro format_argument(argument, escape_keys=True) -%} {%- if argument is none -%} {{- 'null' -}} {%- elif argument is string -%} {{- '<|"|>' + argument + '<|"|>' -}} {%- elif argument is boolean -%} {{- 'true' if argument else 'false' -}} {%- elif argument is mapping -%} {{- '{' -}} {%- set ns = namespace(found_first=false) -%} {%- for key, value in argument | dictsort -%} {%- if ns.found_first %},{% endif -%} {%- set ns.found_first = true -%} {%- if escape_keys -%} {{- '<|"|>' + key + '<|"|>' -}} {%- else -%} {{- key -}} {%- endif -%} :{{- format_argument(value, escape_keys=escape_keys) -}} {%- endfor -%} {{- '}' -}} {%- elif argument is sequence -%} {{- '[' -}} {%- for item in argument -%} {{- format_argument(item, escape_keys=escape_keys) -}} {%- if not loop.last %},{% endif -%} {%- endfor -%} {{- ']' -}} {%- else -%} {{- argument -}} {%- endif -%}{%- endmacro -%}{%- macro strip_thinking(text) -%} {%- set ns = namespace(result='') -%} {%- for part in text.split('<channel|>') -%} {%- if '<|channel>' in part -%} {%- set ns.result = ns.result + part.split('<|channel>')[0] -%} {%- else -%} {%- set ns.result = ns.result + part -%} {%- endif -%} {%- endfor -%} {{- ns.result | trim -}}{%- endmacro -%}
{%- macro format_tool_response_block(tool_name, response) -%} {{- '<|tool_response>' -}} {%- if response is mapping -%} {{- 'response:' + tool_name + '{' -}} {%- for key, value in response | dictsort -%} {{- key -}}:{{- format_argument(value, escape_keys=False) -}} {%- if not loop.last %},{% endif -%} {%- endfor -%} {{- '}' -}} {%- else -%} {{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}} {%- endif -%} {{- '<tool_response|>' -}}{%- endmacro -%}
{#- ===== SETUP ===== -#}{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}{%- set loop_messages = messages -%}{%- set enable_thinking = enable_thinking | default(false) -%}{%- set preserve_thinking = preserve_thinking | default(false) -%}{{- bos_token -}}{#- Handle System/Tool Definitions Block -#}{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%} {{- '<|turn>system\n' -}} {#- Inject Thinking token at the very top of the FIRST system turn -#} {%- if enable_thinking -%} {{- '<|think|>\n' -}} {%- set ns.prev_message_type = 'think' -%} {%- endif -%} {%- if messages and messages[0]['role'] in ['system', 'developer'] -%} {%- if messages[0]['content'] is string -%} {{- messages[0]['content'] | trim -}} {%- elif messages[0]['content'] is sequence -%} {%- for item in messages[0]['content'] -%} {{- item['text'] | trim + ' '-}} {%- endfor -%} {%- endif -%} {%- set loop_messages = messages[1:] -%} {%- endif -%} {%- if tools -%} {%- for tool in tools %} {{- '<|tool>' -}} {{- format_function_declaration(tool) | trim -}} {{- '<tool|>' -}} {%- endfor %} {%- set ns.prev_message_type = 'tool' -%} {%- endif -%} {{- '<turn|>\n' -}}{%- endif %}
{#- Pre-scan: find last user message index for reasoning guard -#}{%- set ns_turn = namespace(last_user_idx=-1) -%}{%- for i in range(loop_messages | length) -%} {%- if loop_messages[i]['role'] == 'user' -%} {%- set ns_turn.last_user_idx = i -%} {%- endif -%}{%- endfor -%}
{#- Loop through messages -#}{%- for message in loop_messages -%} {%- if message['role'] != 'tool' -%} {%- set ns.prev_message_type = None -%} {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%} {#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#} {%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%} {%- if not continue_same_model_turn -%} {{- '<|turn>' + role + '\n' }}
{%- endif -%}
{#- Render reasoning/reasoning_content as thinking channel -#} {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%} {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%} {%- if thinking_text and thinking_gate -%} {{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}} {%- endif -%}
{%- if message.get('tool_calls') -%} {%- for tool_call in message.get('tool_calls') -%} {%- set function = tool_call['function'] -%} {{- '<|tool_call>call:' + function['name'] + '{' -}} {%- if function['arguments'] is mapping -%} {%- set ns_args = namespace(found_first=false) -%} {%- for key, value in function['arguments'] | dictsort -%} {%- if ns_args.found_first %},{% endif -%} {%- set ns_args.found_first = true -%} {{- key -}}:{{- format_argument(value, escape_keys=False) -}} {%- endfor -%} {%- elif function['arguments'] is none -%} {%- else -%} {{- raise_exception( "chat_template: tool_calls[].function.arguments must be a " "JSON object (mapping), not a string. Deserialize arguments " "before passing to the template." ) -}} {%- endif -%} {{- '}<tool_call|>' -}} {%- endfor -%} {%- set ns.prev_message_type = 'tool_call' -%} {%- endif -%}
{%- set ns_tr_out = namespace(flag=false) -%} {%- if message.get('tool_responses') -%} {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#} {%- for tool_response in message.get('tool_responses') -%} {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}} {%- set ns_tr_out.flag = true -%} {%- set ns.prev_message_type = 'tool_response' -%} {%- endfor -%} {%- elif message.get('tool_calls') -%} {#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#} {%- set ns_tool_scan = namespace(stopped=false) -%} {%- for k in range(loop.index0 + 1, loop_messages | length) -%} {%- if ns_tool_scan.stopped -%} {%- elif loop_messages[k]['role'] != 'tool' -%} {%- set ns_tool_scan.stopped = true -%} {%- else -%} {%- set follow = loop_messages[k] -%} {#- Resolve tool_call_id to function name -#} {%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%} {%- for tc in message.get('tool_calls') -%} {%- if tc.get('id') == follow.get('tool_call_id') -%} {%- set ns_tname.name = tc['function']['name'] -%} {%- endif -%} {%- endfor -%} {#- Handle content as string or content-parts array -#} {%- set tool_body = follow.get('content') -%} {%- if tool_body is string -%} {{- format_tool_response_block(ns_tname.name, tool_body) -}} {%- elif tool_body is sequence and tool_body is not string -%} {%- set ns_txt = namespace(s='') -%} {%- for part in tool_body -%} {%- if part.get('type') == 'text' -%} {%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%} {%- endif -%} {%- endfor -%} {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}} {%- for part in tool_body -%} {%- if part.get('type') in ['image', 'image_url'] -%} {{- '<|image|>' -}} {%- elif part.get('type') in ['audio', 'input_audio'] -%} {{- '<|audio|>' -}} {%- elif part.get('type') == 'video' -%} {{- '<|video|>' -}} {%- endif -%} {%- endfor -%} {%- else -%} {{- format_tool_response_block(ns_tname.name, tool_body) -}} {%- endif -%} {%- set ns_tr_out.flag = true -%} {%- set ns.prev_message_type = 'tool_response' -%} {%- endif -%} {%- endfor -%} {%- endif -%}
{%- set captured_content -%} {%- if message.get('content') is string -%} {%- if role == 'model' -%} {{- strip_thinking(message['content']) -}} {%- else -%} {{- message['content'] | trim -}} {%- endif -%} {%- elif message.get('content') is sequence -%} {%- for item in message['content'] -%} {%- if item.get('type') == 'text' -%} {%- if role == 'model' -%} {{- strip_thinking(item['text']) -}} {%- else -%} {{- item['text'] | trim -}} {%- endif -%} {%- elif item.get('type') in ['image', 'image_url'] -%} {{- '<|image|>' -}} {%- elif item.get('type') in ['audio', 'input_audio'] -%} {{- '<|audio|>' -}} {%- elif item.get('type') == 'video' -%} {{- '<|video|>' -}} {%- endif -%} {%- endfor -%} {%- endif -%} {%- endset -%}
{{- captured_content -}} {%- set has_content = captured_content | trim | length > 0 -%}
{#- Forward-scan: find next non-tool message role for continuation detection -#} {%- set next_nt = namespace(role=None, found=false) -%} {%- for j in range(loop.index0 + 1, loop_messages | length) -%} {%- if not next_nt.found -%} {%- if loop_messages[j]['role'] != 'tool' -%} {%- set next_nt.role = loop_messages[j]['role'] -%} {%- set next_nt.found = true -%} {%- endif -%} {%- endif -%} {%- endfor -%}
{%- set continues_into_next = ( role == 'model' and next_nt.role == 'assistant' and (not message.get('tool_calls') or ns_tr_out.flag) ) -%}
{%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%} {{- '<|tool_response>' -}} {%- elif continues_into_next -%} {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%} {{- '<turn|>\n' -}} {%- endif -%}
{#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#} {%- set ns.prev_non_tool_role = message['role'] -%} {%- endif -%}{%- endfor -%}
{%- if add_generation_prompt -%} {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%} {{- '<|turn>model\n' -}} {%- if not enable_thinking -%} {{- '<|channel>thought\n<channel|>' -}} {%- endif -%} {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%} {{- '<|channel>thought\n' -}} {%- endif -%}{%- endif -%}1234567891011{ "metrics": { "junit_pass_rate": 0.2469879518072289, "junit_compile_rate": 0.42168674698795183, "junit_test_rate": 0.2469879518072289, "junit_kill_fraction": 0.2060925018756344, "junit_pass_at_k": 0.5030120481927711, "junit_attempts": 5.0 }, "num_samples": 332}123version https://git-lfs.github.com/spec/v1oid sha256:cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0fsize 32169626123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142{ "audio_token": "<|audio|>", "backend": "tokenizers", "boa_token": "<|audio>", "boi_token": "<|image>", "bos_token": "<bos>", "eoa_token": "<audio|>", "eoc_token": "<channel|>", "eoi_token": "<image|>", "eos_token": "<eos>", "eot_token": "<turn|>", "escape_token": "<|\"|>", "etc_token": "<tool_call|>", "etd_token": "<tool|>", "etr_token": "<tool_response|>", "extra_special_tokens": [ "<|video|>" ], "image_token": "<|image|>", "is_local": false, "local_files_only": false, "mask_token": "<mask>", "model_max_length": 1000000000000000019884624838656, "model_specific_special_tokens": { "audio_token": "<|audio|>", "boa_token": "<|audio>", "boi_token": "<|image>", "eoa_token": "<audio|>", "eoc_token": "<channel|>", "eoi_token": "<image|>", "eot_token": "<turn|>", "escape_token": "<|\"|>", "etc_token": "<tool_call|>", "etd_token": "<tool|>", "etr_token": "<tool_response|>", "image_token": "<|image|>", "soc_token": "<|channel>", "sot_token": "<|turn>", "stc_token": "<|tool_call>", "std_token": "<|tool>", "str_token": "<|tool_response>", "think_token": "<|think|>" }, "pad_token": "<pad>", "padding_side": "right", "processor_class": "Gemma4Processor", "response_schema": { "properties": { "content": { "type": "string" }, "role": { "const": "assistant" }, "thinking": { "type": "string" }, "tool_calls": { "items": { "properties": { "function": { "properties": { "arguments": { "additionalProperties": {}, "type": "object", "x-parser": "gemma4-tool-call" }, "name": { "type": "string" } }, "type": "object", "x-regex": "call\\:(?P<name>\\w+)(?P<arguments>\\{.*\\})" }, "type": { "const": "function" } }, "type": "object" }, "type": "array", "x-regex-iterator": "<\\|tool_call>(.*?)<tool_call\\|>" } }, "type": "object", "x-regex": "(\\<\\|channel\\>thought\\n(?P<thinking>.*?)\\<channel\\|\\>)?(?P<tool_calls>\\<\\|tool_call\\>.*\\<tool_call\\|\\>)?(?P<content>(?:(?!\\<turn\\|\\>)(?!\\<\\|tool_response\\>).)+)?(?:\\<turn\\|\\>|\\<\\|tool_response\\>)?" }, "response_template": { "defaults": { "role": "assistant" }, "fields": { "content": { "close": [ "<turn|>", "<|tool_response>", "<eos>" ], "content": "text" }, "thinking": { "close": "<channel|>", "content": "text", "open": "<|channel>thought\n" }, "tool_calls": { "close": "<tool_call|>", "content": "json", "content_args": { "string_delims": [ [ "<|\"|>", "<|\"|>" ] ], "unquoted_keys": true }, "open_pattern": "<\\|tool_call>call:(?P<name>\\w+)", "repeats": true, "transform": { "function": { "arguments": "{content}", "name": "{name}" }, "type": "function" } } }, "start_anchor": [ "<|turn>model\n", "<tool_response|>" ] }, "soc_token": "<|channel>", "sot_token": "<|turn>", "stc_token": "<|tool_call>", "std_token": "<|tool>", "str_token": "<|tool_response>", "think_token": "<|think|>", "tokenizer_class": "GemmaTokenizer", "unk_token": "<unk>"}1234567{ "total_flos": 1.6958247325338173e+18, "train_loss": 0.7416771020431185, "train_runtime": 5444.8575, "train_samples_per_second": 2.016, "train_steps_per_second": 0.084}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504{ "best_global_step": null, "best_metric": null, "best_model_checkpoint": null, "epoch": 2.0, "eval_steps": 9999, "global_step": 458, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "entropy": 1.0486987829208374, "epoch": 0.04371584699453552, "grad_norm": 8.0, "learning_rate": 7.82608695652174e-05, "loss": 5.89563102722168, "mean_token_accuracy": 0.4319680668413639, "num_tokens": 239087.0, "step": 10 }, { "entropy": 0.884407639503479, "epoch": 0.08743169398907104, "grad_norm": 1.2578125, "learning_rate": 0.00016521739130434784, "loss": 2.102974700927734, "mean_token_accuracy": 0.6724865823984146, "num_tokens": 475150.0, "step": 20 }, { "entropy": 1.1834268897771836, "epoch": 0.13114754098360656, "grad_norm": 0.70703125, "learning_rate": 0.0001999061302243977, "loss": 1.1062660217285156, "mean_token_accuracy": 0.7651933252811431, "num_tokens": 717465.0, "step": 30 }, { "entropy": 0.7881059303879738, "epoch": 0.17486338797814208, "grad_norm": 0.302734375, "learning_rate": 0.000199333119673151, "loss": 0.7654059410095215, "mean_token_accuracy": 0.8342122867703438, "num_tokens": 966531.0, "step": 40 }, { "entropy": 0.6791177123785019, "epoch": 0.2185792349726776, "grad_norm": 0.2890625, "learning_rate": 0.00019824223223072895, "loss": 0.6887028694152832, "mean_token_accuracy": 0.8460865274071694, "num_tokens": 1212977.0, "step": 50 }, { "entropy": 0.6520723849534988, "epoch": 0.26229508196721313, "grad_norm": 16.125, "learning_rate": 0.00019663915527913625, "loss": 0.6579425811767579, "mean_token_accuracy": 0.8477372005581856, "num_tokens": 1453667.0, "step": 60 }, { "entropy": 0.6275352656841278, "epoch": 0.30601092896174864, "grad_norm": 0.376953125, "learning_rate": 0.00019453224651931635, "loss": 0.6366048336029053, "mean_token_accuracy": 0.853670459985733, "num_tokens": 1700109.0, "step": 70 }, { "entropy": 0.6275677800178527, "epoch": 0.34972677595628415, "grad_norm": 0.228515625, "learning_rate": 0.00019193249039796854, "loss": 0.629797887802124, "mean_token_accuracy": 0.8567495480179786, "num_tokens": 1956002.0, "step": 80 }, { "entropy": 0.6235676869750023, "epoch": 0.39344262295081966, "grad_norm": 0.50390625, "learning_rate": 0.00018885344083972914, "loss": 0.6312247753143311, "mean_token_accuracy": 0.852640126645565, "num_tokens": 2204874.0, "step": 90 }, { "entropy": 0.62629174888134, "epoch": 0.4371584699453552, "grad_norm": 0.41796875, "learning_rate": 0.0001853111505832843, "loss": 0.630945348739624, "mean_token_accuracy": 0.8508004978299141, "num_tokens": 2458424.0, "step": 100 }, { "entropy": 0.6070425912737847, "epoch": 0.4808743169398907, "grad_norm": 0.3515625, "learning_rate": 0.00018132408748982356, "loss": 0.6076114654541016, "mean_token_accuracy": 0.8586151331663132, "num_tokens": 2703644.0, "step": 110 }, { "entropy": 0.6136491641402244, "epoch": 0.5245901639344263, "grad_norm": 0.283203125, "learning_rate": 0.0001769130382601629, "loss": 0.6096392631530761, "mean_token_accuracy": 0.8566672906279564, "num_tokens": 2942548.0, "step": 120 }, { "entropy": 0.5921711333096027, "epoch": 0.5683060109289617, "grad_norm": 0.203125, "learning_rate": 0.00017210100006251163, "loss": 0.6015676498413086, "mean_token_accuracy": 0.856255167722702, "num_tokens": 3198996.0, "step": 130 }, { "entropy": 0.5744436584413052, "epoch": 0.6120218579234973, "grad_norm": 8.8125, "learning_rate": 0.00016691306063588583, "loss": 0.5779120445251464, "mean_token_accuracy": 0.8660892397165298, "num_tokens": 3437901.0, "step": 140 }, { "entropy": 0.5826737284660339, "epoch": 0.6557377049180327, "grad_norm": 0.2412109375, "learning_rate": 0.00016137626749425377, "loss": 0.5811635494232178, "mean_token_accuracy": 0.8659511938691139, "num_tokens": 3683492.0, "step": 150 }, { "entropy": 0.5969281956553459, "epoch": 0.6994535519125683, "grad_norm": 0.2216796875, "learning_rate": 0.0001555194869133219, "loss": 0.6036740779876709, "mean_token_accuracy": 0.8583549842238426, "num_tokens": 3935944.0, "step": 160 }, { "entropy": 0.6209515765309334, "epoch": 0.7431693989071039, "grad_norm": 0.248046875, "learning_rate": 0.00014937325343513953, "loss": 0.6191730499267578, "mean_token_accuracy": 0.8536601454019547, "num_tokens": 4195223.0, "step": 170 }, { "entropy": 0.573480324447155, "epoch": 0.7868852459016393, "grad_norm": 0.265625, "learning_rate": 0.0001429696106751352, "loss": 0.5765636444091797, "mean_token_accuracy": 0.8647082209587097, "num_tokens": 4435668.0, "step": 180 }, { "entropy": 0.5718808308243751, "epoch": 0.8306010928961749, "grad_norm": 0.1982421875, "learning_rate": 0.000136341944261543, "loss": 0.5744711875915527, "mean_token_accuracy": 0.8627334550023079, "num_tokens": 4676607.0, "step": 190 }, { "entropy": 0.5809279806911946, "epoch": 0.8743169398907104, "grad_norm": 0.8515625, "learning_rate": 0.000129524807778196, "loss": 0.5852269649505615, "mean_token_accuracy": 0.8613690108060836, "num_tokens": 4927228.0, "step": 200 }, { "entropy": 0.5811030484735966, "epoch": 0.9180327868852459, "grad_norm": 0.73828125, "learning_rate": 0.00012255374261813944, "loss": 0.5799302101135254, "mean_token_accuracy": 0.8622894912958146, "num_tokens": 5174966.0, "step": 210 }, { "entropy": 0.5655277840793133, "epoch": 0.9617486338797814, "grad_norm": 0.2080078125, "learning_rate": 0.00011546509268726438, "loss": 0.5731849670410156, "mean_token_accuracy": 0.8623020827770234, "num_tokens": 5424008.0, "step": 220 }, { "entropy": 0.5541020051026956, "epoch": 1.0043715846994536, "grad_norm": 0.26171875, "learning_rate": 0.00010829581492401102, "loss": 0.5521286010742188, "mean_token_accuracy": 0.8678772892707434, "num_tokens": 5649285.0, "step": 230 }, { "entropy": 0.5556444957852363, "epoch": 1.048087431693989, "grad_norm": 1.515625, "learning_rate": 0.000101083286623004, "loss": 0.5597594261169434, "mean_token_accuracy": 0.8667374014854431, "num_tokens": 5885960.0, "step": 240 }, { "entropy": 0.5644011072814464, "epoch": 1.0918032786885246, "grad_norm": 0.8203125, "learning_rate": 9.386511056714527e-05, "loss": 0.565219783782959, "mean_token_accuracy": 0.8634485810995102, "num_tokens": 6135390.0, "step": 250 }, { "entropy": 0.5583239279687404, "epoch": 1.1355191256830601, "grad_norm": 0.2734375, "learning_rate": 8.667891898411531e-05, "loss": 0.5607303619384766, "mean_token_accuracy": 0.8667840331792831, "num_tokens": 6399066.0, "step": 260 }, { "entropy": 0.5657123997807503, "epoch": 1.1792349726775957, "grad_norm": 0.4609375, "learning_rate": 7.956217734936353e-05, "loss": 0.5595542907714843, "mean_token_accuracy": 0.8627277389168739, "num_tokens": 6645578.0, "step": 270 }, { "entropy": 0.5563506670296192, "epoch": 1.222950819672131, "grad_norm": 0.3359375, "learning_rate": 7.255198905846655e-05, "loss": 0.5601570129394531, "mean_token_accuracy": 0.8659737527370452, "num_tokens": 6884408.0, "step": 280 }, { "entropy": 0.5562774635851383, "epoch": 1.2666666666666666, "grad_norm": 0.57421875, "learning_rate": 6.568490198720426e-05, "loss": 0.5596513271331787, "mean_token_accuracy": 0.8656521663069725, "num_tokens": 7127266.0, "step": 290 }, { "entropy": 0.5515452794730663, "epoch": 1.3103825136612022, "grad_norm": 0.216796875, "learning_rate": 5.899671794785839e-05, "loss": 0.5530119895935058, "mean_token_accuracy": 0.8674060195684433, "num_tokens": 7367949.0, "step": 300 }, { "entropy": 0.5612388111650943, "epoch": 1.3540983606557377, "grad_norm": 0.2578125, "learning_rate": 5.252230603514081e-05, "loss": 0.5572527885437012, "mean_token_accuracy": 0.8650377497076989, "num_tokens": 7602388.0, "step": 310 }, { "entropy": 0.5349247701466083, "epoch": 1.3978142076502733, "grad_norm": 0.515625, "learning_rate": 4.629542083487931e-05, "loss": 0.5396371841430664, "mean_token_accuracy": 0.8693908914923668, "num_tokens": 7852679.0, "step": 320 }, { "entropy": 0.5618424162268638, "epoch": 1.4415300546448089, "grad_norm": 45.0, "learning_rate": 4.034852644323661e-05, "loss": 0.5663045406341553, "mean_token_accuracy": 0.8645561948418617, "num_tokens": 8109647.0, "step": 330 }, { "entropy": 0.5594642959535122, "epoch": 1.4852459016393442, "grad_norm": 1.703125, "learning_rate": 3.4712627213945084e-05, "loss": 0.5558950424194335, "mean_token_accuracy": 0.866220836341381, "num_tokens": 8355525.0, "step": 340 }, { "entropy": 0.5425299815833569, "epoch": 1.5289617486338798, "grad_norm": 2.34375, "learning_rate": 2.941710611596271e-05, "loss": 0.5427396774291993, "mean_token_accuracy": 0.8683088988065719, "num_tokens": 8601424.0, "step": 350 }, { "entropy": 0.5427556604146957, "epoch": 1.5726775956284151, "grad_norm": 0.2421875, "learning_rate": 2.4489571544277945e-05, "loss": 0.5439925193786621, "mean_token_accuracy": 0.8654883369803429, "num_tokens": 8839615.0, "step": 360 }, { "entropy": 0.5338973246514798, "epoch": 1.6163934426229507, "grad_norm": 0.255859375, "learning_rate": 1.9955713382522113e-05, "loss": 0.5421658992767334, "mean_token_accuracy": 0.8713514551520347, "num_tokens": 9083652.0, "step": 370 }, { "entropy": 0.5581418260931968, "epoch": 1.6601092896174863, "grad_norm": 0.2578125, "learning_rate": 1.5839169067811555e-05, "loss": 0.556967830657959, "mean_token_accuracy": 0.8669070154428482, "num_tokens": 9332032.0, "step": 380 }, { "entropy": 0.5558001473546028, "epoch": 1.7038251366120218, "grad_norm": 0.2275390625, "learning_rate": 1.2161400356095375e-05, "loss": 0.5525641441345215, "mean_token_accuracy": 0.8654688194394111, "num_tokens": 9578174.0, "step": 390 }, { "entropy": 0.5537898987531662, "epoch": 1.7475409836065574, "grad_norm": 0.435546875, "learning_rate": 8.941581430497481e-06, "loss": 0.5493928909301757, "mean_token_accuracy": 0.865025418996811, "num_tokens": 9824290.0, "step": 400 }, { "entropy": 0.5512544997036457, "epoch": 1.791256830601093, "grad_norm": 0.36328125, "learning_rate": 6.196498936004235e-06, "loss": 0.5473986625671386, "mean_token_accuracy": 0.8674423485994339, "num_tokens": 10083095.0, "step": 410 }, { "entropy": 0.5495157755911351, "epoch": 1.8349726775956285, "grad_norm": 0.203125, "learning_rate": 3.940464461670135e-06, "loss": 0.5492633819580078, "mean_token_accuracy": 0.8675305873155594, "num_tokens": 10326638.0, "step": 420 }, { "entropy": 0.5277233310043812, "epoch": 1.8786885245901639, "grad_norm": 0.224609375, "learning_rate": 2.1852399266194314e-06, "loss": 0.5260457038879395, "mean_token_accuracy": 0.8726123124361038, "num_tokens": 10564686.0, "step": 430 }, { "entropy": 0.5520216427743435, "epoch": 1.9224043715846995, "grad_norm": 0.375, "learning_rate": 9.399762588459204e-07, "loss": 0.5484935283660889, "mean_token_accuracy": 0.8669327393174171, "num_tokens": 10821540.0, "step": 440 }, { "entropy": 0.5562359377741813, "epoch": 1.966120218579235, "grad_norm": 0.3125, "learning_rate": 2.1116568651156076e-07, "loss": 0.5606791973114014, "mean_token_accuracy": 0.8641782850027084, "num_tokens": 11063652.0, "step": 450 }, { "epoch": 2.0, "eval_entropy": 0.5339264491839069, "eval_loss": 0.5725216269493103, "eval_mean_token_accuracy": 0.866687899189336, "eval_num_tokens": 11252147.0, "eval_runtime": 39.3277, "eval_samples_per_second": 8.442, "eval_steps_per_second": 1.424, "step": 458 }, { "epoch": 2.0, "step": 458, "total_flos": 1.6958247325338173e+18, "train_loss": 0.7416771020431185, "train_runtime": 5444.8575, "train_samples_per_second": 2.016, "train_steps_per_second": 0.084 } ], "logging_steps": 10, "max_steps": 458, "num_input_tokens_seen": 0, "num_train_epochs": 2, "save_steps": 9999, "stateful_callbacks": { "TrainerControl": { "args": { "should_epoch_stop": false, "should_evaluate": false, "should_log": false, "should_save": true, "should_training_stop": true }, "attributes": {} } }, "total_flos": 1.6958247325338173e+18, "train_batch_size": 1, "trial_name": null, "trial_params": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390{# Template: Google Gemma 4 Canonical Chat Template Author: Google Gemma Engineering Team Published: 2026-07-09 Context: Fixed tool-calling loops, turn closures, and thinking content-ordering.#}{%- macro format_parameters(properties, required, filter_keys=false) -%} {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%} {%- set ns = namespace(found_first=false) -%} {%- for key, value in properties | dictsort -%} {%- set add_comma = false -%} {%- if not filter_keys or key not in standard_keys -%} {%- if ns.found_first %},{% endif -%} {%- set ns.found_first = true -%} {{ key }}:{ {%- if value['description'] -%} description:<|"|>{{ value['description'] }}<|"|> {%- set add_comma = true -%} {%- endif -%} {%- if value['type'] | upper == 'STRING' -%} {%- if value['enum'] -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} enum:{{ format_argument(value['enum']) }} {%- endif -%} {%- elif value['type'] | upper == 'ARRAY' -%} {%- if value['items'] is mapping and value['items'] -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} items:{ {%- set ns_items = namespace(found_first=false) -%} {%- for item_key, item_value in value['items'] | dictsort -%} {%- if item_value is not none -%} {%- if ns_items.found_first %},{% endif -%} {%- set ns_items.found_first = true -%} {%- if item_key == 'properties' -%} properties:{ {%- if item_value is mapping -%} {{- format_parameters(item_value, value['items']['required'] | default([])) -}} {%- endif -%} } {%- elif item_key == 'required' -%} required:[ {%- for req_item in item_value -%} <|"|>{{- req_item -}}<|"|> {%- if not loop.last %},{% endif -%} {%- endfor -%} ] {%- elif item_key == 'type' -%} {%- if item_value is string -%} type:{{ format_argument(item_value | upper) }} {%- else -%} type:{{ format_argument(item_value | map('upper') | list) }} {%- endif -%} {%- else -%} {{ item_key }}:{{ format_argument(item_value) }} {%- endif -%} {%- endif -%} {%- endfor -%} } {%- endif -%} {%- endif -%} {%- if value['nullable'] %} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} nullable:true {%- endif -%} {%- if value['type'] | upper == 'OBJECT' -%} {%- if value['properties'] is defined and value['properties'] is mapping -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} properties:{ {{- format_parameters(value['properties'], value['required'] | default([])) -}} } {%- elif value is mapping -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} properties:{ {{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}} } {%- endif -%} {%- if value['required'] -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} required:[ {%- for item in value['required'] | default([]) -%} <|"|>{{- item -}}<|"|> {%- if not loop.last %},{% endif -%} {%- endfor -%} ] {%- endif -%} {%- endif -%} {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} type:<|"|>{{ value['type'] | upper }}<|"|>} {%- endif -%} {%- endfor -%}{%- endmacro -%}{%- macro format_function_declaration(tool_data) -%} declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|> {%- set params = tool_data['function']['parameters'] -%} {%- if params -%} ,parameters:{ {%- if params['properties'] -%} properties:{ {{- format_parameters(params['properties'], params['required']) -}} }, {%- endif -%} {%- if params['required'] -%} required:[ {%- for item in params['required'] -%} <|"|>{{- item -}}<|"|> {{- ',' if not loop.last -}} {%- endfor -%} ], {%- endif -%} {%- if params['type'] -%} type:<|"|>{{- params['type'] | upper -}}<|"|>} {%- endif -%} {%- endif -%} {%- if 'response' in tool_data['function'] -%} {%- set response_declaration = tool_data['function']['response'] -%} ,response:{ {%- if response_declaration['description'] -%} description:<|"|>{{- response_declaration['description'] -}}<|"|>, {%- endif -%} {%- if response_declaration['type'] | upper == 'OBJECT' -%} type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>} {%- endif -%} {%- endif -%} }{%- endmacro -%}{%- macro format_argument(argument, escape_keys=True) -%} {%- if argument is none -%} {{- 'null' -}} {%- elif argument is string -%} {{- '<|"|>' + argument + '<|"|>' -}} {%- elif argument is boolean -%} {{- 'true' if argument else 'false' -}} {%- elif argument is mapping -%} {{- '{' -}} {%- set ns = namespace(found_first=false) -%} {%- for key, value in argument | dictsort -%} {%- if ns.found_first %},{% endif -%} {%- set ns.found_first = true -%} {%- if escape_keys -%} {{- '<|"|>' + key + '<|"|>' -}} {%- else -%} {{- key -}} {%- endif -%} :{{- format_argument(value, escape_keys=escape_keys) -}} {%- endfor -%} {{- '}' -}} {%- elif argument is sequence -%} {{- '[' -}} {%- for item in argument -%} {{- format_argument(item, escape_keys=escape_keys) -}} {%- if not loop.last %},{% endif -%} {%- endfor -%} {{- ']' -}} {%- else -%} {{- argument -}} {%- endif -%}{%- endmacro -%}{%- macro strip_thinking(text) -%} {%- set ns = namespace(result='') -%} {%- for part in text.split('<channel|>') -%} {%- if '<|channel>' in part -%} {%- set ns.result = ns.result + part.split('<|channel>')[0] -%} {%- else -%} {%- set ns.result = ns.result + part -%} {%- endif -%} {%- endfor -%} {{- ns.result | trim -}}{%- endmacro -%}
{%- macro format_tool_response_block(tool_name, response) -%} {{- '<|tool_response>' -}} {%- if response is mapping -%} {{- 'response:' + tool_name + '{' -}} {%- for key, value in response | dictsort -%} {{- key -}}:{{- format_argument(value, escape_keys=False) -}} {%- if not loop.last %},{% endif -%} {%- endfor -%} {{- '}' -}} {%- else -%} {{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}} {%- endif -%} {{- '<tool_response|>' -}}{%- endmacro -%}
{#- ===== SETUP ===== -#}{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}{%- set loop_messages = messages -%}{%- set enable_thinking = enable_thinking | default(false) -%}{%- set preserve_thinking = preserve_thinking | default(false) -%}{{- bos_token -}}{#- Handle System/Tool Definitions Block -#}{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%} {{- '<|turn>system\n' -}} {#- Inject Thinking token at the very top of the FIRST system turn -#} {%- if enable_thinking -%} {{- '<|think|>\n' -}} {%- set ns.prev_message_type = 'think' -%} {%- endif -%} {%- if messages and messages[0]['role'] in ['system', 'developer'] -%} {%- if messages[0]['content'] is string -%} {{- messages[0]['content'] | trim -}} {%- elif messages[0]['content'] is sequence -%} {%- for item in messages[0]['content'] -%} {{- item['text'] | trim + ' '-}} {%- endfor -%} {%- endif -%} {%- set loop_messages = messages[1:] -%} {%- endif -%} {%- if tools -%} {%- for tool in tools %} {{- '<|tool>' -}} {{- format_function_declaration(tool) | trim -}} {{- '<tool|>' -}} {%- endfor %} {%- set ns.prev_message_type = 'tool' -%} {%- endif -%} {{- '<turn|>\n' -}}{%- endif %}
{#- Pre-scan: find last user message index for reasoning guard -#}{%- set ns_turn = namespace(last_user_idx=-1) -%}{%- for i in range(loop_messages | length) -%} {%- if loop_messages[i]['role'] == 'user' -%} {%- set ns_turn.last_user_idx = i -%} {%- endif -%}{%- endfor -%}
{#- Loop through messages -#}{%- for message in loop_messages -%} {%- if message['role'] != 'tool' -%} {%- set ns.prev_message_type = None -%} {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%} {#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#} {%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%} {%- if not continue_same_model_turn -%} {{- '<|turn>' + role + '\n' }}
{%- endif -%}
{#- Render reasoning/reasoning_content as thinking channel -#} {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%} {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%} {%- if thinking_text and thinking_gate -%} {{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}} {%- endif -%}
{%- if message.get('tool_calls') -%} {%- for tool_call in message.get('tool_calls') -%} {%- set function = tool_call['function'] -%} {{- '<|tool_call>call:' + function['name'] + '{' -}} {%- if function['arguments'] is mapping -%} {%- set ns_args = namespace(found_first=false) -%} {%- for key, value in function['arguments'] | dictsort -%} {%- if ns_args.found_first %},{% endif -%} {%- set ns_args.found_first = true -%} {{- key -}}:{{- format_argument(value, escape_keys=False) -}} {%- endfor -%} {%- elif function['arguments'] is none -%} {%- else -%} {{- raise_exception( "chat_template: tool_calls[].function.arguments must be a " "JSON object (mapping), not a string. Deserialize arguments " "before passing to the template." ) -}} {%- endif -%} {{- '}<tool_call|>' -}} {%- endfor -%} {%- set ns.prev_message_type = 'tool_call' -%} {%- endif -%}
{%- set ns_tr_out = namespace(flag=false) -%} {%- if message.get('tool_responses') -%} {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#} {%- for tool_response in message.get('tool_responses') -%} {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}} {%- set ns_tr_out.flag = true -%} {%- set ns.prev_message_type = 'tool_response' -%} {%- endfor -%} {%- elif message.get('tool_calls') -%} {#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#} {%- set ns_tool_scan = namespace(stopped=false) -%} {%- for k in range(loop.index0 + 1, loop_messages | length) -%} {%- if ns_tool_scan.stopped -%} {%- elif loop_messages[k]['role'] != 'tool' -%} {%- set ns_tool_scan.stopped = true -%} {%- else -%} {%- set follow = loop_messages[k] -%} {#- Resolve tool_call_id to function name -#} {%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%} {%- for tc in message.get('tool_calls') -%} {%- if tc.get('id') == follow.get('tool_call_id') -%} {%- set ns_tname.name = tc['function']['name'] -%} {%- endif -%} {%- endfor -%} {#- Handle content as string or content-parts array -#} {%- set tool_body = follow.get('content') -%} {%- if tool_body is string -%} {{- format_tool_response_block(ns_tname.name, tool_body) -}} {%- elif tool_body is sequence and tool_body is not string -%} {%- set ns_txt = namespace(s='') -%} {%- for part in tool_body -%} {%- if part.get('type') == 'text' -%} {%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%} {%- endif -%} {%- endfor -%} {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}} {%- for part in tool_body -%} {%- if part.get('type') in ['image', 'image_url'] -%} {{- '<|image|>' -}} {%- elif part.get('type') in ['audio', 'input_audio'] -%} {{- '<|audio|>' -}} {%- elif part.get('type') == 'video' -%} {{- '<|video|>' -}} {%- endif -%} {%- endfor -%} {%- else -%} {{- format_tool_response_block(ns_tname.name, tool_body) -}} {%- endif -%} {%- set ns_tr_out.flag = true -%} {%- set ns.prev_message_type = 'tool_response' -%} {%- endif -%} {%- endfor -%} {%- endif -%}
{%- set captured_content -%} {%- if message.get('content') is string -%} {%- if role == 'model' -%} {{- strip_thinking(message['content']) -}} {%- else -%} {{- message['content'] | trim -}} {%- endif -%} {%- elif message.get('content') is sequence -%} {%- for item in message['content'] -%} {%- if item.get('type') == 'text' -%} {%- if role == 'model' -%} {{- strip_thinking(item['text']) -}} {%- else -%} {{- item['text'] | trim -}} {%- endif -%} {%- elif item.get('type') in ['image', 'image_url'] -%} {{- '<|image|>' -}} {%- elif item.get('type') in ['audio', 'input_audio'] -%} {{- '<|audio|>' -}} {%- elif item.get('type') == 'video' -%} {{- '<|video|>' -}} {%- endif -%} {%- endfor -%} {%- endif -%} {%- endset -%}
{{- captured_content -}} {%- set has_content = captured_content | trim | length > 0 -%}
{#- Forward-scan: find next non-tool message role for continuation detection -#} {%- set next_nt = namespace(role=None, found=false) -%} {%- for j in range(loop.index0 + 1, loop_messages | length) -%} {%- if not next_nt.found -%} {%- if loop_messages[j]['role'] != 'tool' -%} {%- set next_nt.role = loop_messages[j]['role'] -%} {%- set next_nt.found = true -%} {%- endif -%} {%- endif -%} {%- endfor -%}
{%- set continues_into_next = ( role == 'model' and next_nt.role == 'assistant' and (not message.get('tool_calls') or ns_tr_out.flag) ) -%}
{%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%} {{- '<|tool_response>' -}} {%- elif continues_into_next -%} {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%} {{- '<turn|>\n' -}} {%- endif -%}
{#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#} {%- set ns.prev_non_tool_role = message['role'] -%} {%- endif -%}{%- endfor -%}
{%- if add_generation_prompt -%} {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%} {{- '<|turn>model\n' -}} {%- if not enable_thinking -%} {{- '<|channel>thought\n<channel|>' -}} {%- endif -%} {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%} {{- '<|channel>thought\n' -}} {%- endif -%}{%- endif -%}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146{ "architectures": [ "Gemma4ForConditionalGeneration" ], "audio_config": null, "audio_token_id": 258881, "boa_token_id": 256000, "boi_token_id": 255999, "dtype": "bfloat16", "eoa_token_id": 258883, "eoa_token_index": 258883, "eoi_token_id": 258882, "eos_token_id": [ 1, 106 ], "image_token_id": 258880, "initializer_range": 0.02, "model_type": "gemma4", "text_config": { "attention_bias": false, "attention_dropout": 0.0, "attention_k_eq_v": true, "bos_token_id": 2, "dtype": "bfloat16", "enable_moe_block": true, "eos_token_id": 1, "final_logit_softcapping": 30.0, "global_head_dim": 512, "head_dim": 256, "hidden_activation": "gelu_pytorch_tanh", "hidden_size": 2816, "hidden_size_per_layer_input": 0, "initializer_range": 0.02, "intermediate_size": 2112, "layer_types": [ "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "full_attention" ], "max_position_embeddings": 262144, "model_type": "gemma4_text", "moe_intermediate_size": 704, "num_attention_heads": 16, "num_experts": 128, "num_global_key_value_heads": 2, "num_hidden_layers": 30, "num_key_value_heads": 8, "num_kv_shared_layers": 0, "pad_token_id": 0, "rms_norm_eps": 1e-06, "rope_parameters": { "full_attention": { "partial_rotary_factor": 0.25, "rope_theta": 1000000.0, "rope_type": "proportional" }, "sliding_attention": { "rope_theta": 10000.0, "rope_type": "default" } }, "sliding_window": 1024, "tie_word_embeddings": true, "top_k_experts": 8, "use_bidirectional_attention": "vision", "use_cache": true, "use_double_wide_mlp": false, "vocab_size": 262144, "vocab_size_per_layer_input": 262144 }, "tie_word_embeddings": true, "transformers_version": "5.6.2", "video_token_id": 258884, "vision_config": { "_name_or_path": "", "architectures": null, "attention_bias": false, "attention_dropout": 0.0, "chunk_size_feed_forward": 0, "default_output_length": 280, "dtype": "bfloat16", "global_head_dim": 72, "head_dim": 72, "hidden_activation": "gelu_pytorch_tanh", "hidden_size": 1152, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "initializer_range": 0.02, "intermediate_size": 4304, "is_encoder_decoder": false, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "max_position_embeddings": 131072, "model_type": "gemma4_vision", "num_attention_heads": 16, "num_hidden_layers": 27, "num_key_value_heads": 16, "output_attentions": false, "output_hidden_states": false, "patch_size": 16, "pooling_kernel_size": 3, "position_embedding_size": 10240, "problem_type": null, "return_dict": true, "rms_norm_eps": 1e-06, "rope_parameters": { "rope_theta": 100.0, "rope_type": "default" }, "standardize": true, "use_clipped_linears": false }, "vision_soft_tokens_per_image": 280}1234567891011121314{ "bos_token_id": 2, "do_sample": true, "eos_token_id": [ 1, 106, 50 ], "pad_token_id": 0, "temperature": 1.0, "top_k": 64, "top_p": 0.95, "transformers_version": "5.6.2"}123version https://git-lfs.github.com/spec/v1oid sha256:e3a61f56ebfb5fb19579f120bbc587289b579e9efc84a76819dc068bff54609asize 4739268972123version https://git-lfs.github.com/spec/v1oid sha256:ab854e612c87cbcc6c8481fd7f159b0e3c2e83b2c04b2a8ef77633aff44e1402size 4884578470123version https://git-lfs.github.com/spec/v1oid sha256:cbc3f975c9b1157b4907a6cd5299d49c22a7568ad6b4922d09a4d43693678ce5size 4913415198123version https://git-lfs.github.com/spec/v1oid sha256:a868c0852695fceabeb2305b394c5b4b4e988b3d1a90563eef7ea970d25e232fsize 4884578494123version https://git-lfs.github.com/spec/v1oid sha256:7c3a8b6f83ed0b3955aa4d4ba5040914cb623ef1b3e5356cb0564f12aa9ecb15size 4913415262123version https://git-lfs.github.com/spec/v1oid sha256:c4cfe3b47ca6dccc3afe61741869535d3a08fa467e3030b0bf4f20412a11ad88size 4884578534123version https://git-lfs.github.com/spec/v1oid sha256:5c0e184f731ef88dfedeaf52da2d79b57446c90e04ac72faeb1d3570ee2e8854size 4913415262123version https://git-lfs.github.com/spec/v1oid sha256:a46e1c90025a64f358a0c5f223bc63c1d72a5052880cf05348b3a057cbaa44e6size 4884578534123version https://git-lfs.github.com/spec/v1oid sha256:60fd9accca5e3c48a08afb419eb7f99bb9ec2f288d569fb68646e7b462d12c95size 4913415262123version https://git-lfs.github.com/spec/v1oid sha256:0819d4eea875d63da923e995f32fde738a8df20de4a174a3d1f0a4df0792c5a7size 4884578534123version https://git-lfs.github.com/spec/v1oid sha256:79cb5494f36fd110674a900afdc7838275d3617500b7754fcf82e333b5a98adesize 2796186042123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475{ "audio_ms_per_token": 40, "audio_seq_length": 750, "feature_extractor": { "dither": 0.0, "feature_extractor_type": "Gemma4AudioFeatureExtractor", "feature_size": 128, "fft_length": 512, "fft_overdrive": false, "frame_length": 320, "hop_length": 160, "input_scale_factor": 1.0, "max_frequency": 8000.0, "mel_floor": 0.001, "min_frequency": 0.0, "padding_side": "right", "padding_value": 0.0, "per_bin_mean": null, "per_bin_stddev": null, "preemphasis": 0.0, "preemphasis_htk_flavor": true, "return_attention_mask": true, "sampling_rate": 16000 }, "image_processor": { "do_convert_rgb": true, "do_normalize": false, "do_rescale": true, "do_resize": true, "image_mean": [ 0.0, 0.0, 0.0 ], "image_processor_type": "Gemma4ImageProcessor", "image_seq_length": 280, "image_std": [ 1.0, 1.0, 1.0 ], "max_soft_tokens": 280, "patch_size": 16, "pooling_kernel_size": 3, "resample": 3, "rescale_factor": 0.00392156862745098 }, "image_seq_length": 280, "processor_class": "Gemma4Processor", "video_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "do_sample_frames": true, "image_mean": [ 0.0, 0.0, 0.0 ], "image_std": [ 1.0, 1.0, 1.0 ], "max_soft_tokens": 70, "num_frames": 32, "patch_size": 16, "pooling_kernel_size": 3, "resample": 3, "rescale_factor": 0.00392156862745098, "return_metadata": false, "video_processor_type": "Gemma4VideoProcessor" }}123version https://git-lfs.github.com/spec/v1oid sha256:cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0fsize 32169626123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142{ "audio_token": "<|audio|>", "backend": "tokenizers", "boa_token": "<|audio>", "boi_token": "<|image>", "bos_token": "<bos>", "eoa_token": "<audio|>", "eoc_token": "<channel|>", "eoi_token": "<image|>", "eos_token": "<eos>", "eot_token": "<turn|>", "escape_token": "<|\"|>", "etc_token": "<tool_call|>", "etd_token": "<tool|>", "etr_token": "<tool_response|>", "extra_special_tokens": [ "<|video|>" ], "image_token": "<|image|>", "is_local": true, "local_files_only": false, "mask_token": "<mask>", "model_max_length": 1000000000000000019884624838656, "model_specific_special_tokens": { "audio_token": "<|audio|>", "boa_token": "<|audio>", "boi_token": "<|image>", "eoa_token": "<audio|>", "eoc_token": "<channel|>", "eoi_token": "<image|>", "eot_token": "<turn|>", "escape_token": "<|\"|>", "etc_token": "<tool_call|>", "etd_token": "<tool|>", "etr_token": "<tool_response|>", "image_token": "<|image|>", "soc_token": "<|channel>", "sot_token": "<|turn>", "stc_token": "<|tool_call>", "std_token": "<|tool>", "str_token": "<|tool_response>", "think_token": "<|think|>" }, "pad_token": "<pad>", "padding_side": "right", "processor_class": "Gemma4Processor", "response_schema": { "properties": { "content": { "type": "string" }, "role": { "const": "assistant" }, "thinking": { "type": "string" }, "tool_calls": { "items": { "properties": { "function": { "properties": { "arguments": { "additionalProperties": {}, "type": "object", "x-parser": "gemma4-tool-call" }, "name": { "type": "string" } }, "type": "object", "x-regex": "call\\:(?P<name>\\w+)(?P<arguments>\\{.*\\})" }, "type": { "const": "function" } }, "type": "object" }, "type": "array", "x-regex-iterator": "<\\|tool_call>(.*?)<tool_call\\|>" } }, "type": "object", "x-regex": "(\\<\\|channel\\>thought\\n(?P<thinking>.*?)\\<channel\\|\\>)?(?P<tool_calls>\\<\\|tool_call\\>.*\\<tool_call\\|\\>)?(?P<content>(?:(?!\\<turn\\|\\>)(?!\\<\\|tool_response\\>).)+)?(?:\\<turn\\|\\>|\\<\\|tool_response\\>)?" }, "response_template": { "defaults": { "role": "assistant" }, "fields": { "content": { "close": [ "<turn|>", "<|tool_response>", "<eos>" ], "content": "text" }, "thinking": { "close": "<channel|>", "content": "text", "open": "<|channel>thought\n" }, "tool_calls": { "close": "<tool_call|>", "content": "json", "content_args": { "string_delims": [ [ "<|\"|>", "<|\"|>" ] ], "unquoted_keys": true }, "open_pattern": "<\\|tool_call>call:(?P<name>\\w+)", "repeats": true, "transform": { "function": { "arguments": "{content}", "name": "{name}" }, "type": "function" } } }, "start_anchor": [ "<|turn>model\n", "<tool_response|>" ] }, "soc_token": "<|channel>", "sot_token": "<|turn>", "stc_token": "<|tool_call>", "std_token": "<|tool>", "str_token": "<|tool_response>", "think_token": "<|think|>", "tokenizer_class": "GemmaTokenizer", "unk_token": "<unk>"}.gitattributes+2
LICENSEAdded+202
README.md+622-1
adapter/README.mdAdded+23
adapter/adapter_config.jsonAdded+46
adapter/adapter_model.safetensorsAdded+3
adapter/all_results.jsonAdded+7
adapter/chat_template.jinjaAdded+390
adapter/eval_results.jsonAdded+11
adapter/predictions.jsonlAdded
adapter/tokenizer.jsonAdded+3
adapter/tokenizer_config.jsonAdded+142
adapter/train_results.jsonAdded+7
adapter/trainer_state.jsonAdded+504
chat_template.jinjaAdded+390
config.jsonAdded+146
generation_config.jsonAdded+14
model-00001-of-00011.safetensorsAdded+3
model-00002-of-00011.safetensorsAdded+3
model-00003-of-00011.safetensorsAdded+3
model-00004-of-00011.safetensorsAdded+3
model-00005-of-00011.safetensorsAdded+3
model-00006-of-00011.safetensorsAdded+3
model-00007-of-00011.safetensorsAdded+3
model-00008-of-00011.safetensorsAdded+3
model-00009-of-00011.safetensorsAdded+3
model-00010-of-00011.safetensorsAdded+3
model-00011-of-00011.safetensorsAdded+3
model.safetensors.index.jsonAdded
processor_config.jsonAdded+75
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+142