"""Weight-space surgeon. Point at a Hub model. Point at other models or datasets as water. Discover a direction from that water, cut it into the residual out-projection with rank-1 column ablation, test the cut, then create the named model and an optional chat Space under the token's account. No optimizer. No backward pass. A write token is the only credential. """ from __future__ import annotations import hashlib import io import json import os import re import struct import tempfile from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Tuple from urllib.parse import urlparse import numpy as np import requests from modelifier.engine import audit, rank1_column_ablation, resolve_tensor NEUTRAL = [ "The capital of France is Paris.", "Water freezes at zero degrees Celsius.", "A triangle has three sides.", "Monday comes before Tuesday.", "The sun rises in the east.", "Two plus two equals four.", "Birds have feathers.", "A year has twelve months.", ] EMBED_CANDIDATES = [ "model.embed_tokens.weight", "model.language_model.embed_tokens.weight", "transformer.wte.weight", "model.decoder.embed_tokens.weight", "gpt_neox.embed_in.weight", "embeddings.word_embeddings.weight", ] TENSOR_CAP = 512 * 1024 * 1024 SHARD_CAP = 1500 * 1024 * 1024 def parse_repo(value: str) -> Tuple[str, str]: """Return (repo_id, kind) from a Hub URL or `org/name`.""" raw = (value or "").strip().strip("/") if not raw: raise ValueError("Empty model or dataset pointer.") kind = "model" if "huggingface.co" in raw or raw.startswith("http"): parsed = urlparse(raw if "://" in raw else f"https://{raw}") parts = [p for p in parsed.path.split("/") if p] if not parts: raise ValueError(f"Could not read a repo from {value!r}.") if parts[0] in {"datasets", "spaces"}: kind = "dataset" if parts[0] == "datasets" else "space" parts = parts[1:] if len(parts) < 2: raise ValueError(f"Need org/name, got {value!r}.") return f"{parts[0]}/{parts[1]}", kind if raw.count("/") != 1: raise ValueError(f"Use org/name or a huggingface.co URL, not {value!r}.") return raw, kind def _token(explicit: Optional[str]) -> Optional[str]: token = (explicit or os.environ.get("HF_TOKEN") or "").strip() return token or None def _headers(token: Optional[str]) -> Dict[str, str]: headers = {"User-Agent": "modelifier-surgeon"} if token: headers["Authorization"] = f"Bearer {token}" return headers def _api(token: Optional[str]): from huggingface_hub import HfApi return HfApi(token=_token(token)) def inspect_model(pointer: str, token: Optional[str] = None) -> Dict[str, Any]: """Index and config only. No weights.""" repo_id, kind = parse_repo(pointer) if kind == "dataset": raise ValueError(f"{repo_id} is a dataset. The source has to be a model.") api = _api(token) info = api.model_info(repo_id) files = [s.rfilename for s in info.siblings] config = _read_json(repo_id, "config.json", token) or {} hidden = _hidden_size(config) layers = _layer_count(config) index = None keys: List[str] = [] weight_map: Dict[str, str] = {} if "model.safetensors.index.json" in files: index = _read_json(repo_id, "model.safetensors.index.json", token) or {} weight_map = index.get("weight_map") or {} keys = list(weight_map) elif "model.safetensors" in files: keys = _header_keys(repo_id, "model.safetensors", token) weight_map = {k: "model.safetensors" for k in keys} embed = next((name for name in EMBED_CANDIDATES if name in keys), None) resolved = [] if layers: sample_layers = _default_layers(layers) for layer in sample_layers: try: name = resolve_tensor(keys, layer, "residual_out_proj") resolved.append({"layer": layer, "tensor": name, "shard": weight_map.get(name)}) except (KeyError, ValueError): resolved.append({"layer": layer, "tensor": None, "shard": None}) return { "repo_id": repo_id, "private": bool(getattr(info, "private", False)), "pipeline": getattr(info, "pipeline_tag", None), "files": len(files), "safetensors": bool(keys), "hidden_size": hidden, "layers": layers, "architecture": (config.get("architectures") or [None])[0], "embedding": embed, "resolved": resolved, "has_tokenizer": any(f in files for f in ("tokenizer.json", "tokenizer.model", "vocab.json")), "weights_downloaded": False, } def _hidden_size(config: Dict[str, Any]) -> Optional[int]: for key in ("hidden_size", "n_embd", "d_model"): if isinstance(config.get(key), int): return int(config[key]) text = config.get("text_config") or {} if isinstance(text, dict) and isinstance(text.get("hidden_size"), int): return int(text["hidden_size"]) return None def _layer_count(config: Dict[str, Any]) -> Optional[int]: for key in ("num_hidden_layers", "n_layer", "num_layers"): if isinstance(config.get(key), int): return int(config[key]) text = config.get("text_config") or {} if isinstance(text, dict) and isinstance(text.get("num_hidden_layers"), int): return int(text["num_hidden_layers"]) return None def _default_layers(n: int) -> List[int]: if n <= 2: return list(range(n)) mid = n // 2 return sorted({max(0, mid - 1), min(n - 1, mid + 1)}) def _read_json(repo_id: str, filename: str, token: Optional[str]) -> Optional[Dict[str, Any]]: from huggingface_hub import hf_hub_download try: path = hf_hub_download(repo_id=repo_id, filename=filename, token=_token(token)) except Exception: return None try: return json.loads(Path(path).read_text(encoding="utf-8")) except Exception: return None def _header_keys(repo_id: str, filename: str, token: Optional[str]) -> List[str]: header = _safetensors_header(repo_id, filename, token) return [k for k in header if k != "__metadata__"] def _safetensors_header(repo_id: str, filename: str, token: Optional[str]) -> Dict[str, Any]: from huggingface_hub import hf_hub_url url = hf_hub_url(repo_id=repo_id, filename=filename) headers = _headers(_token(token)) first = requests.get(url, headers={**headers, "Range": "bytes=0-7"}, timeout=60) first.raise_for_status() blob = first.content if len(blob) < 8: raise ValueError(f"Could not read the safetensors header of {filename}.") # A 200 without range still starts with the length. (length,) = struct.unpack(" 64 * 1024 * 1024: raise ValueError(f"Implausible safetensors header in {filename}.") second = requests.get( url, headers={**headers, "Range": f"bytes=8-{8 + length - 1}"}, timeout=60 ) second.raise_for_status() raw = second.content if raw.startswith(blob[:8]) and len(raw) >= 8 + length: raw = raw[8 : 8 + length] return json.loads(raw[:length].decode("utf-8")) def collect_water(pointers: Sequence[str], note: str, token: Optional[str]) -> List[str]: texts: List[str] = [] if note.strip(): texts.append(note.strip()) for pointer in pointers: pointer = pointer.strip() if not pointer: continue repo_id, kind = parse_repo(pointer) if kind == "dataset" or _looks_like_dataset(repo_id, token): texts.extend(_dataset_rows(repo_id, token)) else: texts.extend(_model_card_texts(repo_id, token)) cleaned = [] seen = set() for text in texts: text = re.sub(r"\s+", " ", text).strip() if len(text) < 12 or text in seen: continue seen.add(text) cleaned.append(text[:2000]) if len(cleaned) >= 24: break if not cleaned: raise ValueError("No water. Point at a dataset or another model, or write what you want in.") return cleaned def _looks_like_dataset(repo_id: str, token: Optional[str]) -> bool: try: _api(token).dataset_info(repo_id) return True except Exception: return False def _dataset_rows(repo_id: str, token: Optional[str]) -> List[str]: splits = requests.get( "https://datasets-server.huggingface.co/splits", params={"dataset": repo_id}, headers=_headers(_token(token)), timeout=30, ) config, split = "default", "train" if splits.ok: body = splits.json() rows = body.get("splits") or [] if rows: config = rows[0].get("config") or config split = rows[0].get("split") or split got = requests.get( "https://datasets-server.huggingface.co/rows", params={"dataset": repo_id, "config": config, "split": split, "offset": 0, "length": 12}, headers=_headers(_token(token)), timeout=45, ) texts: List[str] = [] if got.ok: for row in (got.json().get("rows") or []): cell = row.get("row") or {} texts.append(_row_to_text(cell)) if texts: return texts card = _read_text(repo_id, "README.md", token, repo_type="dataset") return _paragraphs(card) def _row_to_text(row: Dict[str, Any]) -> str: for key in ("text", "content", "sentence", "prompt", "question", "instruction", "input"): value = row.get(key) if isinstance(value, str) and value.strip(): return value parts = [] for key, value in row.items(): if isinstance(value, str) and value.strip(): parts.append(f"{key}: {value.strip()}") if len(parts) >= 3: break return "\n".join(parts) def _model_card_texts(repo_id: str, token: Optional[str]) -> List[str]: card = _read_text(repo_id, "README.md", token) or "" return _paragraphs(card) or [f"Behavior associated with the model {repo_id}."] def _read_text(repo_id: str, filename: str, token: Optional[str], repo_type: Optional[str] = None) -> Optional[str]: from huggingface_hub import hf_hub_download try: path = hf_hub_download( repo_id=repo_id, filename=filename, token=_token(token), repo_type=repo_type ) except Exception: return None return Path(path).read_text(encoding="utf-8", errors="replace") def _paragraphs(card: Optional[str]) -> List[str]: if not card: return [] body = re.sub(r"^---.*?---", "", card, count=1, flags=re.S) chunks = re.split(r"\n\s*\n", body) out = [] for chunk in chunks: text = re.sub(r"[#>*`\-]+", " ", chunk) text = re.sub(r"\s+", " ", text).strip() if len(text) >= 40: out.append(text) if len(out) >= 8: break return out def test_edit( pointer: str, water: Sequence[str], note: str = "", layers: Optional[Sequence[int]] = None, alpha: float = 1.0, top_k: int = 64, token: Optional[str] = None, ) -> Dict[str, Any]: """Pull the embedding and the target tensors, edit in memory, return the audit. Writes nothing.""" report = inspect_model(pointer, token) repo_id = report["repo_id"] keys, weight_map = _keys_and_map(repo_id, token) texts = collect_water(water, note, token) embed_name = report["embedding"] or next((n for n in EMBED_CANDIDATES if n in keys), None) if not embed_name: raise ValueError("No embedding tensor in that repo. Need safetensors with an embed matrix.") embed, embed_name = _load_named(repo_id, embed_name, weight_map, token) tokenizer = _load_tokenizer(repo_id, token) direction = _direction_from_water(embed, tokenizer, texts) chosen = list(layers) if layers else _default_layers(report["layers"] or 1) audits = [] for layer in chosen: name = resolve_tensor(keys, int(layer), "residual_out_proj") weight, _ = _load_named(repo_id, name, weight_map, token) edited, cols = rank1_column_ablation(weight, direction, top_k=int(top_k), alpha=float(alpha)) stats = audit(weight, edited) u = direction.reshape(-1) work = weight if weight.shape[0] == u.shape[0] else weight.T after = edited if edited.shape[0] == u.shape[0] else edited.T before_proj = float((u @ work)[cols].mean()) after_proj = float((u @ after)[cols].mean()) audits.append( { "layer": int(layer), "tensor": name, "shard": weight_map.get(name, "model.safetensors"), "shape": list(weight.shape), "columns": int(len(cols)), "column_indexes": [int(c) for c in cols[:16]], "component_scale": round(after_proj / before_proj, 4) if abs(before_proj) > 1e-8 else 0.0, "expected_scale": round(1.0 - float(alpha), 4), "relative_frobenius_pct": round(stats["relative_frobenius_pct"], 4), "sigma2_over_sigma1_pct": round(stats["sigma2_over_sigma1_pct"], 4), "sha256_before": hashlib.sha256(np.ascontiguousarray(weight).tobytes()).hexdigest(), "sha256_after": hashlib.sha256(np.ascontiguousarray(edited).tobytes()).hexdigest(), } ) return { "source": repo_id, "published": False, "alpha": float(alpha), "top_k": int(top_k), "embedding": embed_name, "water_samples": texts[:4], "water_count": len(texts), "u_preview": [round(float(x), 4) for x in direction[:8]], "layers": audits, } def _keys_and_map(repo_id: str, token: Optional[str]) -> Tuple[List[str], Dict[str, str]]: index = _read_json(repo_id, "model.safetensors.index.json", token) if index and index.get("weight_map"): weight_map = index["weight_map"] return list(weight_map), weight_map keys = _header_keys(repo_id, "model.safetensors", token) return keys, {k: "model.safetensors" for k in keys} def _load_named( repo_id: str, name: str, weight_map: Dict[str, str], token: Optional[str] ) -> Tuple[np.ndarray, str]: shard = weight_map.get(name) if not shard: raise KeyError(name) array, _ = _load_matrix(repo_id, name, shard, token) return array, name def _load_matrix( repo_id: str, name: str, shard: str, token: Optional[str] ) -> Tuple[np.ndarray, str]: header = _safetensors_header(repo_id, shard, token) if name not in header: # Single-file assumption failed; find the shard from the index. index = _read_json(repo_id, "model.safetensors.index.json", token) if index and name in (index.get("weight_map") or {}): shard = index["weight_map"][name] header = _safetensors_header(repo_id, shard, token) else: raise KeyError(name) meta = header[name] dtype = meta["dtype"] shape = tuple(int(x) for x in meta["shape"]) start, end = meta["data_offsets"] n_header = _header_len(repo_id, shard, token) if (end - start) > TENSOR_CAP: raise ValueError( f"{name} is {(end - start) / 1e6:.0f} MB. Test refused above {TENSOR_CAP // (1024 * 1024)} MB. Nothing was written." ) raw = _range_bytes(repo_id, shard, 8 + n_header + start, 8 + n_header + end - 1, token) array = _decode(raw, dtype, shape) return array, name def _header_len(repo_id: str, filename: str, token: Optional[str]) -> int: from huggingface_hub import hf_hub_url url = hf_hub_url(repo_id=repo_id, filename=filename) got = requests.get(url, headers={**_headers(_token(token)), "Range": "bytes=0-7"}, timeout=60) got.raise_for_status() return struct.unpack(" bytes: from huggingface_hub import hf_hub_url url = hf_hub_url(repo_id=repo_id, filename=filename) got = requests.get( url, headers={**_headers(_token(token)), "Range": f"bytes={start}-{end}"}, timeout=120, ) got.raise_for_status() data = got.content expected = end - start + 1 if len(data) == expected: return data if len(data) > expected and data[:8] == struct.pack(" expected: return data[:expected] raise ValueError(f"Short read for {filename}: wanted {expected}, got {len(data)}.") def _decode(raw: bytes, dtype: str, shape: Tuple[int, ...]) -> np.ndarray: if dtype == "F32": return np.frombuffer(raw, dtype=" List[int]: if tokenizer is None: return [((ord(ch) * 131) + 17) % 1024 for ch in text[:limit]] ids = tokenizer.encode(text).ids[:limit] return ids or [0] def _direction_from_water(embed: np.ndarray, tokenizer, texts: Sequence[str]) -> np.ndarray: # embed is (vocab, hidden) for every architecture we target. if embed.ndim != 2: raise ValueError(f"Embedding is not a matrix: {embed.shape}") table = embed if embed.shape[0] >= embed.shape[1] else embed.T def pool(samples: Sequence[str]) -> np.ndarray: acc = np.zeros(table.shape[1], dtype=np.float32) for text in samples: ids = [i for i in _encode(tokenizer, text) if 0 <= i < table.shape[0]] if not ids: continue acc += table[ids].mean(axis=0) return acc / max(len(samples), 1) delta = pool(texts) - pool(NEUTRAL) norm = float(np.linalg.norm(delta)) if norm < 1e-8: raise ValueError("Water and the neutral baseline landed on the same direction.") return (delta / norm).astype(np.float32) def publish( pointer: str, water: Sequence[str], name: str, note: str = "", layers: Optional[Sequence[int]] = None, alpha: float = 1.0, top_k: int = 64, chat: bool = True, private: bool = False, token: Optional[str] = None, ) -> Dict[str, Any]: """Create the model under the token's account. Optionally a chat Space. Token is not stored.""" token = _token(token) if not token: raise ValueError("A write token is required to create the model. Test does not need one.") api = _api(token) me = api.whoami() role = ((me.get("auth") or {}).get("accessToken") or {}).get("role") if role == "read": raise ValueError("That token is read-only. Use a write token.") username = me.get("name") if not username: raise ValueError("Token did not resolve to an account.") repo_name = _safe_name(name) target = repo_name if "/" in repo_name else f"{username}/{repo_name}" tested = test_edit(pointer, water, note, layers, alpha, top_k, token) source = tested["source"] info = api.model_info(source) files = [s.rfilename for s in info.siblings] from huggingface_hub import CommitOperationAdd, CommitOperationCopy, hf_hub_download from safetensors.numpy import load_file, save_file dirty = {row["shard"] for row in tested["layers"]} with tempfile.TemporaryDirectory() as tmp: tmp_dir = Path(tmp) patched: Dict[str, Path] = {} direction = _reload_direction(source, water, note, token) for shard in dirty: local = Path(hf_hub_download(repo_id=source, filename=shard, token=token)) if local.stat().st_size > SHARD_CAP: raise ValueError(f"{shard} is over the publish cap. Nothing was created.") tensors = load_file(str(local)) for row in tested["layers"]: if row["shard"] != shard: continue updated, _cols = rank1_column_ablation( tensors[row["tensor"]], direction, top_k=int(top_k), alpha=float(alpha) ) tensors[row["tensor"]] = updated out = tmp_dir / Path(shard).name save_file(tensors, str(out)) patched[shard] = out manifest = { "source": source, "target": target, "operator": "rank1_column_ablation", "formula": "w_j <- w_j - alpha * (u^T w_j) * u", "alpha": float(alpha), "top_k": int(top_k), "water": list(water), "note": note, "layers": tested["layers"], } card = _model_card(manifest) (tmp_dir / "weight_edit.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") (tmp_dir / "README.md").write_text(card, encoding="utf-8") api.create_repo(repo_id=target, private=private, exist_ok=True, repo_type="model") ops = [ CommitOperationAdd(path_in_repo=shard, path_or_fileobj=str(path)) for shard, path in patched.items() ] ops.append(CommitOperationAdd(path_in_repo="weight_edit.json", path_or_fileobj=str(tmp_dir / "weight_edit.json"))) ops.append(CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=str(tmp_dir / "README.md"))) for filename in files: if filename in patched or filename in {"README.md", "weight_edit.json"} or filename.startswith(".git"): continue ops.append( CommitOperationCopy( src_path_in_repo=filename, path_in_repo=filename, src_repo_id=source, src_repo_type="model", ) ) api.create_commit( repo_id=target, operations=ops, commit_message=f"Weight-space edit from {source}", commit_description=note or "Rank-1 column ablation from water sources.", ) space_url = None if chat: space_url = _create_chat_space(api, username, target, manifest, private) return { **tested, "published": True, "account": username, "model": target, "model_url": f"https://huggingface.co/{target}", "space_url": space_url, } def _reload_direction(source: str, water: Sequence[str], note: str, token: Optional[str]) -> np.ndarray: keys, weight_map = _keys_and_map(source, token) embed_name = next((n for n in EMBED_CANDIDATES if n in keys), None) if not embed_name: raise ValueError("No embedding tensor.") embed, _ = _load_named(source, embed_name, weight_map, token) return _direction_from_water(embed, _load_tokenizer(source, token), collect_water(water, note, token)) def _safe_name(name: str) -> str: cleaned = re.sub(r"[^A-Za-z0-9._/-]+", "-", name.strip()).strip("-/") if not cleaned: raise ValueError("Name the model.") return cleaned[:96] def _model_card(manifest: Dict[str, Any]) -> str: layers = ", ".join(f"L{row['layer']} `{row['tensor']}`" for row in manifest["layers"]) return f"""--- license: apache-2.0 tags: - weight-space - modelifier base_model: {manifest['source']} --- # {manifest['target'].split('/')[-1]} Weight-space edit of [{manifest['source']}](https://huggingface.co/{manifest['source']}). No gradient. No optimizer. `w_j <- w_j - alpha (u^T w_j) u` with alpha = {manifest['alpha']}. Touched: {layers}. Water: {', '.join(manifest['water']) or manifest['note'] or 'note only'}. The audit is in `weight_edit.json`. """ def _create_chat_space(api, username: str, model_id: str, manifest: Dict[str, Any], private: bool) -> str: space_id = f"{username}/{model_id.split('/')[-1]}-chat" api.create_repo( repo_id=space_id, repo_type="space", space_sdk="gradio", private=private, exist_ok=True, ) readme = f"""--- title: {model_id.split('/')[-1]} emoji: "✂️" colorFrom: gray colorTo: green sdk: gradio sdk_version: 4.44.1 app_file: app.py pinned: false license: apache-2.0 short_description: Chat with the weight-edited model --- Chat against `{model_id}`. The weights were edited, not fine-tuned. """ app = _CHAT_APP.replace("MODEL_ID", model_id).replace("EDIT_JSON", json.dumps(manifest)[:4000]) req = "gradio==4.44.1\ntransformers>=4.46\ntorch>=2.4\naccelerate>=0.34\n" from huggingface_hub import CommitOperationAdd api.create_commit( repo_id=space_id, repo_type="space", operations=[ CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=readme.encode()), CommitOperationAdd(path_in_repo="app.py", path_or_fileobj=app.encode()), CommitOperationAdd(path_in_repo="requirements.txt", path_or_fileobj=req.encode()), ], commit_message="Chat Space for the weight-edited model", ) return f"https://huggingface.co/spaces/{space_id}" _CHAT_APP = '''import json import gradio as gr import torch from transformers import AutoModelForCausalLM, AutoTokenizer MODEL_ID = "MODEL_ID" EDIT = json.loads("""EDIT_JSON""") tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.float32, low_cpu_mem_usage=True ) model.eval() def respond(message, history): turns = [] for item in history or []: if isinstance(item, dict): turns.append(item) elif isinstance(item, (list, tuple)) and len(item) == 2: turns.append({"role": "user", "content": item[0]}) turns.append({"role": "assistant", "content": item[1]}) turns.append({"role": "user", "content": message}) prompt = tokenizer.apply_chat_template(turns, tokenize=False, add_generation_prompt=True) if hasattr(tokenizer, "apply_chat_template") else "\\n".join(t["content"] for t in turns) inputs = tokenizer(prompt, return_tensors="pt") with torch.no_grad(): out = model.generate(**inputs, max_new_tokens=256, do_sample=True, temperature=0.7, top_p=0.9) text = tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) return text with gr.Blocks(title=MODEL_ID) as demo: gr.Markdown(f"# {MODEL_ID}\\nWeight-edited, not fine-tuned. Source `{EDIT.get('source')}`. alpha = {EDIT.get('alpha')}.") gr.ChatInterface(respond) if __name__ == "__main__": demo.launch() ''' def _parse_layers(value: str) -> Optional[List[int]]: if not value or not value.strip(): return None return [int(part.strip()) for part in value.split(",") if part.strip()] def main() -> None: import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("cmd", choices=["inspect", "test", "publish"]) parser.add_argument("--repo", required=True) parser.add_argument("--water", action="append", default=[]) parser.add_argument("--note", default="") parser.add_argument("--layers", default="") parser.add_argument("--alpha", type=float, default=1.0) parser.add_argument("--topk", type=int, default=64) parser.add_argument("--name", default="") parser.add_argument("--chat", type=int, default=1) parser.add_argument("--private", type=int, default=0) args = parser.parse_args() try: if args.cmd == "inspect": result = inspect_model(args.repo) elif args.cmd == "test": result = test_edit( args.repo, args.water, args.note, _parse_layers(args.layers), args.alpha, args.topk ) else: result = publish( args.repo, args.water, args.name, args.note, _parse_layers(args.layers), args.alpha, args.topk, bool(args.chat), bool(args.private), ) sys.stdout.write(json.dumps(result)) except Exception as exc: sys.stdout.write(json.dumps({"error": str(exc)})) sys.exit(1) if __name__ == "__main__": main()