|
|
--- |
|
|
library_name: transformers |
|
|
pipeline_tag: image-text-to-text |
|
|
inference: true |
|
|
widget: |
|
|
- text: Hello! |
|
|
example_title: Hello world |
|
|
group: Python |
|
|
base_model: |
|
|
- zai-org/GLM-4.5V |
|
|
--- |
|
|
|
|
|
This tiny model is for debugging. It is randomly initialized with the config adapted from [zai-org/GLM-4.5V](https://huggingface.co/zai-org/GLM-4.5V). |
|
|
|
|
|
### Example usage: |
|
|
|
|
|
```python |
|
|
import torch |
|
|
from transformers import AutoProcessor, Glm4vMoeForConditionalGeneration |
|
|
|
|
|
model_id = "tiny-random/glm-4.5v" |
|
|
messages = [ |
|
|
{ |
|
|
"role": "user", |
|
|
"content": [ |
|
|
{ |
|
|
"type": "image", |
|
|
"url": "https://upload.wikimedia.org/wikipedia/commons/f/fa/Grayscale_8bits_palette_sample_image.png" |
|
|
}, |
|
|
{ |
|
|
"type": "text", |
|
|
"text": "describe this image" |
|
|
} |
|
|
], |
|
|
} |
|
|
] |
|
|
processor = AutoProcessor.from_pretrained(model_id) |
|
|
model = Glm4vMoeForConditionalGeneration.from_pretrained( |
|
|
model_id, |
|
|
torch_dtype=torch.bfloat16, |
|
|
device_map="auto", |
|
|
) |
|
|
inputs = processor.apply_chat_template( |
|
|
messages, |
|
|
tokenize=True, |
|
|
add_generation_prompt=True, |
|
|
return_dict=True, |
|
|
return_tensors="pt" |
|
|
).to(model.device) |
|
|
inputs.pop("token_type_ids", None) |
|
|
generated_ids = model.generate(**inputs, max_new_tokens=16) |
|
|
output_text = processor.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=False) |
|
|
print(output_text) |
|
|
``` |
|
|
|
|
|
### Codes to create this repo: |
|
|
|
|
|
```python |
|
|
import json |
|
|
from pathlib import Path |
|
|
|
|
|
import accelerate |
|
|
import torch |
|
|
from huggingface_hub import file_exists, hf_hub_download |
|
|
from transformers import ( |
|
|
AutoConfig, |
|
|
AutoModelForCausalLM, |
|
|
AutoProcessor, |
|
|
GenerationConfig, |
|
|
Glm4vForConditionalGeneration, |
|
|
Glm4vMoeForConditionalGeneration, |
|
|
set_seed, |
|
|
) |
|
|
from transformers.models.glm4v_moe.modeling_glm4v_moe import Glm4vMoeTextTopkRouter |
|
|
|
|
|
source_model_id = "zai-org/GLM-4.5V" |
|
|
save_folder = "/tmp/tiny-random/glm-4.5v" |
|
|
processor = AutoProcessor.from_pretrained(source_model_id, trust_remote_code=True) |
|
|
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['text_config'].update({ |
|
|
"hidden_size": 32, |
|
|
"head_dim": 32, |
|
|
"intermediate_size": 128, |
|
|
"first_k_dense_replace": 1, |
|
|
"moe_intermediate_size": 64, |
|
|
"num_attention_heads": 2, |
|
|
"num_key_value_heads": 1, |
|
|
"num_hidden_layers": 2, # one dense, one moe |
|
|
"tie_word_embeddings": True, |
|
|
}) |
|
|
config_json['text_config']['rope_scaling']['mrope_section'] = [2, 2, 4] |
|
|
config_json['vision_config']['hidden_size'] = 64 |
|
|
config_json['vision_config']['depth'] = 2 |
|
|
config_json['vision_config']['num_heads'] = 2 |
|
|
config_json['vision_config']['intermediate_size'] = 128 |
|
|
config_json['vision_config']['out_hidden_size'] = config_json['text_config']['hidden_size'] |
|
|
|
|
|
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 = Glm4vMoeForConditionalGeneration(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() # cpu is more stable for random initialization across machines |
|
|
num_params = 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.1) |
|
|
print(name, p.shape, p.dtype, p.device, f'{p.numel() / num_params * 100: .2f}%') |
|
|
for _, m in sorted(model.named_modules()): |
|
|
if isinstance(m, Glm4vMoeTextTopkRouter): |
|
|
assert 'e_score_correction_bias' in m.state_dict() |
|
|
torch.nn.init.normal_(m.e_score_correction_bias, 0, 1) |
|
|
model.save_pretrained(save_folder) |
|
|
print(model) |
|
|
``` |
|
|
|
|
|
### Printing the model: |
|
|
|
|
|
```text |
|
|
Glm4vMoeForConditionalGeneration( |
|
|
(model): Glm4vMoeModel( |
|
|
(visual): Glm4vMoeVisionModel( |
|
|
(embeddings): Glm4vMoeVisionEmbeddings( |
|
|
(position_embedding): Embedding(576, 64) |
|
|
) |
|
|
(patch_embed): Glm4vMoeVisionPatchEmbed( |
|
|
(proj): Conv3d(3, 64, kernel_size=(2, 14, 14), stride=(2, 14, 14)) |
|
|
) |
|
|
(rotary_pos_emb): Glm4vMoeVisionRotaryEmbedding() |
|
|
(blocks): ModuleList( |
|
|
(0-1): 2 x Glm4vMoeVisionBlock( |
|
|
(norm1): Glm4vMoeRMSNorm((64,), eps=1e-05) |
|
|
(norm2): Glm4vMoeRMSNorm((64,), eps=1e-05) |
|
|
(attn): Glm4vMoeVisionAttention( |
|
|
(qkv): Linear(in_features=64, out_features=192, bias=False) |
|
|
(proj): Linear(in_features=64, out_features=64, bias=False) |
|
|
) |
|
|
(mlp): Glm4vMoeisionMlp( |
|
|
(gate_proj): Linear(in_features=64, out_features=32, bias=False) |
|
|
(up_proj): Linear(in_features=64, out_features=32, bias=False) |
|
|
(down_proj): Linear(in_features=32, out_features=64, bias=False) |
|
|
(act_fn): SiLU() |
|
|
) |
|
|
) |
|
|
) |
|
|
(merger): Glm4vMoeVisionPatchMerger( |
|
|
(proj): Linear(in_features=32, out_features=32, bias=False) |
|
|
(post_projection_norm): LayerNorm((32,), eps=1e-05, elementwise_affine=True) |
|
|
(gate_proj): Linear(in_features=32, out_features=128, bias=False) |
|
|
(up_proj): Linear(in_features=32, out_features=128, bias=False) |
|
|
(down_proj): Linear(in_features=128, out_features=32, bias=False) |
|
|
(act1): GELU(approximate='none') |
|
|
(act_fn): SiLU() |
|
|
) |
|
|
(post_conv_layernorm): Glm4vMoeRMSNorm((64,), eps=1e-05) |
|
|
(downsample): Conv2d(64, 32, kernel_size=(2, 2), stride=(2, 2)) |
|
|
(post_layernorm): Glm4vMoeRMSNorm((64,), eps=1e-05) |
|
|
) |
|
|
(language_model): Glm4vMoeTextModel( |
|
|
(embed_tokens): Embedding(151552, 32, padding_idx=151329) |
|
|
(layers): ModuleList( |
|
|
(0): Glm4vMoeTextDecoderLayer( |
|
|
(self_attn): Glm4vMoeTextAttention( |
|
|
(q_proj): Linear(in_features=32, out_features=64, bias=True) |
|
|
(k_proj): Linear(in_features=32, out_features=32, bias=True) |
|
|
(v_proj): Linear(in_features=32, out_features=32, bias=True) |
|
|
(o_proj): Linear(in_features=64, out_features=32, bias=False) |
|
|
) |
|
|
(mlp): Glm4vMoeTextMLP( |
|
|
(gate_proj): Linear(in_features=32, out_features=128, bias=False) |
|
|
(up_proj): Linear(in_features=32, out_features=128, bias=False) |
|
|
(down_proj): Linear(in_features=128, out_features=32, bias=False) |
|
|
(act_fn): SiLU() |
|
|
) |
|
|
(input_layernorm): Glm4vMoeTextRMSNorm((32,), eps=1e-05) |
|
|
(post_attention_layernorm): Glm4vMoeTextRMSNorm((32,), eps=1e-05) |
|
|
) |
|
|
(1): Glm4vMoeTextDecoderLayer( |
|
|
(self_attn): Glm4vMoeTextAttention( |
|
|
(q_proj): Linear(in_features=32, out_features=64, bias=True) |
|
|
(k_proj): Linear(in_features=32, out_features=32, bias=True) |
|
|
(v_proj): Linear(in_features=32, out_features=32, bias=True) |
|
|
(o_proj): Linear(in_features=64, out_features=32, bias=False) |
|
|
) |
|
|
(mlp): Glm4vMoeTextMoE( |
|
|
(experts): ModuleList( |
|
|
(0-127): 128 x Glm4vMoeTextMLP( |
|
|
(gate_proj): Linear(in_features=32, out_features=64, bias=False) |
|
|
(up_proj): Linear(in_features=32, out_features=64, bias=False) |
|
|
(down_proj): Linear(in_features=64, out_features=32, bias=False) |
|
|
(act_fn): SiLU() |
|
|
) |
|
|
) |
|
|
(gate): Glm4vMoeTextTopkRouter() |
|
|
(shared_experts): Glm4vMoeTextMLP( |
|
|
(gate_proj): Linear(in_features=32, out_features=64, bias=False) |
|
|
(up_proj): Linear(in_features=32, out_features=64, bias=False) |
|
|
(down_proj): Linear(in_features=64, out_features=32, bias=False) |
|
|
(act_fn): SiLU() |
|
|
) |
|
|
) |
|
|
(input_layernorm): Glm4vMoeTextRMSNorm((32,), eps=1e-05) |
|
|
(post_attention_layernorm): Glm4vMoeTextRMSNorm((32,), eps=1e-05) |
|
|
) |
|
|
) |
|
|
(norm): Glm4vMoeRMSNorm((32,), eps=1e-05) |
|
|
(rotary_emb): Glm4vMoeTextRotaryEmbedding() |
|
|
) |
|
|
) |
|
|
(lm_head): Linear(in_features=32, out_features=151552, bias=False) |
|
|
) |
|
|
``` |