File size: 6,495 Bytes
fc00f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9927f8
 
 
 
 
 
 
 
 
 
 
 
 
 
fc00f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9927f8
fc00f3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
---
library_name: transformers
base_model:
- google/gemma-4-31B-it-assistant
---

This tiny model is intended for debugging. It is randomly initialized using the configuration adapted from [google/gemma-4-31B-it-assistant](https://huggingface.co/google/gemma-4-31B-it-assistant).

| File path | Size |
|------|------|
| model.safetensors | 4.3MB |


### Example usage:

```python
import torch
from transformers import AutoModelForCausalLM, AutoProcessor, AutoModelForMultimodalLM

model_id = "tiny-random/gemma-4-assistant"
target_model_id = "tiny-random/gemma-4-moe"

processor = AutoProcessor.from_pretrained(target_model_id)
target_model = AutoModelForMultimodalLM.from_pretrained(
    target_model_id,
    dtype=torch.bfloat16,
    device_map="auto",
)
assistant_model = AutoModelForCausalLM.from_pretrained(
    model_id,
    dtype=torch.bfloat16,
    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 is shown in this image?"},
        ],
    },
    {
        "role": "assistant",
        "content": [{"type": "text", "text": "Dummy response for image"}],
    },
    {
        "role": "user",
        "content": [
            {
                "type": "video",
                "video": "https://github.com/bebechien/gemma/raw/refs/heads/main/videos/ForBiggerBlazes.mp4",
            },
            {"type": "text", "text": "Describe this video."},
        ],
    },
]
inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    add_generation_prompt=True,
).to(target_model.device)
input_len = inputs["input_ids"].shape[-1]
print("input_len:", input_len)
outputs = target_model.generate(
    **inputs,
    assistant_model=assistant_model,
    max_new_tokens=32,
)
response = processor.decode(outputs[0], skip_special_tokens=False)
response = response.replace("<|image|>", "I")
response = response.replace("<|video|>", "V")
print(response)
```

### Codes to create this repo:

<details>
<summary>Click to expand</summary>

```python
import json
from pathlib import Path

import torch
from huggingface_hub import file_exists, hf_hub_download

from transformers import (
    AutoConfig,
    AutoModelForCausalLM,
    AutoProcessor,
    AutoTokenizer,
    Gemma4AssistantForCausalLM,
    Gemma4ForConditionalGeneration,
    GenerationConfig,
    set_seed,
)

source_model_id = "google/gemma-4-31B-it-assistant"
save_folder = "/tmp/tiny-random/gemma-4-assistant"

processor = AutoProcessor.from_pretrained(source_model_id)
processor.save_pretrained(save_folder)

with open(
    hf_hub_download(source_model_id, filename="config.json", repo_type="model"),
    "r",
    encoding="utf-8",
) as f:
    config_json = json.load(f)

config_json["backbone_hidden_size"] = 8
config_json["text_config"].update(
    {
        "global_head_dim": 64,
        "head_dim": 32,
        "hidden_size": 8,
        "intermediate_size": 64,
        "layer_types": [
            "sliding_attention",
            "sliding_attention",
            "sliding_attention",
            "full_attention",
        ],
        "moe_intermediate_size": 32,
        "num_attention_heads": 8,
        "num_hidden_layers": 4,
        "num_key_value_heads": 4,
    }
)

with open(f"{save_folder}/config.json", "w", encoding="utf-8") as f:
    json.dump(config_json, f, indent=2)

config = AutoConfig.from_pretrained(
    save_folder,
    trust_remote_code=True,
)
print(config)

torch.set_default_dtype(torch.bfloat16)
model = Gemma4AssistantForCausalLM(config)
torch.set_default_dtype(torch.float32)
if file_exists(filename="generation_config.json", repo_id=source_model_id, repo_type="model"):
    model.generation_config = GenerationConfig.from_pretrained(
        source_model_id,
        trust_remote_code=True,
    )
set_seed(42)
model = model.cpu()
all_numels = sum(p.numel() for p in model.parameters())
with torch.no_grad():
    for name, p in sorted(model.named_parameters()):
        torch.nn.init.normal_(p, 0, 0.2)
        print(name, p.shape, f"{p.numel() / all_numels * 100: .4f}%")
model.save_pretrained(save_folder)
```

</details>

### Printing the model:

<details><summary>Click to expand</summary>

```text
Gemma4AssistantForCausalLM(
  (model): Gemma4TextModel(
    (embed_tokens): Gemma4TextScaledWordEmbedding(262144, 8, padding_idx=0)
    (layers): ModuleList(
      (0-2): 3 x Gemma4TextDecoderLayer(
        (self_attn): Gemma4TextAttention(
          (q_proj): Linear(in_features=8, out_features=256, bias=False)
          (q_norm): Gemma4RMSNorm()
          (o_proj): Linear(in_features=256, out_features=8, bias=False)
        )
        (mlp): Gemma4TextMLP(
          (gate_proj): Linear(in_features=8, out_features=64, bias=False)
          (up_proj): Linear(in_features=8, out_features=64, bias=False)
          (down_proj): Linear(in_features=64, out_features=8, bias=False)
          (act_fn): GELUTanh()
        )
        (input_layernorm): Gemma4RMSNorm()
        (post_attention_layernorm): Gemma4RMSNorm()
        (pre_feedforward_layernorm): Gemma4RMSNorm()
        (post_feedforward_layernorm): Gemma4RMSNorm()
      )
      (3): Gemma4TextDecoderLayer(
        (self_attn): Gemma4TextAttention(
          (q_proj): Linear(in_features=8, out_features=512, bias=False)
          (q_norm): Gemma4RMSNorm()
          (o_proj): Linear(in_features=512, out_features=8, bias=False)
        )
        (mlp): Gemma4TextMLP(
          (gate_proj): Linear(in_features=8, out_features=64, bias=False)
          (up_proj): Linear(in_features=8, out_features=64, bias=False)
          (down_proj): Linear(in_features=64, out_features=8, bias=False)
          (act_fn): GELUTanh()
        )
        (input_layernorm): Gemma4RMSNorm()
        (post_attention_layernorm): Gemma4RMSNorm()
        (pre_feedforward_layernorm): Gemma4RMSNorm()
        (post_feedforward_layernorm): Gemma4RMSNorm()
      )
    )
    (norm): Gemma4RMSNorm()
    (rotary_emb): Gemma4TextRotaryEmbedding()
  )
  (lm_head): Linear(in_features=8, out_features=262144, bias=False)
  (pre_projection): Linear(in_features=16, out_features=8, bias=False)
  (post_projection): Linear(in_features=8, out_features=8, bias=False)
)
```

</details>

### Test environment:

- torch: 2.10.0+cu130
- transformers: 5.9.0