humanizer-12b-mlx-8bit / humanizer_support.py
npario's picture cowWhySo's picture
Duplicate from cowWhySo/humanizer-12b-mlx-8bit
eb68581
Raw History Blame Contribute Delete
8.87 kB
"""Standard-library integrity and prompt helpers. SPDX-License-Identifier: Apache-2.0."""
from __future__ import annotations
import hashlib
import json
import math
import re
import struct
from pathlib import Path, PurePosixPath
SCHEMA = "humanizer-mlx-colab/v1"
PROMPT_FINGERPRINT = "cc51d66b4c593fbe"
REQUIRED_METADATA = {
"config.json", "generation_config.json", "tokenizer.json",
"tokenizer_config.json", "prompt_format.json", "LICENSE", "NOTICE", "README.md",
}
OPTIONAL_METADATA = {"model.safetensors.index.json", "special_tokens_map.json",
"tokenizer.model", "added_tokens.json"}
def read_json(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def write_json(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_name(path.name + ".writing")
temp.write_text(json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False,
allow_nan=False) + "\n", encoding="utf-8")
temp.replace(path)
def fingerprint(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(",", ":")).encode()).hexdigest()
def hashes(path):
path = Path(path)
size = path.stat().st_size
sha = hashlib.sha256()
git = hashlib.sha1(f"blob {size}\0".encode())
with path.open("rb") as stream:
for block in iter(lambda: stream.read(8 * 1024**2), b""):
sha.update(block)
git.update(block)
return {"bytes": size, "sha256": sha.hexdigest(), "git_blob_sha1": git.hexdigest()}
def safe_name(name):
p = PurePosixPath(name)
if not name or p.is_absolute() or "\\" in name or any(x in ("", ".", "..") for x in name.split("/")):
raise ValueError("Unsafe package path")
if any(x.startswith(".") or x == "__pycache__" for x in p.parts):
raise ValueError("Hidden/cache path is not publishable")
return name
def select_source_files(names):
"""Do not download the GGUF collection, old variants, adapters, or remote code."""
names = set(names)
missing = REQUIRED_METADATA - names
if missing:
raise ValueError(f"Source release is missing required files: {sorted(missing)}")
weights = sorted(n for n in names if re.fullmatch(r"model(?:-\d+-of-\d+)?\.safetensors", n))
if not weights:
raise ValueError("No root BF16 model safetensors found")
if "model.safetensors" in weights and len(weights) != 1:
raise ValueError("Ambiguous mixture of single-file and sharded source weights")
if len(weights) > 1 and "model.safetensors.index.json" not in names:
raise ValueError("Sharded source is missing its index")
return sorted(REQUIRED_METADATA | (OPTIONAL_METADATA & names) | set(weights))
def check_source_config(config):
if config.get("model_type") != "gemma4_unified":
raise ValueError("Expected the current Gemma 4 Unified 12B release; do not relabel another architecture")
text = config.get("text_config", {})
expected = {"hidden_size": 3840, "num_hidden_layers": 48,
"num_attention_heads": 16, "num_key_value_heads": 8,
"num_global_key_value_heads": 1, "attention_k_eq_v": True,
"hidden_size_per_layer_input": 0, "num_kv_shared_layers": 0}
for key, value in expected.items():
if text.get(key) != value:
raise ValueError(f"Source architecture changed: {key}; review before converting")
if text.get("layer_types") != ["full_attention" if (i + 1) % 6 == 0 else "sliding_attention" for i in range(48)]:
raise ValueError("Unexpected attention schedule")
if config.get("quantization") or config.get("quantization_config") or config.get("model_file") or config.get("auto_map"):
raise ValueError("Expected unquantized weights with no custom model code")
if config.get("dtype", text.get("dtype")) != "bfloat16":
raise ValueError("Expected a BF16 source checkpoint")
return text
def build_prompt(pf, draft):
if not isinstance(draft, str) or not isinstance(pf.get("instr"), str) or not isinstance(pf.get("sep"), str):
raise ValueError("Prompt inputs must be strings")
return pf["instr"] + "\n\n" + draft.strip() + pf["sep"]
def check_prompt(pf):
digest = hashlib.sha256(build_prompt(pf, "X").encode("utf-8")).hexdigest()
if digest[:16] != PROMPT_FINGERPRINT:
raise ValueError("Upstream prompt fingerprint changed; do not silently use a different instruction")
return digest
def safetensors_header(path):
"""Check every shape and byte span without loading tensor values."""
path = Path(path)
size = path.stat().st_size
with path.open("rb") as stream:
raw = stream.read(8)
if len(raw) != 8:
raise ValueError("Truncated safetensors file")
length = struct.unpack("<Q", raw)[0]
if not 2 <= length <= min(64 * 1024**2, size - 8):
raise ValueError("Invalid safetensors header length")
header = json.loads(stream.read(length))
data_bytes = size - 8 - length
widths = {"BOOL": 1, "U8": 1, "I8": 1, "F8_E4M3": 1, "F8_E5M2": 1,
"I16": 2, "U16": 2, "F16": 2, "BF16": 2, "I32": 4,
"U32": 4, "F32": 4, "F64": 8, "I64": 8, "U64": 8}
tensors = {k: v for k, v in header.items() if k != "__metadata__"}
spans = []
for name, t in tensors.items():
shape = t["shape"]
start, end = t["data_offsets"]
if not isinstance(shape, list) or any(type(x) is not int or x < 0 for x in shape):
raise ValueError(f"Invalid tensor shape: {name}")
if t["dtype"] not in widths or not 0 <= start <= end <= data_bytes:
raise ValueError(f"Invalid tensor dtype/span: {name}")
if end - start != math.prod(shape) * widths[t["dtype"]]:
raise ValueError(f"Incorrect tensor byte length: {name}")
if start != end:
spans.append((start, end))
cursor = 0
for start, end in sorted(spans):
if start != cursor:
raise ValueError("Tensor overlap or gap")
cursor = end
if cursor != data_bytes:
raise ValueError("Unaccounted safetensors bytes")
return tensors
def inspect_weights(directory):
directory = Path(directory)
files = sorted(directory.glob("model*.safetensors"))
if not files:
raise ValueError("No converted weights found")
tensors, locations = {}, {}
for path in files:
header = safetensors_header(path)
if set(tensors) & set(header):
raise ValueError("Duplicate tensor across shards")
tensors.update(header)
locations.update({k: path.name for k in header})
index = directory / "model.safetensors.index.json"
if index.exists():
obj = read_json(index)
if obj.get("weight_map") != locations:
raise ValueError("Shard index does not match actual tensor headers")
total = sum(t["data_offsets"][1] - t["data_offsets"][0] for t in tensors.values())
if obj.get("metadata", {}).get("total_size", total) != total:
raise ValueError("Index total_size is not the tensor-byte total")
elif len(files) != 1:
raise ValueError("Multiple weight shards without an index")
return {"tensor_count": len(tensors), "weight_bytes": sum(p.stat().st_size for p in files),
"files": [p.name for p in files], "tensors": tensors}
def package_records(directory, token=None, exclude=()):
directory = Path(directory)
records = {}
for p in sorted(directory.rglob("*")):
if p.is_symlink():
raise ValueError("Package symlinks are not allowed")
if not p.is_file():
continue
name = p.relative_to(directory).as_posix()
if name in exclude:
continue
safe_name(name)
if p.suffix != ".safetensors":
if p.stat().st_size > 64 * 1024**2:
raise ValueError(f"Oversized non-weight file: {name}")
content = p.read_bytes()
if token and token.encode() in content:
raise ValueError(f"Credential found in {name}; no upload")
if re.search(rb"\bhf_[A-Za-z0-9]{20,}\b|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----", content):
raise ValueError(f"Credential-like material in {name}; no upload")
records[name] = hashes(p)
return records
def verify_records(directory, records):
for name, expected in records.items():
safe_name(name)
if hashes(Path(directory) / name) != expected:
raise ValueError(f"Package hash mismatch: {name}")
def public_build_request(settings):
return {k: settings[k] for k in ("source_repo", "source_ref", "bits", "group_size", "mode", "dependencies", "helper_hashes")}