# /// script # requires-python = ">=3.11" # dependencies = [ # "torch>=2.1,<2.7", # "transformers>=4.46,<4.50", # "datasets", # "hqq>=0.2.8", # "accelerate", # "tqdm", # "huggingface_hub", # ] # /// """ HSAQ-quantize the LoRA-merged guardian model for swarm serving. Source: mxguru1/master-chief-guardian-8b-v1 (bf16 merged, 16 GB) Output: HSAQ-quantized state_dict + tokenizer + config in mxguru1/master-chief-guardian-8b-v1-hsaq (HF dataset) This is Phase 1A of the wargame thesis-test. The artifact is then loaded by a local FastAPI shim (Phase 1B) that mimics Ollama's endpoints, so the wargame can route to it via LOCAL_HF_SHIMS in adversarial_wargame_swarm.py. Cost: ~$1.50, ~30 min on A100 80GB. """ from __future__ import annotations import json, logging, os, subprocess, sys, time from datetime import UTC, datetime from pathlib import Path import torch if not torch.cuda.is_available(): subprocess.check_call([sys.executable, "-m", "pip", "install", "torch", "--force-reinstall", "--index-url", "https://download.pytorch.org/whl/cu124"]) import importlib; importlib.reload(torch) if not torch.cuda.is_available(): sys.exit(1) logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s | %(message)s") logger = logging.getLogger("GuardianHSAQ") sys.path.insert(0, "/opt/hsaq") from quantization.hsaq.config import HSAQConfig from quantization.hsaq.pipeline import HSAQPipeline MODEL_ID = "mxguru1/master-chief-guardian-8b-v1" HF_TOKEN = os.environ.get("HF_TOKEN") RUN_TAG = datetime.now(UTC).strftime("%Y%m%d_%H%M%S") OUT = Path("/tmp/guardian_hsaq"); OUT.mkdir(parents=True, exist_ok=True) def main(): start = time.time() report = {"run_tag": RUN_TAG, "approach": "hsaq_quantize_for_serving", "model_id": MODEL_ID} try: cfg = HSAQConfig( model_id=MODEL_ID, output_dir=str(OUT.parent), hf_token=HF_TOKEN, gpu_budget_gb=11.2, enable_2bit=False, enable_pruning=False, train_lora=False, # already LoRA-merged calibration_samples=128, ) pipe = HSAQPipeline(cfg) logger.info("Stage 1: load + profile %s", MODEL_ID) model, tokenizer = pipe._load_model() model = model.to("cuda:0") if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token sensitivity = pipe.profiler.profile(model) candidates = pipe._build_layer_candidates(sensitivity, model) from quantization.hsaq.assignment import assign_bit_widths weight_budget_gb = pipe._compute_weight_budget() assignment = assign_bit_widths(candidates, weight_budget_gb) name_to_bits = {a.component: a.chosen.bits for a in assignment.assignments} logger.info("Stage 2: HQQ apply to all 281 Linears") n_hqq = pipe._apply_per_module_hqq(model, name_to_bits, device="cuda:0") logger.info("HQQ applied to %d Linears", n_hqq) # Save model artifact artifact_dir = OUT / "guardian-hsaq" artifact_dir.mkdir(parents=True, exist_ok=True) try: from hqq.models.hf.base import AutoHQQHFModel AutoHQQHFModel.save_quantized(model, str(artifact_dir)) save_method = "AutoHQQHFModel.save_quantized" except Exception as exc: logger.warning("AutoHQQHFModel.save_quantized failed (%s); falling back to state_dict", exc) torch.save(model.state_dict(), artifact_dir / "pytorch_model.bin") save_method = "state_dict" tokenizer.save_pretrained(str(artifact_dir)) model.config.save_pretrained(str(artifact_dir)) # Per-layer bits manifest for the shim manifest = { "model_id": MODEL_ID, "save_method": save_method, "n_linears_quantized": n_hqq, "name_to_bits": name_to_bits, "group_size": 64, "axis": 0, "compute_dtype": "bfloat16", "total_weight_gb": round(assignment.total_weights_gb, 3), } (artifact_dir / "hsaq_manifest.json").write_text(json.dumps(manifest, indent=2)) report["artifact"] = manifest report["artifact_size_bytes"] = sum(p.stat().st_size for p in artifact_dir.rglob("*") if p.is_file()) logger.info("Artifact saved: %s (%.2f GB)", artifact_dir, report["artifact_size_bytes"] / 1e9) # Upload as dataset (HQQ artifacts aren't standard HF model format; dataset is fine) from huggingface_hub import HfApi repo_id = "mxguru1/master-chief-guardian-8b-v1-hsaq" api = HfApi(token=HF_TOKEN) api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True) for p in artifact_dir.rglob("*"): if p.is_file(): api.upload_file( path_or_fileobj=str(p), path_in_repo=p.name, repo_id=repo_id, repo_type="dataset", ) logger.info("Uploaded artifact to https://huggingface.co/datasets/%s", repo_id) report["status"] = "success" report["artifact_repo"] = repo_id except Exception as e: logger.exception("Run failed") report["status"] = "failed" report["error"] = repr(e) finally: report["elapsed_s"] = round(time.time() - start, 1) # Always upload the report from huggingface_hub import HfApi api = HfApi(token=HF_TOKEN) rid = f"mxguru1/guardian-hsaq-job-{RUN_TAG}" try: api.create_repo(repo_id=rid, repo_type="dataset", exist_ok=True) p = OUT / "report.json"; p.write_text(json.dumps(report, indent=2)) api.upload_file(path_or_fileobj=str(p), path_in_repo="report.json", repo_id=rid, repo_type="dataset") except Exception: pass if __name__ == "__main__": main()