gaunernst commited on
Commit
adc9999
·
verified ·
1 Parent(s): 425c406

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: gemma
3
+ library_name: transformers
4
+ pipeline_tag: image-text-to-text
5
+ extra_gated_heading: Access Gemma on Hugging Face
6
+ extra_gated_prompt: To access Gemma on Hugging Face, you’re required to review and
7
+ agree to Google’s usage license. To do this, please ensure you’re logged in to Hugging
8
+ Face and click below. Requests are processed immediately.
9
+ extra_gated_button_content: Acknowledge license
10
+ base_model: google/gemma-3-27b-it
11
+ ---
12
+
13
+ # Gemma 3 27B Instruction-tuned INT4
14
+
15
+ This is the QAT INT4 Flax checkpoint (from Kaggle) converted to HF+AWQ format for ease of use. AWQ was NOT used for quantization. You can find the conversion script `convert_flax.py` in this model repo.
16
+
17
+ Below is the original Model card from https://huggingface.co/google/gemma-3-27b-it
18
+
19
+ # Gemma 3 model card
20
+
21
+ **Model Page**: [Gemma](https://ai.google.dev/gemma/docs/core)
22
+
23
+ **Resources and Technical Documentation**:
24
+
25
+ * [Gemma 3 Technical Report][g3-tech-report]
26
+ * [Responsible Generative AI Toolkit][rai-toolkit]
27
+ * [Gemma on Kaggle][kaggle-gemma]
28
+ * [Gemma on Vertex Model Garden][vertex-mg-gemma3]
29
+
30
+ **Terms of Use**: [Terms][terms]
31
+
32
+ **Authors**: Google DeepMind
33
+
34
+ ## Model Information
35
+
36
+ Summary description and brief definition of inputs and outputs.
37
+
38
+ ### Description
39
+
40
+ Gemma is a family of lightweight, state-of-the-art open models from Google,
41
+ built from the same research and technology used to create the Gemini models.
42
+ Gemma 3 models are multimodal, handling text and image input and generating text
43
+ output, with open weights for both pre-trained variants and instruction-tuned
44
+ variants. Gemma 3 has a large, 128K context window, multilingual support in over
45
+ 140 languages, and is available in more sizes than previous versions. Gemma 3
46
+ models are well-suited for a variety of text generation and image understanding
47
+ tasks, including question answering, summarization, and reasoning. Their
48
+ relatively small size makes it possible to deploy them in environments with
49
+ limited resources such as laptops, desktops or your own cloud infrastructure,
50
+ democratizing access to state of the art AI models and helping foster innovation
51
+ for everyone.
52
+
53
+ ### Inputs and outputs
54
+
55
+ - **Input:**
56
+ - Text string, such as a question, a prompt, or a document to be summarized
57
+ - Images, normalized to 896 x 896 resolution and encoded to 256 tokens
58
+ each
59
+ - Total input context of 128K tokens for the 4B, 12B, and 27B sizes, and
60
+ 32K tokens for the 1B size
61
+
62
+ - **Output:**
63
+ - Generated text in response to the input, such as an answer to a
64
+ question, analysis of image content, or a summary of a document
65
+ - Total output context of 8192 tokens
66
+
67
+ ### Usage
68
+
69
+ Below there are some code snippets on how to get quickly started with running the model. First, install the Transformers library with the version made for Gemma 3:
70
+
71
+ ```sh
72
+ $ pip install git+https://github.com/huggingface/[email protected]
73
+ ```
74
+
75
+ Then, copy the snippet from the section that is relevant for your use case.
76
+
77
+ #### Running with the `pipeline` API
78
+
79
+ You can initialize the model and processor for inference with `pipeline` as follows.
80
+
81
+ ```python
82
+ from transformers import pipeline
83
+ import torch
84
+
85
+ pipe = pipeline(
86
+ "image-text-to-text",
87
+ model="google/gemma-3-27b-it",
88
+ device="cuda",
89
+ torch_dtype=torch.bfloat16
90
+ )
91
+ ```
92
+
93
+ With instruction-tuned models, you need to use chat templates to process our inputs first. Then, you can pass it to the pipeline.
94
+
95
+ ```python
96
+ messages = [
97
+ {
98
+ "role": "system",
99
+ "content": [{"type": "text", "text": "You are a helpful assistant."}]
100
+ },
101
+ {
102
+ "role": "user",
103
+ "content": [
104
+ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"},
105
+ {"type": "text", "text": "What animal is on the candy?"}
106
+ ]
107
+ }
108
+ ]
109
+
110
+ output = pipe(text=messages, max_new_tokens=200)
111
+ print(output[0][0]["generated_text"][-1]["content"])
112
+ # Okay, let's take a look!
113
+ # Based on the image, the animal on the candy is a **turtle**.
114
+ # You can see the shell shape and the head and legs.
115
+ ```
116
+
117
+ #### Running the model on a single/multi GPU
118
+
119
+ ```python
120
+ # pip install accelerate
121
+
122
+ from transformers import AutoProcessor, Gemma3ForConditionalGeneration
123
+ from PIL import Image
124
+ import requests
125
+ import torch
126
+
127
+ model_id = "google/gemma-3-27b-it"
128
+
129
+ model = Gemma3ForConditionalGeneration.from_pretrained(
130
+ model_id, device_map="auto"
131
+ ).eval()
132
+
133
+ processor = AutoProcessor.from_pretrained(model_id)
134
+
135
+ messages = [
136
+ {
137
+ "role": "system",
138
+ "content": [{"type": "text", "text": "You are a helpful assistant."}]
139
+ },
140
+ {
141
+ "role": "user",
142
+ "content": [
143
+ {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"},
144
+ {"type": "text", "text": "Describe this image in detail."}
145
+ ]
146
+ }
147
+ ]
148
+
149
+ inputs = processor.apply_chat_template(
150
+ messages, add_generation_prompt=True, tokenize=True,
151
+ return_dict=True, return_tensors="pt"
152
+ ).to(model.device, dtype=torch.bfloat16)
153
+
154
+ input_len = inputs["input_ids"].shape[-1]
155
+
156
+ with torch.inference_mode():
157
+ generation = model.generate(**inputs, max_new_tokens=100, do_sample=False)
158
+ generation = generation[0][input_len:]
159
+
160
+ decoded = processor.decode(generation, skip_special_tokens=True)
161
+ print(decoded)
162
+
163
+ # **Overall Impression:** The image is a close-up shot of a vibrant garden scene,
164
+ # focusing on a cluster of pink cosmos flowers and a busy bumblebee.
165
+ # It has a slightly soft, natural feel, likely captured in daylight.
166
+ ```
167
+
168
+ ### Citation
169
+
170
+ ```none
171
+ @article{gemma_2025,
172
+ title={Gemma 3},
173
+ url={https://goo.gle/Gemma3Report},
174
+ publisher={Kaggle},
175
+ author={Gemma Team},
176
+ year={2025}
177
+ }
178
+ ```
179
+
180
+ ## Model Data
181
+
182
+ Data used for model training and how the data was processed.
183
+
184
+ ### Training Dataset
185
+
186
+ These models were trained on a dataset of text data that includes a wide variety
187
+ of sources. The 27B model was trained with 14 trillion tokens, the 12B model was
188
+ trained with 12 trillion tokens, 4B model was trained with 4 trillion tokens and
189
+ 1B with 2 trillion tokens. Here are the key components:
190
+
191
+ - Web Documents: A diverse collection of web text ensures the model is
192
+ exposed to a broad range of linguistic styles, topics, and vocabulary. The
193
+ training dataset includes content in over 140 languages.
194
+ - Code: Exposing the model to code helps it to learn the syntax and
195
+ patterns of programming languages, which improves its ability to generate
196
+ code and understand code-related questions.
197
+ - Mathematics: Training on mathematical text helps the model learn logical
198
+ reasoning, symbolic representation, and to address mathematical queries.
199
+ - Images: A wide range of images enables the model to perform image
200
+ analysis and visual data extraction tasks.
201
+
202
+ The combination of these diverse data sources is crucial for training a powerful
203
+ multimodal model that can handle a wide variety of different tasks and data
204
+ formats.
205
+
206
+ ### Data Preprocessing
207
+
208
+ Here are the key data cleaning and filtering methods applied to the training
209
+ data:
210
+
211
+ - CSAM Filtering: Rigorous CSAM (Child Sexual Abuse Material) filtering
212
+ was applied at multiple stages in the data preparation process to ensure
213
+ the exclusion of harmful and illegal content.
214
+ - Sensitive Data Filtering: As part of making Gemma pre-trained models
215
+ safe and reliable, automated techniques were used to filter out certain
216
+ personal information and other sensitive data from training sets.
217
+ - Additional methods: Filtering based on content quality and safety in
218
+ line with [our policies][safety-policies].
219
+
220
+ ## Implementation Information
221
+
222
+ Details about the model internals.
223
+
224
+ ### Hardware
225
+
226
+ Gemma was trained using [Tensor Processing Unit (TPU)][tpu] hardware (TPUv4p,
227
+ TPUv5p and TPUv5e). Training vision-language models (VLMS) requires significant
228
+ computational power. TPUs, designed specifically for matrix operations common in
229
+ machine learning, offer several advantages in this domain:
230
+
231
+ - Performance: TPUs are specifically designed to handle the massive
232
+ computations involved in training VLMs. They can speed up training
233
+ considerably compared to CPUs.
234
+ - Memory: TPUs often come with large amounts of high-bandwidth memory,
235
+ allowing for the handling of large models and batch sizes during training.
236
+ This can lead to better model quality.
237
+ - Scalability: TPU Pods (large clusters of TPUs) provide a scalable
238
+ solution for handling the growing complexity of large foundation models.
239
+ You can distribute training across multiple TPU devices for faster and more
240
+ efficient processing.
241
+ - Cost-effectiveness: In many scenarios, TPUs can provide a more
242
+ cost-effective solution for training large models compared to CPU-based
243
+ infrastructure, especially when considering the time and resources saved
244
+ due to faster training.
245
+ - These advantages are aligned with
246
+ [Google's commitments to operate sustainably][sustainability].
247
+
248
+ ### Software
249
+
250
+ Training was done using [JAX][jax] and [ML Pathways][ml-pathways].
251
+
252
+ JAX allows researchers to take advantage of the latest generation of hardware,
253
+ including TPUs, for faster and more efficient training of large models. ML
254
+ Pathways is Google's latest effort to build artificially intelligent systems
255
+ capable of generalizing across multiple tasks. This is specially suitable for
256
+ foundation models, including large language models like these ones.
257
+
258
+ Together, JAX and ML Pathways are used as described in the
259
+ [paper about the Gemini family of models][gemini-2-paper]; *"the 'single
260
+ controller' programming model of Jax and Pathways allows a single Python
261
+ process to orchestrate the entire training run, dramatically simplifying the
262
+ development workflow."*
263
+
264
+ ## Evaluation
265
+
266
+ Model evaluation metrics and results.
267
+
268
+ ### Benchmark Results
269
+
270
+ These models were evaluated against a large collection of different datasets and
271
+ metrics to cover different aspects of text generation:
272
+
273
+ #### Reasoning and factuality
274
+
275
+ | Benchmark | Metric | Gemma 3 PT 1B | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B |
276
+ | ------------------------------ |----------------|:--------------:|:-------------:|:--------------:|:--------------:|
277
+ | [HellaSwag][hellaswag] | 10-shot | 62.3 | 77.2 | 84.2 | 85.6 |
278
+ | [BoolQ][boolq] | 0-shot | 63.2 | 72.3 | 78.8 | 82.4 |
279
+ | [PIQA][piqa] | 0-shot | 73.8 | 79.6 | 81.8 | 83.3 |
280
+ | [SocialIQA][socialiqa] | 0-shot | 48.9 | 51.9 | 53.4 | 54.9 |
281
+ | [TriviaQA][triviaqa] | 5-shot | 39.8 | 65.8 | 78.2 | 85.5 |
282
+ | [Natural Questions][naturalq] | 5-shot | 9.48 | 20.0 | 31.4 | 36.1 |
283
+ | [ARC-c][arc] | 25-shot | 38.4 | 56.2 | 68.9 | 70.6 |
284
+ | [ARC-e][arc] | 0-shot | 73.0 | 82.4 | 88.3 | 89.0 |
285
+ | [WinoGrande][winogrande] | 5-shot | 58.2 | 64.7 | 74.3 | 78.8 |
286
+ | [BIG-Bench Hard][bbh] | few-shot | 28.4 | 50.9 | 72.6 | 77.7 |
287
+ | [DROP][drop] | 1-shot | 42.4 | 60.1 | 72.2 | 77.2 |
288
+
289
+ [hellaswag]: https://arxiv.org/abs/1905.07830
290
+ [boolq]: https://arxiv.org/abs/1905.10044
291
+ [piqa]: https://arxiv.org/abs/1911.11641
292
+ [socialiqa]: https://arxiv.org/abs/1904.09728
293
+ [triviaqa]: https://arxiv.org/abs/1705.03551
294
+ [naturalq]: https://github.com/google-research-datasets/natural-questions
295
+ [arc]: https://arxiv.org/abs/1911.01547
296
+ [winogrande]: https://arxiv.org/abs/1907.10641
297
+ [bbh]: https://paperswithcode.com/dataset/bbh
298
+ [drop]: https://arxiv.org/abs/1903.00161
299
+
300
+ #### STEM and code
301
+
302
+ | Benchmark | Metric | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B |
303
+ | ------------------------------ |----------------|:-------------:|:--------------:|:--------------:|
304
+ | [MMLU][mmlu] | 5-shot | 59.6 | 74.5 | 78.6 |
305
+ | [MMLU][mmlu] (Pro COT) | 5-shot | 29.2 | 45.3 | 52.2 |
306
+ | [AGIEval][agieval] | 3-5-shot | 42.1 | 57.4 | 66.2 |
307
+ | [MATH][math] | 4-shot | 24.2 | 43.3 | 50.0 |
308
+ | [GSM8K][gsm8k] | 8-shot | 38.4 | 71.0 | 82.6 |
309
+ | [GPQA][gpqa] | 5-shot | 15.0 | 25.4 | 24.3 |
310
+ | [MBPP][mbpp] | 3-shot | 46.0 | 60.4 | 65.6 |
311
+ | [HumanEval][humaneval] | 0-shot | 36.0 | 45.7 | 48.8 |
312
+
313
+ [mmlu]: https://arxiv.org/abs/2009.03300
314
+ [agieval]: https://arxiv.org/abs/2304.06364
315
+ [math]: https://arxiv.org/abs/2103.03874
316
+ [gsm8k]: https://arxiv.org/abs/2110.14168
317
+ [gpqa]: https://arxiv.org/abs/2311.12022
318
+ [mbpp]: https://arxiv.org/abs/2108.07732
319
+ [humaneval]: https://arxiv.org/abs/2107.03374
320
+
321
+ #### Multilingual
322
+
323
+ | Benchmark | Gemma 3 PT 1B | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B |
324
+ | ------------------------------------ |:-------------:|:-------------:|:--------------:|:--------------:|
325
+ | [MGSM][mgsm] | 2.04 | 34.7 | 64.3 | 74.3 |
326
+ | [Global-MMLU-Lite][global-mmlu-lite] | 24.9 | 57.0 | 69.4 | 75.7 |
327
+ | [WMT24++][wmt24pp] (ChrF) | 36.7 | 48.4 | 53.9 | 55.7 |
328
+ | [FloRes][flores] | 29.5 | 39.2 | 46.0 | 48.8 |
329
+ | [XQuAD][xquad] (all) | 43.9 | 68.0 | 74.5 | 76.8 |
330
+ | [ECLeKTic][eclektic] | 4.69 | 11.0 | 17.2 | 24.4 |
331
+ | [IndicGenBench][indicgenbench] | 41.4 | 57.2 | 61.7 | 63.4 |
332
+
333
+ [mgsm]: https://arxiv.org/abs/2210.03057
334
+ [flores]: https://arxiv.org/abs/2106.03193
335
+ [xquad]: https://arxiv.org/abs/1910.11856v3
336
+ [global-mmlu-lite]: https://huggingface.co/datasets/CohereForAI/Global-MMLU-Lite
337
+ [wmt24pp]: https://arxiv.org/abs/2502.12404v1
338
+ [eclektic]: https://arxiv.org/abs/2502.21228
339
+ [indicgenbench]: https://arxiv.org/abs/2404.16816
340
+
341
+ #### Multimodal
342
+
343
+ | Benchmark | Gemma 3 PT 4B | Gemma 3 PT 12B | Gemma 3 PT 27B |
344
+ | ------------------------------ |:-------------:|:--------------:|:--------------:|
345
+ | [COCOcap][coco-cap] | 102 | 111 | 116 |
346
+ | [DocVQA][docvqa] (val) | 72.8 | 82.3 | 85.6 |
347
+ | [InfoVQA][info-vqa] (val) | 44.1 | 54.8 | 59.4 |
348
+ | [MMMU][mmmu] (pt) | 39.2 | 50.3 | 56.1 |
349
+ | [TextVQA][textvqa] (val) | 58.9 | 66.5 | 68.6 |
350
+ | [RealWorldQA][realworldqa] | 45.5 | 52.2 | 53.9 |
351
+ | [ReMI][remi] | 27.3 | 38.5 | 44.8 |
352
+ | [AI2D][ai2d] | 63.2 | 75.2 | 79.0 |
353
+ | [ChartQA][chartqa] | 63.6 | 74.7 | 76.3 |
354
+ | [VQAv2][vqav2] | 63.9 | 71.2 | 72.9 |
355
+ | [BLINK][blinkvqa] | 38.0 | 35.9 | 39.6 |
356
+ | [OKVQA][okvqa] | 51.0 | 58.7 | 60.2 |
357
+ | [TallyQA][tallyqa] | 42.5 | 51.8 | 54.3 |
358
+ | [SpatialSense VQA][ss-vqa] | 50.9 | 60.0 | 59.4 |
359
+ | [CountBenchQA][countbenchqa] | 26.1 | 17.8 | 68.0 |
360
+
361
+ [coco-cap]: https://cocodataset.org/#home
362
+ [docvqa]: https://www.docvqa.org/
363
+ [info-vqa]: https://arxiv.org/abs/2104.12756
364
+ [mmmu]: https://arxiv.org/abs/2311.16502
365
+ [textvqa]: https://textvqa.org/
366
+ [realworldqa]: https://paperswithcode.com/dataset/realworldqa
367
+ [remi]: https://arxiv.org/html/2406.09175v1
368
+ [ai2d]: https://allenai.org/data/diagrams
369
+ [chartqa]: https://arxiv.org/abs/2203.10244
370
+ [vqav2]: https://visualqa.org/index.html
371
+ [blinkvqa]: https://arxiv.org/abs/2404.12390
372
+ [okvqa]: https://okvqa.allenai.org/
373
+ [tallyqa]: https://arxiv.org/abs/1810.12440
374
+ [ss-vqa]: https://arxiv.org/abs/1908.02660
375
+ [countbenchqa]: https://github.com/google-research/big_vision/blob/main/big_vision/datasets/countbenchqa/
376
+
377
+ ## Ethics and Safety
378
+
379
+ Ethics and safety evaluation approach and results.
380
+
381
+ ### Evaluation Approach
382
+
383
+ Our evaluation methods include structured evaluations and internal red-teaming
384
+ testing of relevant content policies. Red-teaming was conducted by a number of
385
+ different teams, each with different goals and human evaluation metrics. These
386
+ models were evaluated against a number of different categories relevant to
387
+ ethics and safety, including:
388
+
389
+ - **Child Safety**: Evaluation of text-to-text and image to text prompts
390
+ covering child safety policies, including child sexual abuse and
391
+ exploitation.
392
+ - **Content Safety:** Evaluation of text-to-text and image to text prompts
393
+ covering safety policies including, harassment, violence and gore, and hate
394
+ speech.
395
+ - **Representational Harms**: Evaluation of text-to-text and image to text
396
+ prompts covering safety policies including bias, stereotyping, and harmful
397
+ associations or inaccuracies.
398
+
399
+ In addition to development level evaluations, we conduct "assurance
400
+ evaluations" which are our 'arms-length' internal evaluations for responsibility
401
+ governance decision making. They are conducted separately from the model
402
+ development team, to inform decision making about release. High level findings
403
+ are fed back to the model team, but prompt sets are held-out to prevent
404
+ overfitting and preserve the results' ability to inform decision making.
405
+ Assurance evaluation results are reported to our Responsibility & Safety Council
406
+ as part of release review.
407
+
408
+ ### Evaluation Results
409
+
410
+ For all areas of safety testing, we saw major improvements in the categories of
411
+ child safety, content safety, and representational harms relative to previous
412
+ Gemma models. All testing was conducted without safety filters to evaluate the
413
+ model capabilities and behaviors. For both text-to-text and image-to-text, and
414
+ across all model sizes, the model produced minimal policy violations, and showed
415
+ significant improvements over previous Gemma models' performance with respect
416
+ to ungrounded inferences. A limitation of our evaluations was they included only
417
+ English language prompts.
418
+
419
+ ## Usage and Limitations
420
+
421
+ These models have certain limitations that users should be aware of.
422
+
423
+ ### Intended Usage
424
+
425
+ Open vision-language models (VLMs) models have a wide range of applications
426
+ across various industries and domains. The following list of potential uses is
427
+ not comprehensive. The purpose of this list is to provide contextual information
428
+ about the possible use-cases that the model creators considered as part of model
429
+ training and development.
430
+
431
+ - Content Creation and Communication
432
+ - Text Generation: These models can be used to generate creative text
433
+ formats such as poems, scripts, code, marketing copy, and email drafts.
434
+ - Chatbots and Conversational AI: Power conversational interfaces
435
+ for customer service, virtual assistants, or interactive applications.
436
+ - Text Summarization: Generate concise summaries of a text corpus,
437
+ research papers, or reports.
438
+ - Image Data Extraction: These models can be used to extract,
439
+ interpret, and summarize visual data for text communications.
440
+ - Research and Education
441
+ - Natural Language Processing (NLP) and VLM Research: These
442
+ models can serve as a foundation for researchers to experiment with VLM
443
+ and NLP techniques, develop algorithms, and contribute to the
444
+ advancement of the field.
445
+ - Language Learning Tools: Support interactive language learning
446
+ experiences, aiding in grammar correction or providing writing practice.
447
+ - Knowledge Exploration: Assist researchers in exploring large
448
+ bodies of text by generating summaries or answering questions about
449
+ specific topics.
450
+
451
+ ### Limitations
452
+
453
+ - Training Data
454
+ - The quality and diversity of the training data significantly
455
+ influence the model's capabilities. Biases or gaps in the training data
456
+ can lead to limitations in the model's responses.
457
+ - The scope of the training dataset determines the subject areas
458
+ the model can handle effectively.
459
+ - Context and Task Complexity
460
+ - Models are better at tasks that can be framed with clear
461
+ prompts and instructions. Open-ended or highly complex tasks might be
462
+ challenging.
463
+ - A model's performance can be influenced by the amount of context
464
+ provided (longer context generally leads to better outputs, up to a
465
+ certain point).
466
+ - Language Ambiguity and Nuance
467
+ - Natural language is inherently complex. Models might struggle
468
+ to grasp subtle nuances, sarcasm, or figurative language.
469
+ - Factual Accuracy
470
+ - Models generate responses based on information they learned
471
+ from their training datasets, but they are not knowledge bases. They
472
+ may generate incorrect or outdated factual statements.
473
+ - Common Sense
474
+ - Models rely on statistical patterns in language. They might
475
+ lack the ability to apply common sense reasoning in certain situations.
476
+
477
+ ### Ethical Considerations and Risks
478
+
479
+ The development of vision-language models (VLMs) raises several ethical
480
+ concerns. In creating an open model, we have carefully considered the following:
481
+
482
+ - Bias and Fairness
483
+ - VLMs trained on large-scale, real-world text and image data can
484
+ reflect socio-cultural biases embedded in the training material. These
485
+ models underwent careful scrutiny, input data pre-processing described
486
+ and posterior evaluations reported in this card.
487
+ - Misinformation and Misuse
488
+ - VLMs can be misused to generate text that is false, misleading,
489
+ or harmful.
490
+ - Guidelines are provided for responsible use with the model, see the
491
+ [Responsible Generative AI Toolkit][rai-toolkit].
492
+ - Transparency and Accountability:
493
+ - This model card summarizes details on the models' architecture,
494
+ capabilities, limitations, and evaluation processes.
495
+ - A responsibly developed open model offers the opportunity to
496
+ share innovation by making VLM technology accessible to developers and
497
+ researchers across the AI ecosystem.
498
+
499
+ Risks identified and mitigations:
500
+
501
+ - **Perpetuation of biases**: It's encouraged to perform continuous
502
+ monitoring (using evaluation metrics, human review) and the exploration of
503
+ de-biasing techniques during model training, fine-tuning, and other use
504
+ cases.
505
+ - **Generation of harmful content**: Mechanisms and guidelines for content
506
+ safety are essential. Developers are encouraged to exercise caution and
507
+ implement appropriate content safety safeguards based on their specific
508
+ product policies and application use cases.
509
+ - **Misuse for malicious purposes**: Technical limitations and developer
510
+ and end-user education can help mitigate against malicious applications of
511
+ VLMs. Educational resources and reporting mechanisms for users to flag
512
+ misuse are provided. Prohibited uses of Gemma models are outlined in the
513
+ [Gemma Prohibited Use Policy][prohibited-use].
514
+ - **Privacy violations**: Models were trained on data filtered for removal
515
+ of certain personal information and other sensitive data. Developers are
516
+ encouraged to adhere to privacy regulations with privacy-preserving
517
+ techniques.
518
+
519
+ ### Benefits
520
+
521
+ At the time of release, this family of models provides high-performance open
522
+ vision-language model implementations designed from the ground up for
523
+ responsible AI development compared to similarly sized models.
524
+
525
+ Using the benchmark evaluation metrics described in this document, these models
526
+ have shown to provide superior performance to other, comparably-sized open model
527
+ alternatives.
528
+
529
+ [g3-tech-report]: https://goo.gle/Gemma3Report
530
+ [rai-toolkit]: https://ai.google.dev/responsible
531
+ [kaggle-gemma]: https://www.kaggle.com/models/google/gemma-3
532
+ [vertex-mg-gemma3]: https://console.cloud.google.com/vertex-ai/publishers/google/model-garden/gemma3
533
+ [terms]: https://ai.google.dev/gemma/terms
534
+ [safety-policies]: https://ai.google/static/documents/ai-responsibility-update-published-february-2025.pdf
535
+ [prohibited-use]: https://ai.google.dev/gemma/prohibited_use_policy
536
+ [tpu]: https://cloud.google.com/tpu/docs/intro-to-tpu
537
+ [sustainability]: https://sustainability.google/operating-sustainably/
538
+ [jax]: https://github.com/jax-ml/jax
539
+ [ml-pathways]: https://blog.google/technology/ai/introducing-pathways-next-generation-ai-architecture/
540
+ [sustainability]: https://sustainability.google/operating-sustainably/
541
+ [gemini-2-paper]: https://arxiv.org/abs/2312.11805
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "<image_soft_token>": 262144
3
+ }
chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "{{ bos_token }}\n{%- if messages[0]['role'] == 'system' -%}\n {%- if messages[0]['content'] is string -%}\n {%- set first_user_prefix = messages[0]['content'] + '\n\n' -%}\n {%- else -%}\n {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%}\n {%- endif -%}\n {%- set loop_messages = messages[1:] -%}\n{%- else -%}\n {%- set first_user_prefix = \"\" -%}\n {%- set loop_messages = messages -%}\n{%- endif -%}\n{%- for message in loop_messages -%}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception(\"Conversation roles must alternate user/assistant/user/assistant/...\") }}\n {%- endif -%}\n {%- if (message['role'] == 'assistant') -%}\n {%- set role = \"model\" -%}\n {%- else -%}\n {%- set role = message['role'] -%}\n {%- endif -%}\n {{ '<start_of_turn>' + role + '\n' + (first_user_prefix if loop.first else \"\") }}\n {%- if message['content'] is string -%}\n {{ message['content'] | trim }}\n {%- elif message['content'] is iterable -%}\n {%- for item in message['content'] -%}\n {%- if item['type'] == 'image' -%}\n {{ '<start_of_image>' }}\n {%- elif item['type'] == 'text' -%}\n {{ item['text'] | trim }}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{ raise_exception(\"Invalid content type\") }}\n {%- endif -%}\n {{ '<end_of_turn>\n' }}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{'<start_of_turn>model\n'}}\n{%- endif -%}\n"
3
+ }
config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Gemma3ForConditionalGeneration"
4
+ ],
5
+ "boi_token_index": 255999,
6
+ "eoi_token_index": 256000,
7
+ "eos_token_id": [
8
+ 1,
9
+ 106
10
+ ],
11
+ "image_token_index": 262144,
12
+ "initializer_range": 0.02,
13
+ "mm_tokens_per_image": 256,
14
+ "model_type": "gemma3",
15
+ "text_config": {
16
+ "head_dim": 128,
17
+ "hidden_size": 5376,
18
+ "intermediate_size": 21504,
19
+ "model_type": "gemma3_text",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 62,
22
+ "num_key_value_heads": 16,
23
+ "query_pre_attn_scalar": 168,
24
+ "rope_scaling": {
25
+ "factor": 8.0,
26
+ "rope_type": "linear"
27
+ },
28
+ "sliding_window": 1024
29
+ },
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.50.0.dev0",
32
+ "vision_config": {
33
+ "hidden_size": 1152,
34
+ "image_size": 896,
35
+ "intermediate_size": 4304,
36
+ "model_type": "siglip_vision_model",
37
+ "num_attention_heads": 16,
38
+ "num_hidden_layers": 27,
39
+ "patch_size": 14,
40
+ "vision_use_head": false
41
+ },
42
+ "quantization_config": {
43
+ "bits": 4,
44
+ "group_size": 32,
45
+ "quant_method": "awq",
46
+ "version": "gemm",
47
+ "zero_point": true,
48
+ "modules_to_not_convert": [
49
+ "lm_head",
50
+ "vision_tower"
51
+ ]
52
+ }
53
+ }
convert_flax.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ from pathlib import Path
4
+
5
+ import jax
6
+ import jax.numpy as jnp
7
+ import numpy as np
8
+ import orbax.checkpoint as ocp
9
+ from safetensors.flax import save_file
10
+ from tqdm import tqdm
11
+
12
+ SIGLIP_PREFIX = "SigLiPFromPatches_0/siglip_encoder"
13
+
14
+
15
+ def flatten(x: np.ndarray, start: int = 0, end: int = -1):
16
+ if start < 0:
17
+ start += x.ndim
18
+ if end < 0:
19
+ end += x.ndim
20
+ new_shape = x.shape[:start] + (-1,) + x.shape[end + 1 :]
21
+ return x.reshape(new_shape)
22
+
23
+
24
+ def unflatten(x: np.ndarray, dim: int, sizes: tuple[int, ...]):
25
+ new_shape = x.shape[:dim] + tuple(sizes) + x.shape[dim + 1 :]
26
+ return x.reshape(new_shape)
27
+
28
+
29
+ # correct quantization parameters mean quantization error = 0 (or close to 0)
30
+ def check_groups(groups: np.ndarray, scales: np.ndarray, dim: int):
31
+ # groups: (a, b, c, 32, d, e, f)
32
+ # scales: (a, b, c, 1, d, e, f)
33
+ inv_scale = 1.0 / scales.clip(1e-12)
34
+ q_group = np.round(groups * inv_scale)
35
+ max_diff = np.abs(q_group * scales - groups).max(dim, keepdims=True)
36
+ return max_diff < 1e-6, max_diff
37
+
38
+
39
+ def find_scales(w: np.ndarray, dim: int):
40
+ w = unflatten(w, dim, (-1, 32))
41
+ group_range = w.max(dim + 1, keepdims=True) - w.min(dim + 1, keepdims=True)
42
+
43
+ scales = np.zeros_like(group_range)
44
+ for q in range(15, 0, -1):
45
+ try_scale = group_range / q
46
+ ok, _ = check_groups(w, try_scale, dim + 1)
47
+ scales[ok] = try_scale[ok]
48
+
49
+ ok, _ = check_groups(w, scales, dim + 1)
50
+ assert ok.all()
51
+
52
+ return scales.squeeze(dim + 1)
53
+
54
+
55
+ def convert_siglip(params, num_layers: int):
56
+ state_dict = dict()
57
+
58
+ def convert_layer(prefix: str, layer: dict[str, np.ndarray]):
59
+ bias = layer["bias"]
60
+
61
+ if "kernel" in layer:
62
+ w = layer["kernel"]
63
+ if w.ndim == 2: # linear layer
64
+ w = w.T
65
+
66
+ elif w.ndim == 3: # attn projection
67
+ # qkv projection - (dim, num_heads, head_dim)
68
+ if bias.ndim == 2:
69
+ w = flatten(w, 1, 2).T
70
+ bias = bias.reshape(-1)
71
+
72
+ # o projection - (num_heads, head_dim, dim)
73
+ elif bias.ndim == 1:
74
+ w = flatten(w, 0, 1).T
75
+
76
+ elif w.ndim == 4: # conv2d layer
77
+ w = w.transpose(3, 2, 0, 1)
78
+
79
+ else:
80
+ raise RuntimeError(f"Unsupported {w.shape=}")
81
+
82
+ elif "scale" in layer: # layer norm
83
+ w = layer["scale"]
84
+
85
+ else:
86
+ raise RuntimeError
87
+
88
+ state_dict[f"{prefix}weight"] = w
89
+ state_dict[f"{prefix}bias"] = bias
90
+
91
+ convert_layer("embeddings.patch_embedding.", params[f"{SIGLIP_PREFIX}/embedding"])
92
+ state_dict["embeddings.position_embedding.weight"] = params[SIGLIP_PREFIX]["pos_embedding"].squeeze(0)
93
+ convert_layer("post_layernorm.", params[f"{SIGLIP_PREFIX}/Transformer/encoder_norm"])
94
+
95
+ for layer_idx in range(num_layers):
96
+ prefix = f"encoder.layers.{layer_idx}."
97
+ layer_prefix = f"{SIGLIP_PREFIX}/Transformer/encoderblock_{layer_idx}/"
98
+
99
+ convert_layer(f"{prefix}layer_norm1.", params[f"{layer_prefix}LayerNorm_0"])
100
+ convert_layer(f"{prefix}layer_norm2.", params[f"{layer_prefix}LayerNorm_1"])
101
+
102
+ attn_prefix = f"{layer_prefix}MultiHeadDotProductAttention_0/"
103
+ convert_layer(f"{prefix}self_attn.q_proj.", params[f"{attn_prefix}query"])
104
+ convert_layer(f"{prefix}self_attn.k_proj.", params[f"{attn_prefix}key"])
105
+ convert_layer(f"{prefix}self_attn.v_proj.", params[f"{attn_prefix}value"])
106
+ convert_layer(f"{prefix}self_attn.out_proj.", params[f"{attn_prefix}out"])
107
+
108
+ mlp_prefix = f"{layer_prefix}MlpBlock_0/"
109
+ convert_layer(f"{prefix}mlp.fc1.", params[f"{mlp_prefix}Dense_0"])
110
+ convert_layer(f"{prefix}mlp.fc2.", params[f"{mlp_prefix}Dense_1"])
111
+
112
+ return state_dict
113
+
114
+
115
+ # convert to HF format first, then apply quantization
116
+ def convert_to_hf(path: Path):
117
+ path = path.absolute() # orbax only works with absolute path
118
+ ckpt = ocp.StandardCheckpointer()
119
+ metadata = dict(ckpt.metadata(path))
120
+ metadata = jax.tree.map(ocp.utils.to_shape_dtype_struct, metadata)
121
+
122
+ num_layers = num_siglip_layers = 0
123
+ while f"transformer/layer_{num_layers}/attn/_key_norm" in metadata:
124
+ num_layers += 1
125
+ while f"{SIGLIP_PREFIX}/Transformer/encoderblock_{num_siglip_layers}/LayerNorm_0" in metadata:
126
+ num_siglip_layers += 1
127
+ print(f"{num_layers=}")
128
+ print(f"{num_siglip_layers=}")
129
+
130
+ # NOTE: all gemma3 models use tied embeddings, even for the 27B version.
131
+ params = ckpt.restore(path)
132
+ state_dict = dict()
133
+
134
+ if num_siglip_layers > 0:
135
+ # HF append unused tokens for no reason???
136
+ embed = params["transformer/embedder"]["input_embedding"]
137
+ params["transformer/embedder"]["input_embedding"] = np.pad(embed, ((0, 64), (0, 0)))
138
+ gemma_prefix = "language_model."
139
+
140
+ prefix = "multi_modal_projector.mm_"
141
+ jax_prefix = "transformer/embedder/"
142
+ state_dict[f"{prefix}input_projection_weight"] = params[f"{jax_prefix}mm_input_projection"]["w"]
143
+ state_dict[f"{prefix}soft_emb_norm.weight"] = params[f"{jax_prefix}mm_soft_embedding_norm"]["scale"]
144
+
145
+ else:
146
+ gemma_prefix = ""
147
+
148
+ state_dict[f"{gemma_prefix}model.embed_tokens.weight"] = params["transformer/embedder"]["input_embedding"]
149
+ state_dict[f"{gemma_prefix}model.norm.weight"] = params["transformer/final_norm"]["scale"]
150
+
151
+ yield state_dict
152
+
153
+ for layer_idx in range(num_layers):
154
+ jax_prefix = f"transformer/layer_{layer_idx}/"
155
+
156
+ state_dict = dict()
157
+ prefix = f"{gemma_prefix}model.layers.{layer_idx}."
158
+ state_dict[f"{prefix}input_layernorm.weight"] = params[f"{jax_prefix}pre_attention_norm"]["scale"]
159
+ state_dict[f"{prefix}post_attention_layernorm.weight"] = params[f"{jax_prefix}post_attention_norm"]["scale"]
160
+ state_dict[f"{prefix}pre_feedforward_layernorm.weight"] = params[f"{jax_prefix}pre_ffw_norm"]["scale"]
161
+ state_dict[f"{prefix}post_feedforward_layernorm.weight"] = params[f"{jax_prefix}post_ffw_norm"]["scale"]
162
+
163
+ prefix = f"{gemma_prefix}model.layers.{layer_idx}.self_attn."
164
+ jax_prefix = f"transformer/layer_{layer_idx}/attn/"
165
+ state_dict[f"{prefix}q_norm.weight"] = params[f"{jax_prefix}_query_norm"]["scale"]
166
+ state_dict[f"{prefix}k_norm.weight"] = params[f"{jax_prefix}_key_norm"]["scale"]
167
+
168
+ # (num_heads, hidden_size, head_dim) -> (num_heads * head_dim, hidden_size)
169
+ state_dict[f"{prefix}q_proj.weight"] = flatten(params[f"{jax_prefix}q_einsum"]["w"].transpose(0, 2, 1), end=1)
170
+ state_dict[f"{prefix}k_proj.weight"] = flatten(
171
+ params[f"{jax_prefix}kv_einsum"]["w"][0].transpose(0, 2, 1), end=1
172
+ )
173
+ state_dict[f"{prefix}v_proj.weight"] = flatten(
174
+ params[f"{jax_prefix}kv_einsum"]["w"][1].transpose(0, 2, 1), end=1
175
+ )
176
+
177
+ # (num_heads, head_dim, hidden_size) -> (hidden_size, num_heads * head_dim)
178
+ state_dict[f"{prefix}o_proj.weight"] = flatten(params[f"{jax_prefix}attn_vec_einsum"]["w"], end=1).T
179
+
180
+ prefix = f"{gemma_prefix}model.layers.{layer_idx}.mlp."
181
+ jax_prefix = f"transformer/layer_{layer_idx}/mlp/"
182
+ state_dict[f"{prefix}gate_proj.weight"] = params[f"{jax_prefix}gating_einsum"]["w"][0]
183
+ state_dict[f"{prefix}up_proj.weight"] = params[f"{jax_prefix}gating_einsum"]["w"][1]
184
+ state_dict[f"{prefix}down_proj.weight"] = params[f"{jax_prefix}linear"]["w"].T
185
+
186
+ yield state_dict
187
+
188
+ # vision tower
189
+ if num_siglip_layers > 0:
190
+ siglip_state_dict = convert_siglip(params, num_siglip_layers)
191
+ for k, v in siglip_state_dict.items():
192
+ state_dict[f"vision_tower.vision_model.{k}"] = v
193
+ yield state_dict
194
+
195
+
196
+ def convert_awq(state_dict: dict[str, np.ndarray]):
197
+ awq_state_dict = dict()
198
+
199
+ for k, v in state_dict.items():
200
+ if (
201
+ k.endswith("model.embed_tokens.weight") # AWQ doesn't support INT4 embeddings
202
+ or k.startswith(("vision_tower", "multi_modal_projector")) # vision tower is not quantized
203
+ or v.ndim == 1
204
+ ):
205
+ awq_state_dict[k] = v.astype(jnp.bfloat16)
206
+ continue
207
+
208
+ assert v.ndim == 2
209
+ v = v.T # AWQ transpose the weight
210
+
211
+ K, N = v.shape
212
+ scales = find_scales(v, dim=0) # (K/32, N)
213
+ inv_scale = 1 / scales.clip(1e-12)
214
+ qweight = np.round(v.reshape(K // 32, 32, N) * inv_scale[:, None])
215
+
216
+ # AWQ is actually UINT4 (instead of INT4)
217
+ # hence, we will shift qweight up by 8 (even though Google AQT only uses [-7,7])
218
+ # and set zero_point = 8
219
+ qweight = (qweight + 8).astype(np.uint32)
220
+
221
+ # AWQ pack 8 int4 into UINT32 in the following layout (from high bits to low bits)
222
+ # [7 5 3 1 6 4 2 0] along the 2nd dim
223
+ qweight = qweight.reshape(K, N // 8, 8)
224
+ qweight_packed = (
225
+ (qweight[..., 7] << (7 * 4))
226
+ | (qweight[..., 5] << (6 * 4))
227
+ | (qweight[..., 3] << (5 * 4))
228
+ | (qweight[..., 1] << (4 * 4))
229
+ | (qweight[..., 6] << (3 * 4))
230
+ | (qweight[..., 4] << (2 * 4))
231
+ | (qweight[..., 2] << (1 * 4))
232
+ | (qweight[..., 0] << (0 * 4))
233
+ )
234
+ qweight_packed = qweight_packed.view(np.int32).reshape(K, N // 8)
235
+
236
+ prefix = k.removesuffix(".weight")
237
+ awq_state_dict[f"{prefix}.qweight"] = qweight_packed
238
+ awq_state_dict[f"{prefix}.qzeros"] = np.full((K // 32, N // 8), 0x8888_8888, dtype=np.uint32).view(np.int32)
239
+ awq_state_dict[f"{prefix}.scales"] = scales.astype(jnp.bfloat16)
240
+
241
+ return awq_state_dict
242
+
243
+
244
+ if __name__ == "__main__":
245
+ parser = argparse.ArgumentParser()
246
+ parser.add_argument("--ckpt_dir", required=True, type=Path)
247
+ parser.add_argument("--save_dir", required=True, type=Path)
248
+ args = parser.parse_args()
249
+
250
+ args.save_dir.mkdir(parents=True, exist_ok=True)
251
+
252
+ total_size = 0
253
+ weight_map = dict()
254
+
255
+ state_dict = dict()
256
+ size = 0
257
+ shard_idx = 0
258
+ filename = f"model-{shard_idx + 1:05d}.safetensors"
259
+ for sub_state_dict in tqdm(convert_to_hf(args.ckpt_dir)):
260
+ sub_state_dict = convert_awq(sub_state_dict)
261
+ new_size = sum(v.nbytes for v in sub_state_dict.values())
262
+
263
+ if size + new_size > 5e9:
264
+ save_file(state_dict, args.save_dir / filename)
265
+ state_dict = dict()
266
+ size = 0
267
+ shard_idx += 1
268
+ filename = f"model-{shard_idx + 1:05d}.safetensors"
269
+
270
+ # assume that new_size < 5e9
271
+ size += new_size
272
+ total_size += new_size
273
+ for k, v in sub_state_dict.items():
274
+ state_dict[k] = v
275
+ weight_map[k] = filename
276
+
277
+ save_file(state_dict, args.save_dir / filename)
278
+ json.dump(
279
+ dict(metadata=dict(total_size=total_size), weight_map=weight_map),
280
+ open(args.save_dir / "model.safetensors.index.json", "w"),
281
+ )
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 2,
3
+ "cache_implementation": "hybrid",
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 1,
7
+ 106
8
+ ],
9
+ "pad_token_id": 0,
10
+ "top_k": 64,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.50.0.dev0"
13
+ }
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfe46693f149bea38e2c089161ab180ea08f03f2a647d9ade2d63c9f290c0f77
3
+ size 4980332880
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b7e265b1583962613677420aa8de95afd96d7cbfd47fee19d2f4959fadd978a9
3
+ size 4774828736
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc7283de8174bc0d3242ce8530eb05d636208d6164ecdeeefbf3fb672c118d12
3
+ size 4774828760
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cff33cb628f34e3b11b07952bcc696fd0f2528141b251f12a15024334e7b577
3
+ size 3937431096
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_rgb": null,
3
+ "do_normalize": true,
4
+ "do_pan_and_scan": null,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "image_mean": [
8
+ 0.5,
9
+ 0.5,
10
+ 0.5
11
+ ],
12
+ "image_processor_type": "Gemma3ImageProcessor",
13
+ "image_seq_length": 256,
14
+ "image_std": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "pan_and_scan_max_num_crops": null,
20
+ "pan_and_scan_min_crop_size": null,
21
+ "pan_and_scan_min_ratio_to_activate": null,
22
+ "processor_class": "Gemma3Processor",
23
+ "resample": 2,
24
+ "rescale_factor": 0.00392156862745098,
25
+ "size": {
26
+ "height": 896,
27
+ "width": 896
28
+ }
29
+ }
processor_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "image_seq_length": 256,
3
+ "processor_class": "Gemma3Processor"
4
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "boi_token": "<start_of_image>",
3
+ "bos_token": {
4
+ "content": "<bos>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ "eoi_token": "<end_of_image>",
11
+ "eos_token": {
12
+ "content": "<eos>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "image_token": "<image_soft_token>",
19
+ "pad_token": {
20
+ "content": "<pad>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "unk_token": {
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4667f2089529e8e7657cfb6d1c19910ae71ff5f28aa7ab2ff2763330affad795
3
+ size 33384568
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1299c11d7cf632ef3b4e11937501358ada021bbdf7c47638d13c0ee982f2e79c
3
+ size 4689074
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff