Upload gemma_safetensors.py with huggingface_hub
Browse files- gemma_safetensors.py +45 -0
gemma_safetensors.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import torch
|
| 4 |
+
from safetensors.torch import load_file, save_file
|
| 5 |
+
from huggingface_hub import snapshot_download
|
| 6 |
+
|
| 7 |
+
# 1. Download official model shards from Hugging Face
|
| 8 |
+
model_id = "google/gemma-4-31B-it"
|
| 9 |
+
local_dir = "./gemma-4-31B-it"
|
| 10 |
+
print("Downloading model shards...")
|
| 11 |
+
snapshot_download(repo_id=model_id, local_dir=local_dir, allow_patterns=["*.safetensors", "tokenizer.json"])
|
| 12 |
+
|
| 13 |
+
# 2. Merge shards and remap key prefixes to match gemma4.py
|
| 14 |
+
state_dict = {}
|
| 15 |
+
print("Remapping keys...")
|
| 16 |
+
for filename in sorted(os.listdir(local_dir)):
|
| 17 |
+
if filename.endswith(".safetensors"):
|
| 18 |
+
shard_path = os.path.join(local_dir, filename)
|
| 19 |
+
shard = load_file(shard_path)
|
| 20 |
+
for key, tensor in shard.items():
|
| 21 |
+
new_key = key
|
| 22 |
+
# Strip Hugging Face wrappers
|
| 23 |
+
if new_key.startswith("model.language_model.model."):
|
| 24 |
+
new_key = "model." + new_key[len("model.language_model.model."):]
|
| 25 |
+
elif new_key.startswith("model.language_model."):
|
| 26 |
+
new_key = "model." + new_key[len("model.language_model."):]
|
| 27 |
+
elif new_key.startswith("model.vision_tower."):
|
| 28 |
+
new_key = "vision_model." + new_key[len("model.vision_tower."):]
|
| 29 |
+
elif new_key.startswith("model.multi_modal_projector."):
|
| 30 |
+
new_key = "multi_modal_projector." + new_key[len("model.multi_modal_projector."):]
|
| 31 |
+
|
| 32 |
+
state_dict[new_key] = tensor
|
| 33 |
+
|
| 34 |
+
# 3. Embed tokenizer.json in safetensors metadata header
|
| 35 |
+
metadata = {}
|
| 36 |
+
tokenizer_path = os.path.join(local_dir, "tokenizer.json")
|
| 37 |
+
if os.path.exists(tokenizer_path):
|
| 38 |
+
with open(tokenizer_path, "r", encoding="utf-8") as f:
|
| 39 |
+
metadata["tokenizer_json"] = f.read()
|
| 40 |
+
|
| 41 |
+
# 4. Save unified ComfyUI safetensors file
|
| 42 |
+
output_path = "gemma4_31b_it_bf16.safetensors"
|
| 43 |
+
print(f"Saving merged model to {output_path}...")
|
| 44 |
+
save_file(state_dict, output_path, metadata=metadata)
|
| 45 |
+
print("Conversion complete!")
|