"""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(" 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")}