Delete main.py
Browse files
main.py
DELETED
|
@@ -1,219 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
from safetensors.torch import save_file, load_file
|
| 3 |
-
import sys
|
| 4 |
-
import json
|
| 5 |
-
|
| 6 |
-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 7 |
-
|
| 8 |
-
def create_bitnet_safetensors(output_file="model_1.safetensors",
|
| 9 |
-
dtype=torch.bfloat16,
|
| 10 |
-
num_heads=4,
|
| 11 |
-
num_layers=4,
|
| 12 |
-
image_feature_dim=256,
|
| 13 |
-
device=device,
|
| 14 |
-
quantize=True):
|
| 15 |
-
"""
|
| 16 |
-
Creates a safetensors file with initialized BitNet model weights.
|
| 17 |
-
"""
|
| 18 |
-
tensors = {}
|
| 19 |
-
|
| 20 |
-
# These values reduce model size; adjust as needed
|
| 21 |
-
embedding_dim = 5376 // 4
|
| 22 |
-
intermediate_size = 21504 // 4
|
| 23 |
-
head_dim = embedding_dim // num_heads
|
| 24 |
-
|
| 25 |
-
# Text Encoder Components
|
| 26 |
-
# Text embedding
|
| 27 |
-
tensors["language_model.model.embed_tokens.weight"] = torch.randn(262208 // 4, embedding_dim, dtype=dtype, device=device) * 0.02
|
| 28 |
-
|
| 29 |
-
# Text layers
|
| 30 |
-
for layer_idx in range(num_layers):
|
| 31 |
-
layer_prefix = f"language_model.model.layers.{layer_idx}"
|
| 32 |
-
|
| 33 |
-
# Layer normalization
|
| 34 |
-
tensors[f"{layer_prefix}.pre_attn_layernorm.weight"] = torch.ones(embedding_dim, dtype=dtype, device=device)
|
| 35 |
-
tensors[f"{layer_prefix}.post_mlp_layernorm.weight"] = torch.ones(embedding_dim, dtype=dtype, device=device)
|
| 36 |
-
|
| 37 |
-
# Self-attention projections (Q, K, V)
|
| 38 |
-
tensors[f"{layer_prefix}.self_attn.q_proj.weight"] = torch.randn(embedding_dim, embedding_dim, dtype=dtype, device=device) * (embedding_dim ** -0.5)
|
| 39 |
-
tensors[f"{layer_prefix}.self_attn.k_proj.weight"] = torch.randn(embedding_dim, embedding_dim, dtype=dtype, device=device) * (embedding_dim ** -0.5)
|
| 40 |
-
tensors[f"{layer_prefix}.self_attn.v_proj.weight"] = torch.randn(embedding_dim, embedding_dim, dtype=dtype, device=device) * (embedding_dim ** -0.5)
|
| 41 |
-
|
| 42 |
-
# Self-attention output projection
|
| 43 |
-
tensors[f"{layer_prefix}.self_attn.out_proj.weight"] = torch.randn(embedding_dim, embedding_dim, dtype=dtype, device=device) * (embedding_dim ** -0.5)
|
| 44 |
-
|
| 45 |
-
# MLP sub-block: first linear layer
|
| 46 |
-
tensors[f"{layer_prefix}.mlp.fc1.weight"] = torch.randn(intermediate_size, embedding_dim, dtype=dtype, device=device) * (embedding_dim ** -0.5)
|
| 47 |
-
tensors[f"{layer_prefix}.mlp.fc1.bias"] = torch.zeros(intermediate_size, dtype=dtype, device=device)
|
| 48 |
-
|
| 49 |
-
# MLP sub-block: second linear layer
|
| 50 |
-
tensors[f"{layer_prefix}.mlp.fc2.weight"] = torch.randn(embedding_dim, intermediate_size, dtype=dtype, device=device) * (intermediate_size ** -0.5)
|
| 51 |
-
tensors[f"{layer_prefix}.mlp.fc2.bias"] = torch.zeros(embedding_dim, dtype=dtype, device=device)
|
| 52 |
-
|
| 53 |
-
# Vision Encoder Components
|
| 54 |
-
patch_size = 16
|
| 55 |
-
image_size = 224
|
| 56 |
-
num_patches = (image_size // patch_size) ** 2
|
| 57 |
-
vision_embedding_dim = embedding_dim
|
| 58 |
-
|
| 59 |
-
# Patch Embedding
|
| 60 |
-
tensors["vision_encoder.patch_embedding.weight"] = torch.randn(vision_embedding_dim, 3, patch_size, patch_size, dtype=dtype, device=device) * 0.02
|
| 61 |
-
tensors["vision_encoder.patch_embedding.bias"] = torch.zeros(vision_embedding_dim, dtype=dtype, device=device)
|
| 62 |
-
|
| 63 |
-
# Positional Embeddings
|
| 64 |
-
tensors["vision_encoder.position_embeddings"] = torch.randn(1, num_patches + 1, vision_embedding_dim, dtype=dtype, device=device) * 0.02
|
| 65 |
-
|
| 66 |
-
# Class Token
|
| 67 |
-
tensors["vision_encoder.cls_token"] = torch.randn(1, 1, vision_embedding_dim, dtype=dtype, device=device) * 0.02
|
| 68 |
-
|
| 69 |
-
# Vision Transformer Layers
|
| 70 |
-
for layer_idx in range(num_layers):
|
| 71 |
-
layer_prefix = f"vision_encoder.transformer.layers.{layer_idx}"
|
| 72 |
-
|
| 73 |
-
# Pre-Attention Layer Normalization
|
| 74 |
-
tensors[f"{layer_prefix}.pre_attn_layernorm.weight"] = torch.ones(vision_embedding_dim, dtype=dtype, device=device)
|
| 75 |
-
|
| 76 |
-
# Self-Attention projections (Q, K, V)
|
| 77 |
-
tensors[f"{layer_prefix}.self_attn.q_proj.weight"] = torch.randn(vision_embedding_dim, vision_embedding_dim, dtype=dtype, device=device) * (vision_embedding_dim ** -0.5)
|
| 78 |
-
tensors[f"{layer_prefix}.self_attn.k_proj.weight"] = torch.randn(vision_embedding_dim, vision_embedding_dim, dtype=dtype, device=device) * (vision_embedding_dim ** -0.5)
|
| 79 |
-
tensors[f"{layer_prefix}.self_attn.v_proj.weight"] = torch.randn(vision_embedding_dim, vision_embedding_dim, dtype=dtype, device=device) * (vision_embedding_dim ** -0.5)
|
| 80 |
-
|
| 81 |
-
# Self-Attention output projection
|
| 82 |
-
tensors[f"{layer_prefix}.self_attn.out_proj.weight"] = torch.randn(vision_embedding_dim, vision_embedding_dim, dtype=dtype, device=device) * (vision_embedding_dim ** -0.5)
|
| 83 |
-
|
| 84 |
-
# MLP sub-block: first linear layer
|
| 85 |
-
tensors[f"{layer_prefix}.mlp.fc1.weight"] = torch.randn(vision_embedding_dim, intermediate_size, dtype=dtype, device=device) * (vision_embedding_dim ** -0.5)
|
| 86 |
-
tensors[f"{layer_prefix}.mlp.fc1.bias"] = torch.zeros(intermediate_size, dtype=dtype, device=device)
|
| 87 |
-
|
| 88 |
-
# MLP sub-block: second linear layer
|
| 89 |
-
tensors[f"{layer_prefix}.mlp.fc2.weight"] = torch.randn(intermediate_size, vision_embedding_dim, dtype=dtype, device=device) * (vision_embedding_dim ** -0.5)
|
| 90 |
-
tensors[f"{layer_prefix}.mlp.fc2.bias"] = torch.zeros(vision_embedding_dim, dtype=dtype, device=device)
|
| 91 |
-
|
| 92 |
-
# Post-MLP Layer Normalization
|
| 93 |
-
tensors[f"{layer_prefix}.post_mlp_layernorm.weight"] = torch.ones(vision_embedding_dim, dtype=dtype, device=device)
|
| 94 |
-
|
| 95 |
-
total_params = sum(tensor.numel() * tensor.element_size() for tensor in tensors.values())
|
| 96 |
-
total_params_gb = total_params / (1024 ** 3)
|
| 97 |
-
|
| 98 |
-
print(f"Estimated total parameter size: {total_params_gb:.2f} GB ({dtype}).")
|
| 99 |
-
|
| 100 |
-
proceed = input("Do you want to proceed and create the safetensors file? (y/n): ").lower()
|
| 101 |
-
|
| 102 |
-
if proceed == 'y':
|
| 103 |
-
if quantize:
|
| 104 |
-
# Apply 1.58-bit quantization
|
| 105 |
-
quantized_tensors = {}
|
| 106 |
-
for key, tensor in tensors.items():
|
| 107 |
-
# Normalize the tensor
|
| 108 |
-
max_val = torch.max(torch.abs(tensor))
|
| 109 |
-
normalized = tensor / max_val
|
| 110 |
-
|
| 111 |
-
# Quantize to {-1, 0, 1}
|
| 112 |
-
quantized = torch.where(normalized > 0.5, torch.ones_like(normalized),
|
| 113 |
-
torch.where(normalized < -0.5, -torch.ones_like(normalized), torch.zeros_like(normalized)))
|
| 114 |
-
|
| 115 |
-
quantized_tensors[key] = quantized
|
| 116 |
-
print(f"Quantized {key} to 1.58-bit precision.")
|
| 117 |
-
|
| 118 |
-
tensors = quantized_tensors
|
| 119 |
-
|
| 120 |
-
tensors = {k: v.cpu() for k, v in tensors.items()}
|
| 121 |
-
save_file(tensors, output_file)
|
| 122 |
-
print(f"BitNet safetensors file created: {output_file}")
|
| 123 |
-
else:
|
| 124 |
-
print("Safetensors file creation cancelled.")
|
| 125 |
-
sys.exit()
|
| 126 |
-
|
| 127 |
-
def quantize_model(model_file, output_file, device=device):
|
| 128 |
-
"""
|
| 129 |
-
Quantizes the given model to 1.58-bit precision.
|
| 130 |
-
"""
|
| 131 |
-
try:
|
| 132 |
-
# Load the model
|
| 133 |
-
tensors = load_file(model_file, device=device)
|
| 134 |
-
|
| 135 |
-
# Quantize each tensor
|
| 136 |
-
quantized_tensors = {}
|
| 137 |
-
for key, tensor in tensors.items():
|
| 138 |
-
# Normalize the tensor
|
| 139 |
-
max_val = torch.max(torch.abs(tensor))
|
| 140 |
-
normalized = tensor / max_val
|
| 141 |
-
|
| 142 |
-
# Quantize to {-1, 0, 1}
|
| 143 |
-
quantized = torch.where(normalized > 0.5, torch.ones_like(normalized),
|
| 144 |
-
torch.where(normalized < -0.5, -torch.ones_like(normalized), torch.zeros_like(normalized)))
|
| 145 |
-
|
| 146 |
-
quantized_tensors[key] = quantized
|
| 147 |
-
print(f"Quantized {key} to 1.58-bit precision.")
|
| 148 |
-
|
| 149 |
-
# Save the quantized model
|
| 150 |
-
save_file(quantized_tensors, output_file)
|
| 151 |
-
print(f"Quantized model saved to {output_file}")
|
| 152 |
-
|
| 153 |
-
except FileNotFoundError:
|
| 154 |
-
print(f"Error: Model file '{model_file}' not found.")
|
| 155 |
-
except Exception as e:
|
| 156 |
-
print(f"An error occurred during quantization: {e}")
|
| 157 |
-
|
| 158 |
-
def analyze_model_file(model_file):
|
| 159 |
-
"""
|
| 160 |
-
Analyzes a safetensors model file and prints/saves the configuration.
|
| 161 |
-
"""
|
| 162 |
-
try:
|
| 163 |
-
tensors = load_file(model_file, device="cpu")
|
| 164 |
-
config = {}
|
| 165 |
-
|
| 166 |
-
# Basic model architecture details
|
| 167 |
-
config["architectures"] = ["TestLakeForConditionalGeneration"]
|
| 168 |
-
config["model_type"] = "testlake"
|
| 169 |
-
config["torch_dtype"] = str(tensors["language_model.model.embed_tokens.weight"].dtype)
|
| 170 |
-
|
| 171 |
-
# Extract dimensions for language model
|
| 172 |
-
config["hidden_size"] = tensors["language_model.model.embed_tokens.weight"].shape[1]
|
| 173 |
-
config["num_hidden_layers"] = len([key for key in tensors if "language_model.model.layers." in key]) // 12
|
| 174 |
-
num_heads = tensors["language_model.model.layers.0.self_attn.q_proj.weight"].shape[0] // (config["hidden_size"] // 4)
|
| 175 |
-
config["num_attention_heads"] = num_heads
|
| 176 |
-
config["intermediate_size"] = tensors["language_model.model.layers.0.mlp.fc1.weight"].shape[1]
|
| 177 |
-
config["head_dim"] = config["hidden_size"] // config["num_attention_heads"]
|
| 178 |
-
|
| 179 |
-
# Extract vocabulary and vision details
|
| 180 |
-
config["vocab_size"] = tensors["language_model.model.embed_tokens.weight"].shape[0]
|
| 181 |
-
config["image_feature_dim"] = tensors["vision_encoder.patch_embedding.weight"].shape[0]
|
| 182 |
-
config["num_patches"] = ((224 // 16) ** 2)
|
| 183 |
-
config["vision_num_layers"] = len([key for key in tensors if "vision_encoder.transformer.layers." in key]) // 6
|
| 184 |
-
|
| 185 |
-
print(json.dumps(config, indent=2))
|
| 186 |
-
|
| 187 |
-
# Save to config.json
|
| 188 |
-
with open("config.json", "w") as f:
|
| 189 |
-
json.dump(config, f, indent=2)
|
| 190 |
-
|
| 191 |
-
print("Model analysis completed and saved to config.json")
|
| 192 |
-
|
| 193 |
-
except FileNotFoundError:
|
| 194 |
-
print(f"Error: Model file '{model_file}' not found.")
|
| 195 |
-
except Exception as e:
|
| 196 |
-
print(f"An error occurred during model analysis: {e}")
|
| 197 |
-
|
| 198 |
-
if __name__ == "__main__":
|
| 199 |
-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 200 |
-
|
| 201 |
-
# Set the desired data type for training (BFloat16)
|
| 202 |
-
dtype_input = input("Enter the desired data type (bfloat16, float16, float32, etc.): ").lower()
|
| 203 |
-
if dtype_input == "bfloat16":
|
| 204 |
-
dtype = torch.bfloat16
|
| 205 |
-
elif dtype_input == "float16":
|
| 206 |
-
dtype = torch.float16
|
| 207 |
-
elif dtype_input == "float32":
|
| 208 |
-
dtype = torch.float32
|
| 209 |
-
elif dtype_input == "float8":
|
| 210 |
-
dtype = torch.float8
|
| 211 |
-
else:
|
| 212 |
-
print("Invalid data type. Using bfloat16 as default.")
|
| 213 |
-
dtype = torch.bfloat16
|
| 214 |
-
|
| 215 |
-
# Create the initial model with BFloat16 precision and quantize it
|
| 216 |
-
create_bitnet_safetensors(dtype=dtype, device=device, quantize=True)
|
| 217 |
-
|
| 218 |
-
# Analyze the created model file
|
| 219 |
-
analyze_model_file("model_1.safetensors")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|