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| 1 |
+
--- START OF FILE app.py ---
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import subprocess
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 8 |
+
from huggingface_hub import HfApi, whoami, ModelCard, list_models
|
| 9 |
+
from gradio_huggingfacehub_search import HuggingfaceHubSearch
|
| 10 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 11 |
+
from textwrap import dedent
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import hashlib
|
| 14 |
+
import torch.nn.utils.prune as prune
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
from torch.utils.checkpoint import checkpoint
|
| 17 |
+
import logging
|
| 18 |
+
from datetime import datetime
|
| 19 |
+
from typing import List, Dict
|
| 20 |
+
|
| 21 |
+
logging.basicConfig(level=logging.INFO)
|
| 22 |
+
|
| 23 |
+
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
| 24 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 25 |
+
SPACE_ID = "Ffftdtd5dtft/gguf-my-repo" # Replace with your space ID if different
|
| 26 |
+
|
| 27 |
+
def generate_importance_matrix(model_path, train_data_path):
|
| 28 |
+
os.chdir("llama.cpp")
|
| 29 |
+
if not os.path.isfile(f"../{model_path}"):
|
| 30 |
+
raise Exception(f"Model file not found: {model_path}")
|
| 31 |
+
imatrix_command = f"./llama-imatrix -m ../{model_path} -f {train_data_path} -ngl 99 --output-frequency 10"
|
| 32 |
+
process = subprocess.Popen(imatrix_command, shell=True)
|
| 33 |
+
try:
|
| 34 |
+
process.wait(timeout=3600)
|
| 35 |
+
except subprocess.TimeoutExpired:
|
| 36 |
+
process.kill()
|
| 37 |
+
os.chdir("..")
|
| 38 |
+
|
| 39 |
+
def split_upload_model(model_path, repo_id, oauth_token, split_max_tensors=256, split_max_size=None):
|
| 40 |
+
if oauth_token.token is None:
|
| 41 |
+
raise ValueError("You have to be logged in.")
|
| 42 |
+
split_cmd = f"llama.cpp/llama-gguf-split --split --split-max-tensors {split_max_tensors}"
|
| 43 |
+
if split_max_size:
|
| 44 |
+
split_cmd += f" --split-max-size {split_max_size}"
|
| 45 |
+
split_cmd += f" {model_path} {model_path.split('.')[0]}"
|
| 46 |
+
result = subprocess.run(split_cmd, shell=True, capture_output=True, text=True)
|
| 47 |
+
if result.returncode != 0:
|
| 48 |
+
raise Exception(f"Error splitting the model: {result.stderr}")
|
| 49 |
+
sharded_model_files = [f for f in os.listdir('.') if f.startswith(model_path.split('.')[0])]
|
| 50 |
+
if sharded_model_files:
|
| 51 |
+
api = HfApi(token=oauth_token.token)
|
| 52 |
+
for file in sharded_model_files:
|
| 53 |
+
file_path = os.path.join('.', file)
|
| 54 |
+
try:
|
| 55 |
+
api.upload_file(path_or_fileobj=file_path, path_in_repo=file, repo_id=repo_id)
|
| 56 |
+
except Exception as e:
|
| 57 |
+
raise Exception(f"Error uploading file {file_path}: {e}")
|
| 58 |
+
else:
|
| 59 |
+
raise Exception("No sharded files found.")
|
| 60 |
+
|
| 61 |
+
def quantize_to_q1_with_min(tensor, min_value=-1):
|
| 62 |
+
tensor = torch.sign(tensor)
|
| 63 |
+
tensor[tensor < min_value] = min_value
|
| 64 |
+
return tensor
|
| 65 |
+
|
| 66 |
+
def quantize_model_to_q1_with_min(model, min_value=-1):
|
| 67 |
+
for name, param in model.named_parameters():
|
| 68 |
+
if param.dtype in [torch.float32, torch.float16]:
|
| 69 |
+
with torch.no_grad():
|
| 70 |
+
param.copy_(quantize_to_q1_with_min(param.data, min_value))
|
| 71 |
+
|
| 72 |
+
def disable_unnecessary_components(model):
|
| 73 |
+
for name, module in model.named_modules():
|
| 74 |
+
if isinstance(module, torch.nn.Dropout):
|
| 75 |
+
module.p = 0.0
|
| 76 |
+
elif isinstance(module, torch.nn.BatchNorm1d):
|
| 77 |
+
module.eval()
|
| 78 |
+
|
| 79 |
+
def ultra_max_compress(model):
|
| 80 |
+
model = quantize_model_to_q1_with_min(model, min_value=-0.05)
|
| 81 |
+
disable_unnecessary_components(model)
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
for name, param in model.named_parameters():
|
| 84 |
+
if param.requires_grad:
|
| 85 |
+
param.requires_grad = False
|
| 86 |
+
param.data = torch.nn.functional.hardtanh(param.data, min_val=-1.0, max_val=1.0)
|
| 87 |
+
param.data = param.data.half()
|
| 88 |
+
model.eval()
|
| 89 |
+
for buffer_name, buffer in model.named_buffers():
|
| 90 |
+
if buffer.numel() == 0:
|
| 91 |
+
model._buffers.pop(buffer_name)
|
| 92 |
+
return model
|
| 93 |
+
|
| 94 |
+
def optimize_model_resources(model):
|
| 95 |
+
torch.set_grad_enabled(False)
|
| 96 |
+
model.eval()
|
| 97 |
+
for name, param in model.named_parameters():
|
| 98 |
+
param.requires_grad = False
|
| 99 |
+
if param.dtype == torch.float32:
|
| 100 |
+
param.data = param.data.half()
|
| 101 |
+
if hasattr(model, 'config'):
|
| 102 |
+
if hasattr(model.config, 'max_position_embeddings'):
|
| 103 |
+
model.config.max_position_embeddings = min(model.config.max_position_embeddings, 512)
|
| 104 |
+
if hasattr(model.config, 'hidden_size'):
|
| 105 |
+
model.config.hidden_size = min(model.config.hidden_size, 768)
|
| 106 |
+
return model
|
| 107 |
+
|
| 108 |
+
def aggressive_optimize(model, reduce_layers_factor=0.5):
|
| 109 |
+
if hasattr(model.config, 'num_attention_heads'):
|
| 110 |
+
model.config.num_attention_heads = int(model.config.num_attention_heads * reduce_layers_factor)
|
| 111 |
+
if hasattr(model.config, 'hidden_size'):
|
| 112 |
+
model.config.hidden_size = int(model.config.hidden_size * reduce_layers_factor)
|
| 113 |
+
return model
|
| 114 |
+
|
| 115 |
+
def apply_quantization(model, use_int8_inference):
|
| 116 |
+
if use_int8_inference:
|
| 117 |
+
quantized_model = torch.quantization.quantize_dynamic(
|
| 118 |
+
model, {torch.nn.Linear}, dtype=torch.qint8
|
| 119 |
+
)
|
| 120 |
+
return quantized_model
|
| 121 |
+
else:
|
| 122 |
+
return model
|
| 123 |
+
|
| 124 |
+
def reduce_layers(model, reduction_factor=0.5):
|
| 125 |
+
if hasattr(model, 'transformer') and hasattr(model.transformer, 'h'):
|
| 126 |
+
original_num_layers = len(model.transformer.h)
|
| 127 |
+
new_num_layers = int(original_num_layers * reduction_factor)
|
| 128 |
+
model.transformer.h = torch.nn.ModuleList(model.transformer.h[:new_num_layers])
|
| 129 |
+
return model
|
| 130 |
+
|
| 131 |
+
def use_smaller_embeddings(model, reduction_factor=0.75):
|
| 132 |
+
if hasattr(model, 'config'):
|
| 133 |
+
original_embedding_dim = model.config.hidden_size
|
| 134 |
+
new_embedding_dim = int(original_embedding_dim * reduction_factor)
|
| 135 |
+
model.config.hidden_size = new_embedding_dim
|
| 136 |
+
if hasattr(model, 'resize_token_embeddings'):
|
| 137 |
+
model.resize_token_embeddings(int(model.config.vocab_size * reduction_factor))
|
| 138 |
+
return model
|
| 139 |
+
|
| 140 |
+
def use_fp16_embeddings(model):
|
| 141 |
+
if hasattr(model, 'transformer') and hasattr(model.transformer, 'wte'):
|
| 142 |
+
model.transformer.wte = model.transformer.wte.half()
|
| 143 |
+
return model
|
| 144 |
+
|
| 145 |
+
def quantize_embeddings(model):
|
| 146 |
+
if hasattr(model, 'transformer') and hasattr(model.transformer, 'wte'):
|
| 147 |
+
model.transformer.wte = torch.quantization.quantize_dynamic(
|
| 148 |
+
model.transformer.wte, {torch.nn.Embedding}, dtype=torch.qint8
|
| 149 |
+
)
|
| 150 |
+
return model
|
| 151 |
+
|
| 152 |
+
def use_bnb_f16(model):
|
| 153 |
+
if torch.cuda.is_available() and torch.cuda.is_bf16_supported():
|
| 154 |
+
model = model.to(dtype=torch.bfloat16)
|
| 155 |
+
return model
|
| 156 |
+
|
| 157 |
+
def use_group_quantization(model):
|
| 158 |
+
for module in model.modules():
|
| 159 |
+
if isinstance(module, torch.nn.Linear):
|
| 160 |
+
torch.quantization.fuse_modules(module, ['weight'], inplace=True)
|
| 161 |
+
torch.quantization.quantize_dynamic(module, {torch.nn.Linear}, dtype=torch.qint8, inplace=True)
|
| 162 |
+
return model
|
| 163 |
+
|
| 164 |
+
def apply_layer_norm_trick(model):
|
| 165 |
+
for name, module in model.named_modules():
|
| 166 |
+
if isinstance(module, torch.nn.LayerNorm):
|
| 167 |
+
module.elementwise_affine = False
|
| 168 |
+
return model
|
| 169 |
+
|
| 170 |
+
def remove_padding(inputs, attention_mask):
|
| 171 |
+
last_non_padded = attention_mask.sum(dim=1) - 1
|
| 172 |
+
gathered_inputs = torch.gather(inputs, dim=1, index=last_non_padded.unsqueeze(1).unsqueeze(2).expand(-1, -1, inputs.size(2)))
|
| 173 |
+
return gathered_inputs
|
| 174 |
+
|
| 175 |
+
def use_selective_quantization(model):
|
| 176 |
+
for module in model.modules():
|
| 177 |
+
if isinstance(module, torch.nn.MultiheadAttention):
|
| 178 |
+
torch.quantization.quantize_dynamic(module, {torch.nn.Linear}, dtype=torch.qint8, inplace=True)
|
| 179 |
+
return model
|
| 180 |
+
|
| 181 |
+
def use_mixed_precision(model):
|
| 182 |
+
if hasattr(model, 'transformer') and hasattr(model.transformer, 'wte'):
|
| 183 |
+
model.transformer.wte = model.transformer.wte.half()
|
| 184 |
+
return model
|
| 185 |
+
|
| 186 |
+
def use_pruning_after_training(model, prune_amount=0.1):
|
| 187 |
+
from torch import nn as nn
|
| 188 |
+
for name, module in model.named_modules():
|
| 189 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 190 |
+
prune.l1_unstructured(module, name='weight', amount=prune_amount)
|
| 191 |
+
prune.remove(module, 'weight')
|
| 192 |
+
return model
|
| 193 |
+
|
| 194 |
+
def use_knowledge_distillation(model, teacher_model, temperature=2.0, alpha=0.5):
|
| 195 |
+
teacher_model.eval()
|
| 196 |
+
criterion = torch.nn.KLDivLoss(reduction='batchmean')
|
| 197 |
+
|
| 198 |
+
def distillation_loss(student_logits, teacher_logits):
|
| 199 |
+
student_probs = F.log_softmax(student_logits / temperature, dim=-1)
|
| 200 |
+
teacher_probs = F.softmax(teacher_logits / temperature, dim=-1)
|
| 201 |
+
return criterion(student_probs, teacher_probs) * (temperature**2)
|
| 202 |
+
|
| 203 |
+
def train_step(inputs, labels):
|
| 204 |
+
student_outputs = model(**inputs, labels=labels)
|
| 205 |
+
student_logits = student_outputs.logits
|
| 206 |
+
with torch.no_grad():
|
| 207 |
+
teacher_outputs = teacher_model(**inputs)
|
| 208 |
+
teacher_logits = teacher_outputs.logits
|
| 209 |
+
loss = alpha * student_outputs.loss + (1 - alpha) * distillation_loss(student_logits, teacher_logits)
|
| 210 |
+
return loss
|
| 211 |
+
|
| 212 |
+
return train_step
|
| 213 |
+
|
| 214 |
+
def use_weight_sharing(model):
|
| 215 |
+
if hasattr(model, 'transformer') and hasattr(model.transformer, 'h'):
|
| 216 |
+
if len(model.transformer.h) > 1:
|
| 217 |
+
model.transformer.h[-1].load_state_dict(model.transformer.h[0].state_dict())
|
| 218 |
+
return model
|
| 219 |
+
|
| 220 |
+
def use_low_rank_approximation(model, rank_factor=0.5):
|
| 221 |
+
for module in model.modules():
|
| 222 |
+
if isinstance(module, torch.nn.Linear):
|
| 223 |
+
original_weight = module.weight.data
|
| 224 |
+
U, S, V = torch.linalg.svd(original_weight)
|
| 225 |
+
rank = int(S.size(0) * rank_factor)
|
| 226 |
+
module.weight.data = U[:, :rank] @ torch.diag(S[:rank]) @ V[:rank, :]
|
| 227 |
+
return model
|
| 228 |
+
|
| 229 |
+
def use_hashing_trick(model, num_hashes=1024):
|
| 230 |
+
def hash_features(features):
|
| 231 |
+
features_bytes = features.cpu().numpy().tobytes()
|
| 232 |
+
hash_object = hashlib.sha256(features_bytes)
|
| 233 |
+
hash_value = hash_object.hexdigest()
|
| 234 |
+
hashed_features = int(hash_value, 16) % num_hashes
|
| 235 |
+
return torch.tensor(hashed_features, device=features.device)
|
| 236 |
+
|
| 237 |
+
original_forward = model.forward
|
| 238 |
+
|
| 239 |
+
def forward(*args, **kwargs):
|
| 240 |
+
inputs = args[0]
|
| 241 |
+
hashed_inputs = hash_features(inputs)
|
| 242 |
+
return original_forward(hashed_inputs, *args[1:], **kwargs)
|
| 243 |
+
|
| 244 |
+
def use_quantization_aware_training(model):
|
| 245 |
+
model.qconfig = torch.quantization.get_default_qat_qconfig('fbgemm')
|
| 246 |
+
torch.quantization.prepare_qat(model, inplace=True)
|
| 247 |
+
torch.quantization.convert(model, inplace=True)
|
| 248 |
+
return model
|
| 249 |
+
|
| 250 |
+
def use_gradient_checkpointing(model):
|
| 251 |
+
def custom_forward(*inputs):
|
| 252 |
+
return checkpoint(model, *inputs)
|
| 253 |
+
model.forward = custom_forward
|
| 254 |
+
return model
|
| 255 |
+
|
| 256 |
+
def use_channel_pruning(model, prune_amount=0.1):
|
| 257 |
+
from torch import nn as nn
|
| 258 |
+
for module in model.modules():
|
| 259 |
+
if isinstance(module, nn.Conv2d):
|
| 260 |
+
prune.ln_structured(module, name="weight", amount=prune_amount, n=2, dim=0)
|
| 261 |
+
prune.remove(module, 'weight')
|
| 262 |
+
return model
|
| 263 |
+
|
| 264 |
+
def use_sparse_tensors(model, sparsity_threshold=0.01):
|
| 265 |
+
for name, param in model.named_parameters():
|
| 266 |
+
if param.dim() >= 2 and param.is_floating_point():
|
| 267 |
+
sparse_param = param.to_sparse()
|
| 268 |
+
sparse_param._values()[sparse_param._values().abs() < sparsity_threshold] = 0
|
| 269 |
+
param.data = sparse_param.to_dense()
|
| 270 |
+
return model
|
| 271 |
+
|
| 272 |
+
def use_lora(model, r=8, lora_alpha=16, lora_dropout=0.05, target_modules=None):
|
| 273 |
+
from peft import LoraConfig, get_peft_model
|
| 274 |
+
config = LoraConfig(
|
| 275 |
+
r=r,
|
| 276 |
+
lora_alpha=lora_alpha,
|
| 277 |
+
lora_dropout=lora_dropout,
|
| 278 |
+
target_modules=target_modules if target_modules else ["q_proj", "v_proj"], # Example target modules
|
| 279 |
+
bias="none",
|
| 280 |
+
task_type="CAUSAL_LM"
|
| 281 |
+
)
|
| 282 |
+
model = get_peft_model(model, config)
|
| 283 |
+
return model
|
| 284 |
+
|
| 285 |
+
def use_adalora(model, target_r=8, init_r=12, tmask_init=0.01, beta1=0.85, beta2=0.99, loha=False, **kwargs):
|
| 286 |
+
from peft import AdaLoraConfig, get_peft_model
|
| 287 |
+
config = AdaLoraConfig(
|
| 288 |
+
target_r=target_r,
|
| 289 |
+
init_r=init_r,
|
| 290 |
+
tmask_init=tmask_init,
|
| 291 |
+
beta1=beta1,
|
| 292 |
+
beta2=beta2,
|
| 293 |
+
loha=loha,
|
| 294 |
+
task_type="CAUSAL_LM",
|
| 295 |
+
**kwargs
|
| 296 |
+
)
|
| 297 |
+
model = get_peft_model(model, config)
|
| 298 |
+
return model
|
| 299 |
+
|
| 300 |
+
def use_ia3(model, target_modules=None):
|
| 301 |
+
from peft import IA3Config, get_peft_model
|
| 302 |
+
config = IA3Config(
|
| 303 |
+
target_modules=target_modules if target_modules else ["k_proj", "v_proj", "down_proj"], # Example target modules
|
| 304 |
+
feedforward_modules=None,
|
| 305 |
+
task_type="CAUSAL_LM"
|
| 306 |
+
)
|
| 307 |
+
model = get_peft_model(model, config)
|
| 308 |
+
return model
|
| 309 |
+
|
| 310 |
+
def use_prompt_tuning(model, num_virtual_tokens=8, prompt_tuning_init_text="You are a helpful assistant."):
|
| 311 |
+
from peft import PromptTuningConfig, get_peft_model, TaskType
|
| 312 |
+
config = PromptTuningConfig(
|
| 313 |
+
task_type=TaskType.CAUSAL_LM,
|
| 314 |
+
num_virtual_tokens=num_virtual_tokens,
|
| 315 |
+
prompt_tuning_init_text=prompt_tuning_init_text,
|
| 316 |
+
tokenizer_name_or_path=model.config.tokenizer_class if hasattr(model.config, 'tokenizer_class') else None
|
| 317 |
+
)
|
| 318 |
+
model = get_peft_model(model, config)
|
| 319 |
+
return model
|
| 320 |
+
|
| 321 |
+
def apply_moe_layer_splitting(model, num_experts: int = 4, expert_capacity_factor: float = 2.0, moe_layer_freq: int = 2):
|
| 322 |
+
# Assumes a standard transformer block structure
|
| 323 |
+
if not hasattr(model, 'transformer') or not hasattr(model.transformer, 'h'):
|
| 324 |
+
logging.warning("Model does not have the expected transformer structure for MoE splitting.")
|
| 325 |
+
return model
|
| 326 |
+
|
| 327 |
+
from transformers.models.mixtral.modeling_mixtral import MixtralSparseMoeBlock, MixtralBLock
|
| 328 |
+
|
| 329 |
+
for i in range(len(model.transformer.h)):
|
| 330 |
+
if (i + 1) % moe_layer_freq == 0:
|
| 331 |
+
original_layer = model.transformer.h[i]
|
| 332 |
+
# Extract necessary components, handling different layer structures
|
| 333 |
+
if isinstance(original_layer, MixtralBLock):
|
| 334 |
+
config = original_layer.config
|
| 335 |
+
new_moe_block = MixtralSparseMoeBlock(config, num_experts=num_experts, capacity_factor=expert_capacity_factor)
|
| 336 |
+
# Copy relevant weights - this might need adjustments based on the model
|
| 337 |
+
new_moe_block.load_state_dict(original_layer.mlp.state_dict(), strict=False)
|
| 338 |
+
model.transformer.h[i] = new_moe_block
|
| 339 |
+
else:
|
| 340 |
+
logging.warning(f"Skipping layer {i} for MoE, not a recognized block type.")
|
| 341 |
+
return model
|
| 342 |
+
|
| 343 |
+
def process_model(model_id, q_method, use_imatrix, imatrix_q_method, private_repo, train_data_file, split_model, split_max_tensors, split_max_size,
|
| 344 |
+
oauth_token: gr.OAuthToken | None, apply_aggressive_optimization, apply_reduce_layers, apply_smaller_embeddings,
|
| 345 |
+
apply_weight_sharing, apply_low_rank_approx, use_lora_opt, use_adalora_opt, use_ia3_opt, use_prompt_tuning_opt,
|
| 346 |
+
apply_moe_splitting, num_experts_moe, expert_capacity_factor_moe, moe_layer_freq_moe,
|
| 347 |
+
is_automated=False):
|
| 348 |
+
if oauth_token.token is None and not is_automated:
|
| 349 |
+
raise ValueError("You must be logged in to use GGUF-my-repo")
|
| 350 |
+
elif oauth_token.token is None and is_automated:
|
| 351 |
+
logging.warning("Running in automated mode without user authentication.")
|
| 352 |
+
|
| 353 |
+
model_name = model_id.split('/')[-1]
|
| 354 |
+
fp16 = f"{model_name}.fp16.gguf"
|
| 355 |
+
|
| 356 |
+
try:
|
| 357 |
+
api = HfApi(token=oauth_token.token if oauth_token else None)
|
| 358 |
+
dl_pattern = ["*.safetensors", "*.bin", "*.pt", "*.onnx", "*.h5", "*.tflite", "*.ckpt", "*.pb", "*.tar", "*.xml", "*.caffemodel", "*.md", "*.json", "*.model"]
|
| 359 |
+
pattern = "*.safetensors" if any(file.path.endswith(".safetensors") for file in api.list_repo_tree(repo_id=model_id, recursive=True)) else "*.bin"
|
| 360 |
+
dl_pattern += pattern
|
| 361 |
+
api.snapshot_download(repo_id=model_id, local_dir=model_name, local_dir_use_symlinks=False, allow_patterns=dl_pattern)
|
| 362 |
+
|
| 363 |
+
config = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
|
| 364 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, config=config, torch_dtype=torch.float16, trust_remote_code=True)
|
| 365 |
+
|
| 366 |
+
if apply_aggressive_optimization:
|
| 367 |
+
model = aggressive_optimize(model)
|
| 368 |
+
if apply_reduce_layers:
|
| 369 |
+
model = reduce_layers(model)
|
| 370 |
+
if apply_smaller_embeddings:
|
| 371 |
+
model = use_smaller_embeddings(model)
|
| 372 |
+
if apply_weight_sharing:
|
| 373 |
+
model = use_weight_sharing(model)
|
| 374 |
+
if apply_low_rank_approx:
|
| 375 |
+
model = use_low_rank_approximation(model)
|
| 376 |
+
if use_lora_opt:
|
| 377 |
+
model = use_lora(model)
|
| 378 |
+
if use_adalora_opt:
|
| 379 |
+
model = use_adalora(model)
|
| 380 |
+
if use_ia3_opt:
|
| 381 |
+
model = use_ia3(model)
|
| 382 |
+
if use_prompt_tuning_opt:
|
| 383 |
+
model = use_prompt_tuning(model)
|
| 384 |
+
if apply_moe_splitting:
|
| 385 |
+
model = apply_moe_layer_splitting(model, num_experts_moe, expert_capacity_factor_moe, moe_layer_freq_moe)
|
| 386 |
+
|
| 387 |
+
optimized_model_path = f"{model_name}_optimized"
|
| 388 |
+
model.save_pretrained(optimized_model_path)
|
| 389 |
+
|
| 390 |
+
conversion_script = "convert_hf_to_gguf.py"
|
| 391 |
+
fp16_conversion = f"python llama.cpp/{conversion_script} {optimized_model_path} --outtype f16 --outfile {fp16}"
|
| 392 |
+
result = subprocess.run(fp16_conversion, shell=True, capture_output=True)
|
| 393 |
+
if result.returncode != 0:
|
| 394 |
+
raise Exception(f"Error converting to fp16: {result.stderr}")
|
| 395 |
+
|
| 396 |
+
imatrix_path = "llama.cpp/imatrix.dat"
|
| 397 |
+
if use_imatrix:
|
| 398 |
+
if train_data_file:
|
| 399 |
+
train_data_path = train_data_file.name
|
| 400 |
+
else:
|
| 401 |
+
train_data_path = "groups_merged.txt"
|
| 402 |
+
if not os.path.isfile(train_data_path):
|
| 403 |
+
raise Exception(f"Training data file not found: {train_data_path}")
|
| 404 |
+
generate_importance_matrix(fp16, train_data_path)
|
| 405 |
+
|
| 406 |
+
username = whoami(oauth_token.token)["name"] if oauth_token and oauth_token.token else "automated-gguf"
|
| 407 |
+
quantized_gguf_name = f"{model_name.lower()}-{imatrix_q_method.lower()}-imat.gguf" if use_imatrix else f"{model_name.lower()}-{q_method.lower()}.gguf"
|
| 408 |
+
quantized_gguf_path = quantized_gguf_name
|
| 409 |
+
|
| 410 |
+
if use_imatrix:
|
| 411 |
+
quantise_ggml = f"./llama.cpp/llama-quantize --imatrix {imatrix_path} {fp16} {quantized_gguf_path} {imatrix_q_method}"
|
| 412 |
+
else:
|
| 413 |
+
quantise_ggml = f"./llama.cpp/llama-quantize {fp16} {quantized_gguf_path} {q_method}"
|
| 414 |
+
|
| 415 |
+
result = subprocess.run(quantise_ggml, shell=True, capture_output=True)
|
| 416 |
+
if result.returncode != 0:
|
| 417 |
+
raise Exception(f"Error quantizing: {result.stderr}")
|
| 418 |
+
|
| 419 |
+
try:
|
| 420 |
+
subprocess.run(["llama.cpp/llama", "-m", quantized_gguf_path, "-p", "Test prompt"], check=True)
|
| 421 |
+
except Exception as e:
|
| 422 |
+
raise Exception(f"Model verification failed: {e}")
|
| 423 |
+
|
| 424 |
+
new_repo_id = f"{username}/{model_name}-{imatrix_q_method if use_imatrix else q_method}-GGUF"
|
| 425 |
+
new_repo_url = api.create_repo(repo_id=new_repo_id, exist_ok=True, private=private_repo)
|
| 426 |
+
|
| 427 |
+
try:
|
| 428 |
+
card = ModelCard.load(model_id, token=oauth_token.token if oauth_token else None)
|
| 429 |
+
except:
|
| 430 |
+
card = ModelCard("")
|
| 431 |
+
|
| 432 |
+
if card.data.tags is None:
|
| 433 |
+
card.data.tags = []
|
| 434 |
+
card.data.tags.append("llama-cpp")
|
| 435 |
+
card.data.tags.append("gguf-my-repo")
|
| 436 |
+
card.data.base_model = model_id
|
| 437 |
+
optimization_notes = []
|
| 438 |
+
if apply_aggressive_optimization:
|
| 439 |
+
optimization_notes.append("Aggressive optimization applied.")
|
| 440 |
+
if apply_reduce_layers:
|
| 441 |
+
optimization_notes.append("Number of layers reduced.")
|
| 442 |
+
if apply_smaller_embeddings:
|
| 443 |
+
optimization_notes.append("Embedding size reduced.")
|
| 444 |
+
if apply_weight_sharing:
|
| 445 |
+
optimization_notes.append("Weight sharing applied.")
|
| 446 |
+
if apply_low_rank_approx:
|
| 447 |
+
optimization_notes.append(f"Low-rank approximation applied.")
|
| 448 |
+
if use_lora_opt:
|
| 449 |
+
optimization_notes.append("LoRA applied.")
|
| 450 |
+
if use_adalora_opt:
|
| 451 |
+
optimization_notes.append("AdaLoRA applied.")
|
| 452 |
+
if use_ia3_opt:
|
| 453 |
+
optimization_notes.append("IA3 applied.")
|
| 454 |
+
if use_prompt_tuning_opt:
|
| 455 |
+
optimization_notes.append("Prompt Tuning applied.")
|
| 456 |
+
if apply_moe_splitting:
|
| 457 |
+
optimization_notes.append(f"Mixture-of-Experts (MoE) layer splitting applied with {num_experts_moe} experts every {moe_layer_freq_moe} layers.")
|
| 458 |
+
|
| 459 |
+
card.text = dedent(
|
| 460 |
+
f"""
|
| 461 |
+
# {new_repo_id}
|
| 462 |
+
This model was converted to GGUF format from [`{model_id}`](https://huggingface.co/{model_id}) using llama.cpp via the ggml.ai's [GGUF-my-repo](https://huggingface.co/spaces/ggml-org/gguf-my-repo) space.
|
| 463 |
+
Refer to the [original model card](https://huggingface.co/{model_id}) for more details on the model.
|
| 464 |
+
|
| 465 |
+
{' '.join(optimization_notes)}
|
| 466 |
+
|
| 467 |
+
## Use with llama.cpp
|
| 468 |
+
Install llama.cpp through brew (works on Mac and Linux)
|
| 469 |
+
|
| 470 |
+
```bash
|
| 471 |
+
brew install llama.cpp
|
| 472 |
+
|
| 473 |
+
```
|
| 474 |
+
Invoke the llama.cpp server or the CLI.
|
| 475 |
+
|
| 476 |
+
### CLI:
|
| 477 |
+
```bash
|
| 478 |
+
llama-cli --hf-repo {new_repo_id} --hf-file {quantized_gguf_name} -p "The meaning to life and the universe is"
|
| 479 |
+
```
|
| 480 |
+
|
| 481 |
+
### Server:
|
| 482 |
+
```bash
|
| 483 |
+
llama-server --hf-repo {new_repo_id} --hf-file {quantized_gguf_name} -c 2048
|
| 484 |
+
```
|
| 485 |
+
|
| 486 |
+
Note: You can also use this checkpoint directly through the [usage steps](https://github.com/ggerganov/llama.cpp?tab=readme-ov-file#usage) listed in the Llama.cpp repo as well.
|
| 487 |
+
Step 1: Clone llama.cpp from GitHub.
|
| 488 |
+
```
|
| 489 |
+
git clone https://github.com/ggerganov/llama.cpp
|
| 490 |
+
```
|
| 491 |
+
Step 2: Move into the llama.cpp folder and build it with `LLAMA_CURL=1` flag along with other hardware-specific flags (for ex: LLAMA_CUDA=1 for Nvidia GPUs on Linux).
|
| 492 |
+
```
|
| 493 |
+
cd llama.cpp && LLAMA_CURL=1 make
|
| 494 |
+
```
|
| 495 |
+
Step 3: Run inference through the main binary.
|
| 496 |
+
```
|
| 497 |
+
./llama-cli --hf-repo {new_repo_id} --hf-file {quantized_gguf_name} -p "The meaning to life and the universe is"
|
| 498 |
+
```
|
| 499 |
+
or
|
| 500 |
+
```
|
| 501 |
+
./llama-server --hf-repo {new_repo_id} --hf-file {quantized_gguf_name} -c 2048
|
| 502 |
+
```
|
| 503 |
+
"""
|
| 504 |
+
)
|
| 505 |
+
card.save(f"README.md")
|
| 506 |
+
|
| 507 |
+
if split_model:
|
| 508 |
+
split_upload_model(quantized_gguf_path, new_repo_id, oauth_token, split_max_tensors, split_max_size)
|
| 509 |
+
else:
|
| 510 |
+
try:
|
| 511 |
+
api.upload_file(path_or_fileobj=quantized_gguf_path, path_in_repo=quantized_gguf_name, repo_id=new_repo_id)
|
| 512 |
+
except Exception as e:
|
| 513 |
+
raise Exception(f"Error uploading quantized model: {e}")
|
| 514 |
+
|
| 515 |
+
if os.path.isfile(imatrix_path):
|
| 516 |
+
try:
|
| 517 |
+
api.upload_file(path_or_fileobj=imatrix_path, path_in_repo="imatrix.dat", repo_id=new_repo_id)
|
| 518 |
+
except Exception as e:
|
| 519 |
+
raise Exception(f"Error uploading imatrix.dat: {e}")
|
| 520 |
+
|
| 521 |
+
api.upload_file(path_or_fileobj=f"README.md", path_in_repo=f"README.md", repo_id=new_repo_id)
|
| 522 |
+
|
| 523 |
+
log_message = f"Successfully processed and uploaded GGUF model for {model_id} to {new_repo_url}"
|
| 524 |
+
logging.info(log_message)
|
| 525 |
+
return (f'Find your repo <a href=\'{new_repo_url}\' target="_blank" style="text-decoration:underline">here</a>', "llama.png")
|
| 526 |
+
except Exception as e:
|
| 527 |
+
error_message = f"Error processing model {model_id}: {e}"
|
| 528 |
+
logging.error(error_message)
|
| 529 |
+
return (f"Error: {e}", "error.png")
|
| 530 |
+
finally:
|
| 531 |
+
shutil.rmtree(model_name, ignore_errors=True)
|
| 532 |
+
shutil.rmtree(optimized_model_path, ignore_errors=True)
|
| 533 |
+
|
| 534 |
+
def select_models_for_automation():
|
| 535 |
+
# Example logic: Select top N most downloaded models
|
| 536 |
+
models = list_models(sort="downloads", direction=-1, limit=5)
|
| 537 |
+
return [model.modelId for model in models]
|
| 538 |
+
|
| 539 |
+
def get_automation_parameters():
|
| 540 |
+
# Example logic: Define default parameters or load from a config
|
| 541 |
+
return {
|
| 542 |
+
"q_method": "Q4_K_M",
|
| 543 |
+
"use_imatrix": False,
|
| 544 |
+
"imatrix_q_method": "IQ4_NL",
|
| 545 |
+
"private_repo": True,
|
| 546 |
+
"train_data_file": None,
|
| 547 |
+
"split_model": False,
|
| 548 |
+
"split_max_tensors": 256,
|
| 549 |
+
"split_max_size": None,
|
| 550 |
+
"apply_aggressive_optimization": True,
|
| 551 |
+
"apply_reduce_layers": True,
|
| 552 |
+
"apply_smaller_embeddings": True,
|
| 553 |
+
"apply_weight_sharing": False,
|
| 554 |
+
"apply_low_rank_approx": False,
|
| 555 |
+
"use_lora_opt": False,
|
| 556 |
+
"use_adalora_opt": False,
|
| 557 |
+
"use_ia3_opt": False,
|
| 558 |
+
"use_prompt_tuning_opt": False,
|
| 559 |
+
"apply_moe_splitting": False,
|
| 560 |
+
"num_experts_moe": 4,
|
| 561 |
+
"expert_capacity_factor_moe": 2.0,
|
| 562 |
+
"moe_layer_freq_moe": 2,
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
def automate_gguf_creation():
|
| 566 |
+
logging.info(f"Starting automated GGUF creation at {datetime.now()}")
|
| 567 |
+
api = HfApi(token=HF_TOKEN)
|
| 568 |
+
try:
|
| 569 |
+
whoami(token=HF_TOKEN) # Check if the token is valid
|
| 570 |
+
except Exception as e:
|
| 571 |
+
logging.error(f"Error with Hugging Face token: {e}")
|
| 572 |
+
return
|
| 573 |
+
|
| 574 |
+
models_to_process = select_models_for_automation()
|
| 575 |
+
automation_params = get_automation_parameters()
|
| 576 |
+
|
| 577 |
+
for model_id in models_to_process:
|
| 578 |
+
logging.info(f"Attempting to process model: {model_id}")
|
| 579 |
+
try:
|
| 580 |
+
process_model(model_id=model_id, oauth_token=None, is_automated=True, **automation_params)
|
| 581 |
+
except Exception as e:
|
| 582 |
+
logging.error(f"Failed to process model {model_id} automatically: {e}")
|
| 583 |
+
|
| 584 |
+
css="""/* Custom CSS to allow scrolling */ .gradio-container {overflow-y: auto;}"""
|
| 585 |
+
|
| 586 |
+
with gr.Blocks(css=css) as demo:
|
| 587 |
+
gr.Markdown("You must be logged in to use GGUF-my-repo for manual processing. Automation runs in the background.")
|
| 588 |
+
oauth_token = gr.OAuthButton(min_width=250)
|
| 589 |
+
model_id = HuggingfaceHubSearch(label="Hub Model ID", placeholder="Search for model id on Huggingface", search_type="model")
|
| 590 |
+
|
| 591 |
+
q_method = gr.Dropdown(["Q2_K", "Q3_K_S", "Q3_K_M", "Q3_K_L", "Q4_0", "Q4_K_S", "Q4_K_M", "Q5_0", "Q5_K_S", "Q5_K_M", "Q6_K", "Q8_0"],
|
| 592 |
+
label="Quantization Method", info="GGML quantization type", value="Q4_K_M", filterable=False, visible=True)
|
| 593 |
+
imatrix_q_method = gr.Dropdown(["IQ1", "IQ1_S", "IQ1_XXS", "IQ2_S", "IQ2_XXS", "IQ3_M", "IQ3_XXS", "Q4_K_M", "Q4_K_S", "IQ4_NL", "IQ4_XS", "Q5_K_M", "Q5_K_S"],
|
| 594 |
+
label="Imatrix Quantization Method", info="GGML imatrix quants type", value="IQ4_NL", filterable=False, visible=False)
|
| 595 |
+
use_imatrix = gr.Checkbox(value=False, label="Use Imatrix Quantization", info="Use importance matrix for quantization.")
|
| 596 |
+
train_data_file = gr.File(label="Training Data File", file_types=["txt"], visible=False)
|
| 597 |
+
|
| 598 |
+
size_reduction_accordion = gr.Accordion("Additional Size Reduction Techniques", open=False)
|
| 599 |
+
with size_reduction_accordion:
|
| 600 |
+
apply_aggressive_optimization = gr.Checkbox(value=True, label="Apply Aggressive Optimization", info="Reduces attention heads and hidden size.")
|
| 601 |
+
apply_reduce_layers = gr.Checkbox(value=True, label="Reduce Layers", info="Reduces the number of layers in the model.")
|
| 602 |
+
apply_smaller_embeddings = gr.Checkbox(value=True, label="Use Smaller Embeddings", info="Reduces the size of the embedding layer.")
|
| 603 |
+
apply_weight_sharing = gr.Checkbox(value=False, label="Apply Weight Sharing", info="Shares weights across layers to reduce parameters.")
|
| 604 |
+
apply_low_rank_approx = gr.Checkbox(value=False, label="Apply Low-Rank Approximation", info="Approximates weight matrices with lower rank.")
|
| 605 |
+
use_lora_opt = gr.Checkbox(value=False, label="Use LoRA", info="Applies Low-Rank Adaptation.")
|
| 606 |
+
use_adalora_opt = gr.Checkbox(value=False, label="Use AdaLoRA", info="Applies Adaptive Low-Rank Adaptation.")
|
| 607 |
+
use_ia3_opt = gr.Checkbox(value=False, label="Use IA3", info="Applies Infused Adapter by Inhibiting and Amplifying Inner Activations.")
|
| 608 |
+
use_prompt_tuning_opt = gr.Checkbox(value=False, label="Use Prompt Tuning", info="Adds trainable virtual tokens to the input embeddings.")
|
| 609 |
+
apply_moe_splitting = gr.Checkbox(value=False, label="Apply MoE Layer Splitting", info="Splits layers into a mixture-of-experts (MoE).", visible=False)
|
| 610 |
+
with gr.Row(visible=False) as moe_params:
|
| 611 |
+
num_experts_moe = gr.Number(value=4, label="Number of Experts", info="Number of experts to use in the MoE layers.", precision=0)
|
| 612 |
+
expert_capacity_factor_moe = gr.Number(value=2.0, label="Expert Capacity Factor", info="Capacity factor for each expert in the MoE layer.", precision=1)
|
| 613 |
+
moe_layer_freq_moe = gr.Number(value=2, label="MoE Layer Frequency", info="Apply MoE every N layers", precision=0)
|
| 614 |
+
|
| 615 |
+
private_repo = gr.Checkbox(value=True, label="Private Repo", info="Create a private repo under your username.")
|
| 616 |
+
split_model = gr.Checkbox(value=False, label="Split Model", info="Shard the model using gguf-split.")
|
| 617 |
+
split_max_tensors = gr.Number(value=256, label="Max Tensors per File", info="Maximum number of tensors per file when splitting model.", visible=False)
|
| 618 |
+
split_max_size = gr.Textbox(label="Max File Size", info="Maximum file size when splitting model (--split-max-size). May leave empty to use the default.", visible=False)
|
| 619 |
+
|
| 620 |
+
use_imatrix.change(fn=lambda use_imatrix: gr.update(visible=not use_imatrix), inputs=use_imatrix, outputs=q_method)
|
| 621 |
+
use_imatrix.change(fn=lambda use_imatrix: gr.update(visible=use_imatrix), inputs=use_imatrix, outputs=imatrix_q_method)
|
| 622 |
+
use_imatrix.change(fn=lambda use_imatrix: gr.update(visible=use_imatrix), inputs=use_imatrix, outputs=train_data_file)
|
| 623 |
+
split_model.change(fn=lambda split_model: gr.update(visible=split_model), inputs=split_model, outputs=split_max_tensors)
|
| 624 |
+
split_model.change(fn=lambda split_model: gr.update(visible=split_model), inputs=split_model, outputs=split_max_size)
|
| 625 |
+
apply_moe_splitting.change(fn=lambda apply_moe_splitting: gr.update(visible=apply_moe_splitting), inputs=apply_moe_splitting, outputs=moe_params)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
iface = gr.Interface(
|
| 629 |
+
fn=process_model,
|
| 630 |
+
inputs=[
|
| 631 |
+
model_id,
|
| 632 |
+
q_method,
|
| 633 |
+
use_imatrix,
|
| 634 |
+
imatrix_q_method,
|
| 635 |
+
private_repo,
|
| 636 |
+
train_data_file,
|
| 637 |
+
split_model,
|
| 638 |
+
split_max_tensors,
|
| 639 |
+
split_max_size,
|
| 640 |
+
oauth_token,
|
| 641 |
+
apply_aggressive_optimization,
|
| 642 |
+
apply_reduce_layers,
|
| 643 |
+
apply_smaller_embeddings,
|
| 644 |
+
apply_weight_sharing,
|
| 645 |
+
apply_low_rank_approx,
|
| 646 |
+
use_lora_opt,
|
| 647 |
+
use_adalora_opt,
|
| 648 |
+
use_ia3_opt,
|
| 649 |
+
use_prompt_tuning_opt,
|
| 650 |
+
apply_moe_splitting,
|
| 651 |
+
num_experts_moe,
|
| 652 |
+
expert_capacity_factor_moe,
|
| 653 |
+
moe_layer_freq_moe,
|
| 654 |
+
],
|
| 655 |
+
outputs=[
|
| 656 |
+
gr.Markdown(label="output"),
|
| 657 |
+
gr.Image(show_label=False),
|
| 658 |
+
],
|
| 659 |
+
title="Create your own GGUF Quants, blazingly fast ⚡!",
|
| 660 |
+
description="The space takes an HF repo as an input, applies size reduction techniques, quantizes it and creates a Public or Private repo containing the selected quant under your HF user namespace. It also automates the creation of GGUF quants for popular models in the background.",
|
| 661 |
+
api_name=False
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
def restart_space():
|
| 665 |
+
HfApi().restart_space(repo_id=SPACE_ID, token=HF_TOKEN, factory_reboot=True)
|
| 666 |
+
|
| 667 |
+
scheduler = BackgroundScheduler()
|
| 668 |
+
scheduler.add_job(restart_space, "interval", seconds=21600)
|
| 669 |
+
scheduler.add_job(automate_gguf_creation, "interval", hours=6) # Run automation every 6 hours
|
| 670 |
+
scheduler.start()
|
| 671 |
+
|
| 672 |
+
demo.queue(default_concurrency_limit=1, max_size=5).launch(debug=True, show_api=False)
|