#!/usr/bin/env python3 # /// script # dependencies = ["torch", "transformers", "gguf", "huggingface_hub", "sentencepiece", "numpy", "tiktoken"] # /// """Convert sakthai-coder-browser to GGUF (F16).""" import os, sys, json, numpy as np from pathlib import Path import torch from transformers import AutoModelForCausalLM, AutoTokenizer from gguf import GGUFWriter, GGMLQuantizationType, MODEL_ARCH, get_tensor_name_map MODEL_ID = "Nanthasit/sakthai-coder-browser" OUTPUT_DIR = Path("gguf-output") OUTPUT_DIR.mkdir(exist_ok=True) GGUF_PATH = OUTPUT_DIR / "sakthai-coder-browser-f16.gguf" print("Loading model...", flush=True) model = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.float16, device_map=None, low_cpu_mem_usage=True) print("Loading tokenizer...", flush=True) tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) c = model.config n_blocks = c.num_hidden_layers print(f"Arch: Qwen2, layers={n_blocks}, heads={c.num_attention_heads}, " f"kv={c.num_key_value_heads}, embd={c.hidden_size}, ff={c.intermediate_size}", flush=True) gguf_writer = GGUFWriter(str(GGUF_PATH), "qwen2") gguf_writer.add_block_count(n_blocks) gguf_writer.add_context_length(c.max_position_embeddings) gguf_writer.add_embedding_length(c.hidden_size) gguf_writer.add_feed_forward_length(c.intermediate_size) gguf_writer.add_head_count(c.num_attention_heads) gguf_writer.add_head_count_kv(c.num_key_value_heads) gguf_writer.add_layer_norm_rms_eps(c.rms_norm_eps) gguf_writer.add_rope_dimension_count(c.hidden_size // c.num_attention_heads) gguf_writer.add_rope_freq_base(getattr(c, 'rope_theta', 10000.0)) tmap = get_tensor_name_map(MODEL_ARCH.QWEN2, n_blocks) # Remove .weight/.bias suffixes to match the GGUF mapping (keys are base names) def lookup_gguf_name(hf_name: str) -> str | None: # Try exact name first if hf_name in tmap.mapping: return tmap.mapping[hf_name][1] # Try without .weight or .bias suffix, then re-append .bias for bias tensors is_bias = hf_name.endswith('.bias') base = hf_name.removesuffix('.weight').removesuffix('.bias') if base in tmap.mapping: gguf_name = tmap.mapping[base][1] return gguf_name + '.bias' if is_bias else gguf_name return None state = model.state_dict() matched = 0 for hf_name, tensor in state.items(): gguf_name = lookup_gguf_name(hf_name) if gguf_name is None: print(f" SKIP: no mapping for {hf_name}", flush=True) continue data = tensor.to(torch.float32).numpy() gguf_writer.add_tensor(gguf_name, data) matched += 1 print(f"Matched {matched}/{len(state)} tensors", flush=True) # Tokenizer gguf_writer.add_tokenizer_model("gpt2") gguf_writer.add_tokenizer_pre("default") vocab = tokenizer.get_vocab() sorted_tokens = sorted(vocab.items(), key=lambda x: x[1]) tokens = [t for t, _ in sorted_tokens] scores = [0.0] * len(tokens) gguf_writer.add_token_list(tokens) gguf_writer.add_token_scores(scores) gguf_writer.add_bos_token_id(tokenizer.bos_token_id or 151643) gguf_writer.add_eos_token_id(tokenizer.eos_token_id or 151643) gguf_writer.add_unk_token_id(tokenizer.unk_token_id or 0) print("Writing GGUF...", flush=True) gguf_writer.write_header_to_file() gguf_writer.write_kv_data_to_file() gguf_writer.write_tensors_to_file() gguf_writer.close() size_gb = GGUF_PATH.stat().st_size / 1e9 print(f"Done: {GGUF_PATH} ({size_gb:.2f} GB)", flush=True)