Spaces:
Sleeping
Sleeping
Upload 133 files
Browse filesFiles changed (11)
- app.py+24-4
- docs/index.html+13-2
- obliteratus/adaptive_defaults.py+1-7
- obliteratus/architecture_profiles.py+4-1
- obliteratus/bayesian_optimizer.py-1
- obliteratus/cli.py+1-1
- obliteratus/evaluation/heretic_eval.py+1
- obliteratus/informed_pipeline.py+1-1
- obliteratus/mlx_backend.py-2
- obliteratus/telemetry.py+45-8
- obliteratus/tourney.py+4-5
1088 unmodified lines108910901091109210931094109510961097109810991100110111021103110416 unmodified lines1121112211231124112511261127112811293951 unmodified lines5081508250835084508550865087452 unmodified lines5540554155425543554455451088 unmodified linessuffix = f" β {model_label}" if model_label else ""heatmap_fig = plot_cross_layer_heatmap(result,output_path=tempfile.mktemp(suffix=".png"),title=f"Cross-Layer Direction Alignment{suffix}",)figs.append(heatmap_fig)drift_fig = plot_angular_drift(result,output_path=tempfile.mktemp(suffix=".png"),title=f"Refusal Direction Angular Drift{suffix}",)figs.append(drift_fig)16 unmodified linesproxy_harmless[idx] = torch.zeros_like(d_f).unsqueeze(0)proxy_harmful[idx] = (d_f * norm).unsqueeze(0)topo_fig = plot_refusal_topology(directions, proxy_harmful, proxy_harmless, list(strong_layers),output_path=tempfile.mktemp(suffix=".png"),title=f"Refusal Topology Map{suffix}",)figs.append(topo_fig)3951 unmodified linesDownload all intermediate data from your last obliteration run as a ZIP archive.**Contents:**- `refusal_directions.pt` β Per-layer refusal direction tensors (load with `torch.load()`)- `config.json` β Full pipeline configuration, strong layers, direction dimensions- `results.csv` β Quality metrics (perplexity, coherence, refusal rate)- `pipeline_log.txt` β Complete pipeline execution log452 unmodified lines_parser.add_argument("--auth", type=str, default=None, help="Basic auth as user:pass")_args = _parser.parse_args()_auth = tuple(_args.auth.split(":", 1)) if _args.auth else Nonelaunch(server_name=_args.host,server_port=_args.port,1088 unmodified lines1089109010911092109310941095109610971098109911001101110211031104110511061107110816 unmodified lines112511261127112811291130113111321133113411353951 unmodified lines5087508850895090509150925093452 unmodified lines554655475548554955505551555255535554555555565557555855595560556155625563556455651088 unmodified linessuffix = f" β {model_label}" if model_label else ""_fd1, _heatmap_path = tempfile.mkstemp(suffix=".png")os.close(_fd1)heatmap_fig = plot_cross_layer_heatmap(result,output_path=_heatmap_path,title=f"Cross-Layer Direction Alignment{suffix}",)figs.append(heatmap_fig)_fd2, _drift_path = tempfile.mkstemp(suffix=".png")os.close(_fd2)drift_fig = plot_angular_drift(result,output_path=_drift_path,title=f"Refusal Direction Angular Drift{suffix}",)figs.append(drift_fig)16 unmodified linesproxy_harmless[idx] = torch.zeros_like(d_f).unsqueeze(0)proxy_harmful[idx] = (d_f * norm).unsqueeze(0)_fd3, _topo_path = tempfile.mkstemp(suffix=".png")os.close(_fd3)topo_fig = plot_refusal_topology(directions, proxy_harmful, proxy_harmless, list(strong_layers),output_path=_topo_path,title=f"Refusal Topology Map{suffix}",)figs.append(topo_fig)3951 unmodified linesDownload all intermediate data from your last obliteration run as a ZIP archive.**Contents:**- `refusal_directions.pt` β Per-layer refusal direction tensors (load with `torch.load(..., weights_only=True)`)- `config.json` β Full pipeline configuration, strong layers, direction dimensions- `results.csv` β Quality metrics (perplexity, coherence, refusal rate)- `pipeline_log.txt` β Complete pipeline execution log452 unmodified lines_parser.add_argument("--auth", type=str, default=None, help="Basic auth as user:pass")_args = _parser.parse_args()_auth = tuple(_args.auth.split(":", 1)) if _args.auth else Noneif _args.share and _auth is None:import warnings as _w_w.warn("WARNING: --share creates a public link without authentication. ""Anyone with the link can access the UI. Use --auth user:pass to restrict access.",stacklevel=1,)if _args.host == "0.0.0.0" and _auth is None and not os.environ.get("SPACE_ID"):import warnings as _w_w.warn("WARNING: Binding to 0.0.0.0 exposes the UI to all network interfaces without authentication. ""Use --auth user:pass or --host 127.0.0.1 for local-only access.",stacklevel=1,)launch(server_name=_args.host,server_port=_args.port,
2014 unmodified lines2015201620172018201920202021105 unmodified lines21272128212921302131213221332014 unmodified linesablMethod = m;document.querySelectorAll('.method-radio').forEach(el => el.classList.remove('selected'));document.getElementById('method-' + m).classList.add('selected');document.getElementById('method-details').innerHTML = METHOD_INFO[m].desc;updateCmdDisplay();}105 unmodified linesstages.forEach(s => s.classList.remove('active','done'));connectors.forEach(c => c.classList.remove('active'));const modelName = ablSelectedModel || 'meta-llama/Llama-3.1-8B-Instruct';logEl.innerHTML = `<div class="log-line stage-line">[ ABLITERATION PIPELINE β ${modelName} ]</div>`;function addLog(text, cls='') {const line = document.createElement('div');2014 unmodified lines20152016201720182019202020212022202320242025202620272028105 unmodified lines213421352136213721382139214021412142214321442014 unmodified linesablMethod = m;document.querySelectorAll('.method-radio').forEach(el => el.classList.remove('selected'));document.getElementById('method-' + m).classList.add('selected');const detailsEl = document.getElementById('method-details');// METHOD_INFO descriptions are hardcoded constants β safe for innerHTML.// Guard against unexpected keys to avoid prototype pollution.if (Object.prototype.hasOwnProperty.call(METHOD_INFO, m)) {detailsEl.innerHTML = METHOD_INFO[m].desc;} else {detailsEl.textContent = '';}updateCmdDisplay();}105 unmodified linesstages.forEach(s => s.classList.remove('active','done'));connectors.forEach(c => c.classList.remove('active'));const modelName = ablSelectedModel || 'meta-llama/Llama-3.1-8B-Instruct';logEl.textContent = '';const headerLine = document.createElement('div');headerLine.className = 'log-line stage-line';headerLine.textContent = `[ ABLITERATION PIPELINE β ${modelName} ]`;logEl.appendChild(headerLine);function addLog(text, cls='') {const line = document.createElement('div');
427 unmodified lines428429430431432433434435436437251 unmodified lines689690691692693694695696131 unmodified lines828829830831832833834427 unmodified lines(arch_class, reasoning_class, param_bucket),]# Also check model-specific records (exact model name match)# This is for the future when we have enough data per-modelmodel_short = model_name.split("/")[-1].lower() if model_name else ""bucket = Noneused_key = Nonefor key in candidates:251 unmodified lineslines.append("| Rank | Method | Mean Score | Runs |")lines.append("|------|--------|------------|------|")for i, (name, score) in enumerate(rec.method_ranking[:8], 1):ms_runs = 0# Get run count from the knowledge (not stored directly, but we have n_method_records for winner)lines.append(f"| {i} | `{name}` | {score:.4f} | β |")lines.append("")131 unmodified linesreturn Noneknowledge = build_knowledge_base(records)snapshot_path = save_snapshot(knowledge)# Also compute and log global insights for visibilityinsights = get_global_insights(knowledge)427 unmodified lines428429430431432433251 unmodified lines685686687688689690131 unmodified lines822823824825826827828427 unmodified lines(arch_class, reasoning_class, param_bucket),]bucket = Noneused_key = Nonefor key in candidates:251 unmodified lineslines.append("| Rank | Method | Mean Score | Runs |")lines.append("|------|--------|------------|------|")for i, (name, score) in enumerate(rec.method_ranking[:8], 1):lines.append(f"| {i} | `{name}` | {score:.4f} | β |")lines.append("")131 unmodified linesreturn Noneknowledge = build_knowledge_base(records)save_snapshot(knowledge)# Also compute and log global insights for visibilityinsights = get_global_insights(knowledge)
19 unmodified lines2021222324252619 unmodified linesimport refrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Anylogger = logging.getLogger(__name__)19 unmodified lines2021222324252627282919 unmodified linesimport refrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, TYPE_CHECKINGif TYPE_CHECKING:from obliteratus.adaptive_defaults import AdaptiveRecommendationlogger = logging.getLogger(__name__)
29 unmodified lines3031323334353629 unmodified linesfrom __future__ import annotationsimport loggingimport mathfrom typing import TYPE_CHECKINGimport torch29 unmodified lines30313233343529 unmodified linesfrom __future__ import annotationsimport loggingfrom typing import TYPE_CHECKINGimport torch
482 unmodified lines483484485486487488489482 unmodified linesdef _cmd_tourney(args):from obliteratus.tourney import TourneyRunner, render_bracketdef on_log(msg):console.print(msg)482 unmodified lines483484485486487488489482 unmodified linesdef _cmd_tourney(args):from obliteratus.tourney import TourneyRunnerdef on_log(msg):console.print(msg)
638 unmodified lines639640641642643644638 unmodified linesoutput_dir: str | None,) -> dict:"""Run lm-evaluation-harness via Python API."""import lm_eval# Build per-task num_fewshot overrides638 unmodified lines639640641642643644645638 unmodified linesoutput_dir: str | None,) -> dict:"""Run lm-evaluation-harness via Python API."""model_path = _sanitize_model_path(model_path)import lm_eval# Build per-task num_fewshot overrides
784 unmodified lines785786787788789790791784 unmodified linesif self.direction_method == "leace":from obliteratus.analysis.leace import LEACEExtractorleace_extractor = LEACEExtractor()self.log(f"Using LEACE (closed-form optimal concept erasure)")if self.use_whitened_svd and self.n_directions > 1 and leace_extractor is None:from obliteratus.analysis.whitened_svd import WhitenedSVDExtractor784 unmodified lines785786787788789790791784 unmodified linesif self.direction_method == "leace":from obliteratus.analysis.leace import LEACEExtractorleace_extractor = LEACEExtractor()self.log("Using LEACE (closed-form optimal concept erasure)")if self.use_whitened_svd and self.n_directions > 1 and leace_extractor is None:from obliteratus.analysis.whitened_svd import WhitenedSVDExtractor
386 unmodified lines38738838939039139239332 unmodified lines426427428429430431432386 unmodified lines"""_require_mlx()from mlx_lm import convert # type: ignore[import-untyped]out = Path(output_dir)out.mkdir(parents=True, exist_ok=True)32 unmodified lines"""Convert a PyTorch tensor to an MLX array."""_require_mlx()import mlx.core as mx # type: ignore[import-untyped]import numpy as np# Move to CPU and convert via numpynp_array = tensor.detach().cpu().float().numpy()386 unmodified lines38738838939039139232 unmodified lines425426427428429430386 unmodified lines"""_require_mlx()out = Path(output_dir)out.mkdir(parents=True, exist_ok=True)32 unmodified lines"""Convert a PyTorch tensor to an MLX array."""_require_mlx()import mlx.core as mx # type: ignore[import-untyped]# Move to CPU and convert via numpynp_array = tensor.detach().cpu().float().numpy()
366 unmodified lines3673683693703713723733743753763773783793803813823833843853862 unmodified lines3893903913923933943953963973983994004012 unmodified lines4044054064074084094107 unmodified lines41841942042142242391 unmodified lines515516517518519520521522366 unmodified linesensuring all data lands in the same dataset repository.Uses _sync_in_progress event to prevent overlapping uploads."""if _sync_in_progress.is_set():return # Another sync is already running_sync_in_progress.set()try:repo = _TELEMETRY_REPOif not repo:returnif not TELEMETRY_FILE.exists():returnfrom huggingface_hub import HfApiif not _ensure_hub_repo(repo):returnapi = HfApi(token=os.environ.get("HF_TOKEN"))slug = _instance_slug()api.upload_file(path_or_fileobj=str(TELEMETRY_FILE),2 unmodified linesrepo_type="dataset",commit_message=f"Auto-sync telemetry from {slug}",)logger.info(f"Synced telemetry to {repo}/data/{slug}.jsonl")except Exception as e:logger.warning(f"Hub sync failed: {e}")finally:_sync_in_progress.clear()def _schedule_hub_sync() -> None:"""Schedule a debounced background sync of local telemetry to Hub.2 unmodified lines- Telemetry is disabled- Last sync was less than _HUB_SYNC_INTERVAL seconds ago"""global _hub_sync_lastif not _TELEMETRY_REPO:returnif not is_enabled():7 unmodified linest = threading.Thread(target=_sync_to_hub_bg, daemon=True)t.start()def fetch_hub_records(max_records: int = 10000) -> list[dict[str, Any]]:91 unmodified linesclone_dir = Path(tempfile.mkdtemp(prefix="obliteratus_telemetry_"))try:env = dict(os.environ)env["GIT_LFS_SKIP_SMUDGE"] = "1"result = subprocess.run(["git", "clone", "--depth", "1", clone_url, str(clone_dir)],capture_output=True, text=True, timeout=60, env=env,366 unmodified lines3673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963972 unmodified lines4004014024034044054064074084094104114124134144152 unmodified lines4184194204214224234247 unmodified lines43243343443543643743843944044144244344444544644744844945045145245345491 unmodified lines546547548549550551552553554555556557558559366 unmodified linesensuring all data lands in the same dataset repository.Uses _sync_in_progress event to prevent overlapping uploads."""# Atomic check-and-set to prevent concurrent syncs (Event lacks# compare-and-swap, so we use a lock for correctness).with _hub_sync_lock:if _sync_in_progress.is_set():return # Another sync is already running_sync_in_progress.set()try:repo = _TELEMETRY_REPOif not repo:logger.debug("Hub sync skipped: no telemetry repo configured")returnif not TELEMETRY_FILE.exists():logger.debug("Hub sync skipped: telemetry file does not exist")returntoken = os.environ.get("HF_TOKEN")if not token:logger.warning("Hub sync skipped: HF_TOKEN not set β auto-sync requires a write token")returnfrom huggingface_hub import HfApiif not _ensure_hub_repo(repo):logger.warning("Hub sync skipped: could not verify repo %s exists", repo)returnapi = HfApi(token=token)slug = _instance_slug()api.upload_file(path_or_fileobj=str(TELEMETRY_FILE),2 unmodified linesrepo_type="dataset",commit_message=f"Auto-sync telemetry from {slug}",)logger.info("Synced telemetry to %s/data/%s.jsonl", repo, slug)except Exception as e:logger.warning("Hub sync failed (will retry on next benchmark): %s", e)finally:_sync_in_progress.clear()_active_sync_thread: threading.Thread | None = Nonedef _schedule_hub_sync() -> None:"""Schedule a debounced background sync of local telemetry to Hub.2 unmodified lines- Telemetry is disabled- Last sync was less than _HUB_SYNC_INTERVAL seconds ago"""global _hub_sync_last, _active_sync_threadif not _TELEMETRY_REPO:returnif not is_enabled():7 unmodified linest = threading.Thread(target=_sync_to_hub_bg, daemon=True)t.start()_active_sync_thread = tdef _flush_sync_on_exit() -> None:"""Atexit handler: wait for any in-flight Hub sync to finish.On ZeroGPU Spaces the worker process is killed after each request.Without this, the daemon sync thread gets killed mid-upload andtelemetry silently fails to reach the Hub."""t = _active_sync_threadif t is not None and t.is_alive():t.join(timeout=30)import atexitatexit.register(_flush_sync_on_exit)def fetch_hub_records(max_records: int = 10000) -> list[dict[str, Any]]:91 unmodified linesclone_dir = Path(tempfile.mkdtemp(prefix="obliteratus_telemetry_"))try:# Only pass necessary env vars to subprocess β avoid leaking secrets_safe_keys = {"PATH", "HOME", "USER", "LANG", "LC_ALL", "TMPDIR","GIT_TERMINAL_PROMPT", "GIT_LFS_SKIP_SMUDGE","HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY","http_proxy", "https_proxy", "no_proxy"}env = {k: v for k, v in os.environ.items() if k in _safe_keys}env["GIT_LFS_SKIP_SMUDGE"] = "1"env["GIT_TERMINAL_PROMPT"] = "0"result = subprocess.run(["git", "clone", "--depth", "1", clone_url, str(clone_dir)],capture_output=True, text=True, timeout=60, env=env,
870 unmodified lines871872873874875876877139 unmodified lines1017101810191020102110221023223 unmodified lines1247124812491250125112521253103 unmodified lines13571358135913601361136213631364136513661367870 unmodified linesverify_sample_size: int = 30,) -> Contender:"""Run a single abliteration method and return its Contender result."""import torcht0 = time.time()contender = Contender(method=method)139 unmodified lines)n_methods = len(self.methods)self.log(f"OBLITERATUS TOURNEY")self.log(f"Model: {self.model_name}")self.log(f"Contenders: {n_methods} methods")self.log(f"Dataset: {self.dataset_key}")223 unmodified linesif resuming and resume_round_spec:# We have an interrupted round to finish β schedule it first,# then let the dynamic scheduling add subsequent rounds.ir = resume_round_specskip_completed_rounds = len(result.rounds)else:skip_completed_rounds = 0103 unmodified linesquantization=self.quantization,methods=self.methods,)self.log(f"\nGPU SESSION INTERRUPTED β checkpoint saved")self.log(f" Reason: {exc}")self.log(f" Completed: {len(rnd.contenders)} methods in round {round_num}")self.log(f" Remaining: {len(still_remaining)} methods")self.log(f" Click Run again to resume automatically.")raisernd.contenders.append(contender)870 unmodified lines871872873874875876139 unmodified lines1016101710181019102010211022223 unmodified lines1246124712481249125012511252103 unmodified lines13561357135813591360136113621363136413651366870 unmodified linesverify_sample_size: int = 30,) -> Contender:"""Run a single abliteration method and return its Contender result."""t0 = time.time()contender = Contender(method=method)139 unmodified lines)n_methods = len(self.methods)self.log("OBLITERATUS TOURNEY")self.log(f"Model: {self.model_name}")self.log(f"Contenders: {n_methods} methods")self.log(f"Dataset: {self.dataset_key}")223 unmodified linesif resuming and resume_round_spec:# We have an interrupted round to finish β schedule it first,# then let the dynamic scheduling add subsequent rounds._ = resume_round_spec # noqa: F841 β consumed by dynamic scheduling belowskip_completed_rounds = len(result.rounds)else:skip_completed_rounds = 0103 unmodified linesquantization=self.quantization,methods=self.methods,)self.log("\nGPU SESSION INTERRUPTED β checkpoint saved")self.log(f" Reason: {exc}")self.log(f" Completed: {len(rnd.contenders)} methods in round {round_num}")self.log(f" Remaining: {len(still_remaining)} methods")self.log(" Click Run again to resume automatically.")raisernd.contenders.append(contender)
app.py+24-4
docs/index.html+13-2
obliteratus/adaptive_defaults.py+1-7
obliteratus/architecture_profiles.py+4-1
obliteratus/bayesian_optimizer.py-1
obliteratus/cli.py+1-1
obliteratus/evaluation/heretic_eval.py+1
obliteratus/informed_pipeline.py+1-1
obliteratus/mlx_backend.py-2
obliteratus/telemetry.py+45-8
obliteratus/tourney.py+4-5