File size: 6,317 Bytes
a4054b7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | # MIT License, Bryan Cheng, 2026.
"""Publish data, results and trained adapters to Hugging Face (D-050).
Two staging trees of per-file symlinks are built on scratch:
dataset -> datasets/bryan7264/lorapop (public): processed genotypes and kinship of every population, results/,
selected raw inputs (HF index, reference corpus, training data, battery sources without the HarmBench
behaviour list, concordance), and a copy of the git HEAD under code/.
adapters -> bryan7264/lorapop-adapters (public): every finished adapter we trained (folders with _ok), without the
gradient files and the _ok markers.
Third-party public adapters and reduced full fine-tunes are not redistributed.
Every text file under 50 MB is scanned for credentials (Hugging Face, GitHub and AWS tokens, private keys) and for the
strings in the environment variable PUBLISH_BLOCK (comma-separated); a file with a hit is left out and listed.
Uploads use upload_large_folder, which resumes from its cache in <stage>/<tree>/.cache after an interruption.
python tools/publish_hf.py --stage /nfs/roberts/scratch/pi_skr2/bjc75/finetuning/hf_stage [--dry] [--only dataset]
"""
import argparse
import json
import os
import re
import subprocess
import sys
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
SCR = "/nfs/roberts/scratch/pi_skr2/bjc75/finetuning"
REPOS = {"dataset": ("bryan7264/lorapop", "dataset"), "adapters": ("bryan7264/lorapop-adapters", "model")}
RAW_KEEP = ["hf_index", "refcorpus", "train_data", "battery", "concord_q05", "sciq"]
RAW_SKIP_DIRS = {os.path.join("battery", "harmbench")}
TRAINED = ["targeted", "opposite", "siblings", "targeted_tinyllama"]
PAT = [re.compile(p) for p in (r"hf_[A-Za-z0-9]{30,}", r"ghp_[A-Za-z0-9]{30,}", r"github_pat_[A-Za-z0-9_]{30,}",
r"AKIA[0-9A-Z]{16}", r"-----BEGIN [A-Z ]*PRIVATE KEY-----")]
BLOCK = [s.strip() for s in os.environ.get("PUBLISH_BLOCK", "").split(",") if s.strip()]
def link(src, dst, out):
os.makedirs(os.path.dirname(dst), exist_ok=True)
if not os.path.lexists(dst):
os.symlink(os.path.realpath(src), dst)
out.append(dst)
def link_tree(src_dir, dst_dir, out, skip_dirs=(), skip=lambda name: False):
for d, subdirs, files in os.walk(src_dir, followlinks=True):
rel = os.path.relpath(d, src_dir)
subdirs[:] = sorted(s for s in subdirs if os.path.normpath(os.path.join(rel, s)) not in skip_dirs
and s not in ("__pycache__", ".cache"))
for f in sorted(files):
if not skip(f):
link(os.path.join(d, f), os.path.join(dst_dir, rel, f), out)
def flagged(path):
"""Name of the first credential pattern or blocked string found in a text file, else None."""
if os.path.getsize(path) > 50 * 2 ** 20:
return None
with open(path, "rb") as fh:
if b"\0" in fh.read(8192):
return None
with open(path, "r", errors="ignore") as fh:
for line in fh:
for p in PAT:
if p.search(line):
return p.pattern.split("[")[0]
for b in BLOCK:
if b in line:
return "blocked string"
return None
def build_dataset(stage):
out = []
link(os.path.join(ROOT, "tools", "hf_dataset_card.md"), os.path.join(stage, "README.md"), out)
code = os.path.join(stage, "code")
if not os.path.isdir(code): # real copy of the committed tree
os.makedirs(code)
subprocess.run(f"git -C {ROOT} archive HEAD | tar -x -C {code}", shell=True, check=True)
for d, _, files in os.walk(code):
out += [os.path.join(d, f) for f in files]
for pop in sorted(os.listdir(os.path.join(SCR, "processed"))):
src = os.path.join(SCR, "processed", pop)
if os.listdir(src):
link_tree(src, os.path.join(stage, "data", "processed", pop), out)
for r in RAW_KEEP:
link_tree(os.path.join(SCR, "raw", r), os.path.join(stage, "data", "raw", r), out,
skip_dirs={os.path.relpath(s, r) for s in RAW_SKIP_DIRS if s.startswith(r + os.sep)})
link_tree(os.path.join(ROOT, "results"), os.path.join(stage, "results"), out)
return out
def build_adapters(stage):
out = []
link(os.path.join(ROOT, "tools", "hf_adapters_card.md"), os.path.join(stage, "README.md"), out)
for s in TRAINED:
base = os.path.join(SCR, "raw", "trained", s)
for name in sorted(os.listdir(base)):
d = os.path.join(base, name)
if os.path.isdir(d) and os.path.exists(os.path.join(d, "_ok")):
link_tree(d, os.path.join(stage, s, name), out, skip=lambda f: f == "_ok")
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--stage", required=True)
ap.add_argument("--dry", action="store_true")
ap.add_argument("--only", choices=list(REPOS))
ap.add_argument("--workers", type=int, default=2)
a = ap.parse_args()
report = {}
for tree in ([a.only] if a.only else list(REPOS)):
stage = os.path.join(a.stage, tree)
files = (build_dataset if tree == "dataset" else build_adapters)(stage)
hits = {}
for f in files:
h = flagged(f)
if h:
hits[os.path.relpath(f, stage)] = h
os.remove(f) if os.path.islink(f) else os.rename(f, f + ".withheld")
size = sum(os.path.getsize(f) for f in files if os.path.exists(f))
report[tree] = {"files": len(files) - len(hits), "bytes": size, "withheld": hits}
print(tree, json.dumps(report[tree]), flush=True)
if a.dry:
continue
from huggingface_hub import HfApi
api = HfApi()
repo_id, rtype = REPOS[tree]
api.create_repo(repo_id, repo_type=rtype, private=False, exist_ok=True)
ign = ["**/*.withheld", ".cache/**"]
api.upload_large_folder(repo_id=repo_id, folder_path=stage, repo_type=rtype, num_workers=a.workers,
ignore_patterns=ign)
print("UPLOADED", tree, repo_id, flush=True)
json.dump(report, open(os.path.join(a.stage, "publish_report.json"), "w"), indent=1)
print("PUBLISHDONE", flush=True)
if __name__ == "__main__":
sys.exit(main())
|