"""Upload the payload the Colab lanes need, to Jyo-K/PopTurk. export HF_TOKEN=hf_... python scripts/01_upload_hf.py --what code shards models --split test WHAT GOES UP, AND WHAT DELIBERATELY DOES NOT code this source tree (~120 KB). The notebook imports berx from it, so there is exactly one copy of the scoring logic and a fix on the box reaches Colab on the next push. shards the self-contained cross-encoder work units from 04_make_shards.py. Text included, so a lane needs nothing else. models the fine-tuned cross-encoder checkpoints. Weights ONLY - the optimiser state is 4.5 GB of AdamW moments that inference never reads. geo the mined administrative-equivalence tables (a few MB). NOT the embeddings. They are already in the three channel repos and they are 42 GB; a Colab lane does cross-encoder scoring, which needs no embeddings at all. Anything that pulls them into a Colab VM has misunderstood the split of work. NOT the raw dataset in full. The shards already carry the text they need. PRIVACY. Every repo is created PRIVATE. The competition data is licensed to participants, not to the public, and a public dataset repo is a redistribution. Passing --public is an explicit decision to publish; think before you do. """ from __future__ import annotations import argparse import glob import os import re import shutil import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from berx import io_hf # noqa: E402 from berx import paths as P # noqa: E402 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Matches the assignment `HF_TOKEN = "hf_..."` so it can be blanked, and any bare hf_ token # anywhere else as a backstop. TOKEN_RE = re.compile(r'^(HF_TOKEN\s*=\s*).*$', re.M) LEAK_RE = re.compile(r'hf_[A-Za-z0-9]{20,}') # Backreference to group 1 (the `HF_TOKEN = ` prefix) plus an EMPTY STRING LITERAL. The empty # literal is not decoration: dropping it leaves `HF_TOKEN =` with no value, which is a # SyntaxError, and the published code/ tree would fail to import on every Colab lane. REDACTED = r'\1"" # redacted for upload' # Inference reads none of these; they are the bulk of a checkpoint directory. SKIP_IN_MODEL = {"opt.pt", "optimizer.pt", "scheduler.pt", "rng_state.pth", "trainer_state.json", "training_args.bin"} def push_code(repo: str, public: bool): """Upload the source tree, with the embedded token REDACTED. The token now lives in berx/io_hf.py so it does not have to be exported. That makes this function the one place it could leak: uploading the tree verbatim would publish the token inside the very repo it authenticates to. The redaction below is asserted, and the upload is refused outright if any token-shaped string survives it - a silent failure here means a live credential in a dataset repo. """ tmp = tempfile.mkdtemp() dst = os.path.join(tmp, "code") shutil.copytree(os.path.join(ROOT, "berx"), os.path.join(dst, "berx"), ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) shutil.copytree(os.path.join(ROOT, "scripts"), os.path.join(dst, "scripts"), ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) for f in ("hf_token.txt",): # never ships, whatever else happens q = os.path.join(dst, f) if os.path.exists(q): os.remove(q) redacted = 0 for root, _, files in os.walk(dst): for fn in files: if not fn.endswith((".py", ".sh", ".md", ".txt", ".json", ".ipynb")): continue fp = os.path.join(root, fn) try: txt = open(fp, encoding="utf-8").read() except (UnicodeDecodeError, OSError): continue new_txt = TOKEN_RE.sub(REDACTED, txt) if new_txt != txt: open(fp, "w", encoding="utf-8").write(new_txt) redacted += 1 leak = LEAK_RE.search(new_txt) assert not leak, ( f"REFUSING TO UPLOAD: {fp} still contains something token-shaped " f"({leak.group(0)[:12]}...). Fix the redaction before publishing.") io_hf.upload(dst, "code", repo, public) shutil.rmtree(tmp, ignore_errors=True) print(f" code/ uploaded (token redacted in {redacted} file(s))") def push_shards(repo: str, split: str, public: bool): files = sorted(glob.glob(P.work("shards", f"{split}_shard*.parquet"))) files += glob.glob(P.work("shards", f"{split}_manifest.json")) assert files, "no shards found - run 04_make_shards.py first" total = 0 for f in files: mb = os.path.getsize(f) / 2 ** 20 total += mb io_hf.upload(f, f"shards/{os.path.basename(f)}", repo, public) print(f" shards/{os.path.basename(f)} {mb:.1f} MB") print(f" {total:.1f} MB total") def push_model(repo: str, local: str, name: str, public: bool): assert os.path.isdir(local), f"not a directory: {local}" tmp = tempfile.mkdtemp() dst = os.path.join(tmp, name) os.makedirs(dst) kept = 0 for f in os.listdir(local): if f in SKIP_IN_MODEL or f == "ckpt": continue src = os.path.join(local, f) if os.path.isfile(src): shutil.copy2(src, os.path.join(dst, f)) kept += os.path.getsize(src) io_hf.upload(dst, f"models/{name}", repo, public) shutil.rmtree(tmp, ignore_errors=True) print(f" models/{name} {kept/2**30:.2f} GiB (optimiser state excluded)") def push_geo(repo: str, public: bool): for f in glob.glob(P.work("geo", "*.json")): io_hf.upload(f, f"geo/{os.path.basename(f)}", repo, public) print(f" geo/{os.path.basename(f)}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--what", nargs="+", required=True, choices=["code", "shards", "models", "geo", "all"]) ap.add_argument("--split", default="test") ap.add_argument("--repo", default=P.PAYLOAD_REPO) ap.add_argument("--model-dirs", nargs="*", default=[], help="LOCAL_DIR:NAME pairs, e.g. work/ce_model_A:bge_reranker_ft") ap.add_argument("--token", default="", help="overrides every other token source") ap.add_argument("--public", action="store_true", help="publish instead of keeping the repo private - think first") a = ap.parse_args() if a.token: io_hf.set_token(a.token) if not io_hf.token(): sys.exit("No token. Set HF_TOKEN in berx/io_hf.py, or pass --token, or put it in " "hf_token.txt, or export HF_TOKEN.") print(f"token from {io_hf.token_source()}") what = set(a.what) if "all" in what: what = {"code", "shards", "models", "geo"} io_hf.ensure_repo(a.repo, a.public) print(f"repo {a.repo} ({'PUBLIC' if a.public else 'private'})") if "code" in what: push_code(a.repo, a.public) if "shards" in what: push_shards(a.repo, a.split, a.public) if "geo" in what: push_geo(a.repo, a.public) if "models" in what: if not a.model_dirs: print(" --model-dirs not given; skipping models") for spec in a.model_dirs: local, _, name = spec.partition(":") push_model(a.repo, local, name or os.path.basename(local.rstrip("/")), a.public) print(f"\nhttps://huggingface.co/datasets/{a.repo}") if __name__ == "__main__": main()