"""Shared config and helpers. Importable without MLX/Metal (no mlx imports here).""" import json import os from pathlib import Path HERE = Path(__file__).resolve().parent DATA = HERE / "data" RESULTS = HERE / "results" HF_HUB = Path(os.environ.get("HF_HUB_CACHE", Path.home() / ".cache/huggingface/hub")) # key -> (HF repo, contexts in tokens, label) MODELS = { "moe": ("mlx-community/Qwen3.6-35B-A3B-4bit", [8192, 16384, 32768], "Qwen3.6-35B-A3B-4bit (MoE)"), "dense": ("mlx-community/Qwen3.8-27B-4bit", [8192, 16384], "Qwen3.8-27B-4bit (dense)"), } # KV settings: name -> kv_bits (None = default fp16/bf16 cache) KV_SETTINGS = {"fp16": None, "kv8": 8, "kv4": 4} KV_GROUP_SIZE = 64 QUANTIZED_KV_START = 0 N_VARIANTS = 3 NEEDLE_DEPTHS = [0.10, 0.30, 0.50, 0.70, 0.90] BASE_SEED = 20261019 MAX_TOKENS = 128 DRIFT_TOKENS = 64 def snapshot_dir(repo: str) -> Path: """Local snapshot path of the revision that refs/main points to (no network).""" d = HF_HUB / ("models--" + repo.replace("/", "--")) rev = (d / "refs" / "main").read_text().strip() p = d / "snapshots" / rev if not (p / "config.json").exists(): raise FileNotFoundError(f"{repo} not in local HF cache at {p}") return p def revision(repo: str) -> str: return snapshot_dir(repo).name def text_config(repo: str) -> dict: cfg = json.loads((snapshot_dir(repo) / "config.json").read_text()) return cfg.get("text_config", cfg) def arch_summary(repo: str) -> dict: """Layer layout from config.json: which layers keep a growing KV cache.""" t = text_config(repo) n_layers = t["num_hidden_layers"] interval = t.get("full_attention_interval", 1) n_full = sum(1 for i in range(n_layers) if (i + 1) % interval == 0) return { "num_hidden_layers": n_layers, "full_attention_layers": n_full, "linear_attention_layers": n_layers - n_full, "num_key_value_heads": t["num_key_value_heads"], "num_attention_heads": t["num_attention_heads"], "head_dim": t["head_dim"], "num_experts": t.get("num_experts") or 0, "num_experts_per_tok": t.get("num_experts_per_tok") or 0, } def bytes_per_kv_element(kv_bits): """Storage per K or V element: fp16/bf16 = 2 bytes; quantized = bits/8 plus a bf16 scale and bf16 bias per group of KV_GROUP_SIZE elements.""" if kv_bits is None: return 2.0 return kv_bits / 8 + 2 * 2 / KV_GROUP_SIZE def kv_theoretical_bytes(repo: str, tokens: int, kv_bits, all_layers=False) -> float: """layers x kv_heads x head_dim x tokens x 2 (K and V) x bytes/element. all_layers=True gives the figure a naive estimate would use if every layer were full attention (these Qwen3.x models are hybrid).""" a = arch_summary(repo) layers = a["num_hidden_layers"] if all_layers else a["full_attention_layers"] return layers * a["num_key_value_heads"] * a["head_dim"] * tokens * 2 * bytes_per_kv_element(kv_bits)