zaher-m's picture
download
raw
16.3 kB
"""Move code to a Colab server and result files back.
Through the notebook file (when a Colab kernel works)
python -m src.colab_sync pack notebooks/fit_eval.ipynb writes the bundle file and its hash for the notebook
python -m src.colab_sync extract notebooks/fit_eval.ipynb writes files that Colab cells emitted with emit()
Through a terminal on the Colab server
python -m src.colab_sync runner <path>/fit_colab.py writes a self-contained runner to upload
python -m src.colab_sync unpack <path>/fit_results_<phase>.tar.gz writes the downloaded results
"""
import base64
import gzip
import hashlib
import io
import json
import os
import sys
import tarfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
PACK_PATHS = ["config.yaml", "src", "prompts", "data/eval_set.jsonl", "data/probe_set.jsonl"]
PACK_SUFFIXES = {".py", ".json", ".yaml"}
# The notebook also carries the saved outputs, so it can rebuild every table and figure without a rerun.
NOTEBOOK_DATA = ["outputs/raw/full.jsonl", "results/probe_r2.csv", "results/mechanism/tokens_per_digit.csv",
"results/mechanism/tokenization_examples.json", "results/run/throughput_full.jsonl"]
TAG = "FIT_FILE"
BOOTSTRAP_ID = "bootstrap"
BUNDLE_NAME = "fit_bundle.tar.gz" # written next to the notebook, and kept at notebooks/ in the bucket
BUCKET_ID = "zaher-m/eastern-arabic-digits-eval"
BUNDLE_URL = f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/notebooks/{BUNDLE_NAME}"
BOOTSTRAP_TEMPLATE = '''# Written by src/colab_sync.py. Do not edit. On Colab it unpacks the project code and the saved outputs
# from {name} after checking its SHA-256 hash. Upload the file to the Colab Files pane (it lands in /content),
# or let this cell download it from the public bucket. Locally the cell only sets paths.
import hashlib, io, os, sys, tarfile, urllib.request
from pathlib import Path
BUNDLE_SHA256 = "{sha}"
BUNDLE_URL = "{url}"
if RUNTIME == "colab":
bundle_file = Path("/content") / "{name}"
if not bundle_file.exists():
print("downloading", BUNDLE_URL)
urllib.request.urlretrieve(BUNDLE_URL, bundle_file)
raw = bundle_file.read_bytes()
if hashlib.sha256(raw).hexdigest() != BUNDLE_SHA256:
raise RuntimeError(f"{{bundle_file}} does not match its hash. Upload the {name} that came with this notebook")
PROJECT = Path("/content/fit")
PROJECT.mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tar:
tar.extractall(PROJECT, filter="data")
else:
PROJECT = Path.cwd().parent if Path.cwd().name == "notebooks" else Path.cwd()
os.chdir(PROJECT)
if str(PROJECT) not in sys.path:
sys.path.insert(0, str(PROJECT))
for name in [m for m in sys.modules if m == "src" or m.startswith("src.")]:
del sys.modules[name] # a live kernel would otherwise keep the old code
print("runtime:", RUNTIME, "| code bundle:", BUNDLE_SHA256[:12])
'''
RUNNER_TEMPLATE = '''"""Self-contained runner for a terminal on a Colab server. Written by src/colab_sync.py. Do not edit.
Usage:
python3 fit_colab.py <phase> [archive ...] run a phase, after restoring results from earlier archives
python3 fit_colab.py pack <phase> pack the current results, also while a run is going on
A run unpacks the project code to /content/fit, installs the pinned packages and runs the phase. Every few
minutes and at the end it packs the results and the full log into /content/fit_results_<phase>.tar.gz.
With HF_TOKEN set, each archive is also copied to the private dataset repo <user>/fit-run-checkpoints, and
a new run of the same phase first restores the copy kept there. A run that stopped can then be started
again with the same command, on any server, and it continues where it stopped.
"""
import base64, hashlib, io, os, subprocess, sys, tarfile, threading, time
from pathlib import Path
BUNDLE_SHA256 = "{sha}"
BUNDLE = "{bundle}"
PROJECT = Path("/content/fit")
CHECKPOINT_SECONDS = 300
CHECKPOINT_REPO = "fit-run-checkpoints"
PACK_LOCK = threading.Lock()
def unpack():
raw = base64.b64decode(BUNDLE)
if hashlib.sha256(raw).hexdigest() != BUNDLE_SHA256:
raise RuntimeError("code bundle does not match its hash")
PROJECT.mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tar:
tar.extractall(PROJECT, filter="data")
def install():
import yaml
pins = yaml.safe_load((PROJECT / "config.yaml").read_text())["runtimes"]["colab"]["pip"]
subprocess.run([sys.executable, "-m", "pip", "install", "-q", *pins], check=True)
def archive_path(phase):
return PROJECT.parent / f"fit_results_{{phase}}.tar.gz"
def checkpoint_store(api):
"""The private dataset repo that keeps copies of the archives. Refuses a repo that is public."""
repo_id = api.whoami()["name"] + "/" + CHECKPOINT_REPO
api.create_repo(repo_id, repo_type="dataset", private=True, exist_ok=True)
if not api.repo_info(repo_id, repo_type="dataset").private:
raise RuntimeError(f"{{repo_id}} is public, checkpoints may only go to a private repo")
return api, repo_id
def restore_checkpoint(store, phase):
from src.colab_sync import unpack_results
api, repo_id = store
name = archive_path(phase).name
if not api.file_exists(repo_id, name, repo_type="dataset"):
print("no checkpoint of", phase, "in", repo_id, flush=True)
return
local = api.hf_hub_download(repo_id, name, repo_type="dataset", local_dir=PROJECT.parent / "checkpoint")
print("restoring results from", repo_id, flush=True)
unpack_results(local, root=PROJECT)
def checkpoint(phase, store):
"""Pack the results now and, with a store, copy the archive there. Returns the archive and whether
the copy worked. A failed copy is reported, and the next checkpoint tries again."""
from src.colab_sync import pack_results
with PACK_LOCK:
out = pack_results(PROJECT, archive_path(phase))
if store is None:
return out, False
api, repo_id = store
try:
api.upload_file(path_or_fileobj=str(out), path_in_repo=out.name, repo_id=repo_id,
repo_type="dataset", commit_message=f"checkpoint {{phase}}")
except Exception as e:
print("checkpoint copy failed:", repr(e), flush=True)
return out, False
print(time.strftime("%H:%M"), "checkpoint copied to", repo_id, flush=True)
return out, True
def single_run_lock():
"""Hold a lock for the life of this process, so a second run started by mistake stops at once.
The system releases the lock when the process ends, also when it is killed."""
import fcntl
handle = open(PROJECT.parent / "fit_run.lock", "w")
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise SystemExit("another run is already active on this server, so this one does not start")
return handle
def keep_checkpointing(phase, store, stop):
while not stop.wait(CHECKPOINT_SECONDS):
checkpoint(phase, store)
def run_job(phase, log_path):
log_path.parent.mkdir(parents=True, exist_ok=True)
env = {{k: v for k, v in os.environ.items() if k != "HF_TOKEN"}} # the model download stays anonymous
env["FIT_CODE_BUNDLE"] = BUNDLE_SHA256[:12]
with open(log_path, "a", encoding="utf-8") as log: # append, so a resumed run extends the log
proc = subprocess.Popen([sys.executable, "-u", "-m", "src.colab_job", phase], cwd=PROJECT, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in proc.stdout:
sys.stdout.write(line)
sys.stdout.flush()
log.write(line)
log.flush()
return proc.wait()
def main(args):
sys.path.insert(0, str(PROJECT))
if args[0] == "pack":
print("download this file:", checkpoint(args[1], None)[0])
return
phase = args[0]
lock = single_run_lock()
print("code bundle:", BUNDLE_SHA256[:12])
unpack()
from src.colab_sync import unpack_results
for archive in args[1:]:
print("restoring results from", archive)
unpack_results(archive, root=PROJECT)
install()
os.environ["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "1"
token = os.environ.get("HF_TOKEN")
store = None
if token:
from huggingface_hub import HfApi
store = checkpoint_store(HfApi(token=token))
restore_checkpoint(store, phase)
else:
print("HF_TOKEN is not set, so checkpoints stay on this server only", flush=True)
stop = threading.Event()
threading.Thread(target=keep_checkpointing, args=(phase, store, stop), daemon=True).start()
code = run_job(phase, PROJECT / "logs" / f"colab_{{phase}}.log")
stop.set()
out, copied = checkpoint(phase, store)
print("phase", phase, "exit code", code)
print("download this file:", out)
if store:
print("copy in", store[1] + ":", "done" if copied else "FAILED, download the file above")
sys.exit(code)
if __name__ == "__main__":
main(sys.argv[1:])
'''
RESULT_DIRS = ["results", "outputs", "logs"]
MANIFEST = "MANIFEST.json"
def write_runner(path, root=ROOT):
raw = bundle_bytes(root)
text = RUNNER_TEMPLATE.format(sha=hashlib.sha256(raw).hexdigest(), bundle=base64.b64encode(raw).decode())
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text(text, encoding="utf-8")
print(f"runner with {len(packed_files(root))} files written to {path}, bundle {hashlib.sha256(raw).hexdigest()[:12]}")
def result_files(project):
files = []
for d in RESULT_DIRS:
if (project / d).is_dir():
files += [f for f in sorted((project / d).rglob("*")) if f.is_file()]
return files
def snapshot(path):
"""File bytes. A JSONL file that is still being written is cut after its last complete line."""
data = path.read_bytes()
if path.suffix == ".jsonl" and not data.endswith(b"\n"):
data = data[:data.rfind(b"\n") + 1]
return data
def add_bytes(tar, name, data):
info = tarfile.TarInfo(name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
def pack_results(project, out_path):
"""Tar.gz of result files with a manifest of SHA-256 hashes."""
project, out_path = Path(project), Path(out_path)
snaps = {f.relative_to(project).as_posix(): snapshot(f) for f in result_files(project)}
manifest = {rel: hashlib.sha256(data).hexdigest() for rel, data in snaps.items()}
part = out_path.with_name(f"{out_path.name}.{os.getpid()}.part")
with tarfile.open(part, mode="w:gz") as tar:
add_bytes(tar, MANIFEST, json.dumps(manifest, indent=1).encode())
for rel, data in snaps.items():
add_bytes(tar, rel, data)
os.replace(part, out_path) # a download never sees a half-written archive
return out_path
def unpack_results(tar_path, root=ROOT):
results = []
with tarfile.open(tar_path, mode="r:gz") as tar:
manifest = json.loads(tar.extractfile(MANIFEST).read())
members = {m.name: m for m in tar.getmembers() if m.isfile() and m.name != MANIFEST}
if set(members) != set(manifest):
raise RuntimeError(f"archive members and manifest differ: {sorted(set(members) ^ set(manifest))}")
for rel, sha in sorted(manifest.items()):
data = tar.extractfile(members[rel]).read()
if hashlib.sha256(data).hexdigest() != sha:
raise RuntimeError(f"hash mismatch for {rel}")
status = write_checked(Path(root) / safe_relative(rel), data)
results.append((rel, status))
print(f"{status}: {rel} ({len(data)} bytes)")
return results
def packed_files(root=ROOT, extra=()):
files = []
for name in [*PACK_PATHS, *extra]:
p = root / name
if p.is_file():
files.append(p)
elif p.is_dir():
files += [f for f in sorted(p.rglob("*")) if f.is_file() and f.suffix in PACK_SUFFIXES
and "__pycache__" not in f.parts]
return files
def bundle_bytes(root=ROOT, extra=()):
"""Deterministic tar.gz of the code: sorted names, zero mtimes, no owner names."""
tar_buf = io.BytesIO()
with tarfile.open(fileobj=tar_buf, mode="w") as tar:
for f in packed_files(root, extra):
data = f.read_bytes()
info = tarfile.TarInfo(f.relative_to(root).as_posix())
info.size = len(data)
info.mtime = 0
info.mode = 0o644
tar.addfile(info, io.BytesIO(data))
gz_buf = io.BytesIO()
with gzip.GzipFile(fileobj=gz_buf, mode="wb", mtime=0) as gz:
gz.write(tar_buf.getvalue())
return gz_buf.getvalue()
def notebook_bundle(root=ROOT):
return bundle_bytes(root, NOTEBOOK_DATA)
def bootstrap_source(root=ROOT):
raw = notebook_bundle(root)
return BOOTSTRAP_TEMPLATE.format(sha=hashlib.sha256(raw).hexdigest(), url=BUNDLE_URL, name=BUNDLE_NAME)
def pack(notebook_path):
"""Write the bundle file next to the notebook and its hash into the bootstrap cell."""
nb = json.loads(Path(notebook_path).read_text(encoding="utf-8"))
cells = [c for c in nb["cells"] if c.get("id") == BOOTSTRAP_ID]
if len(cells) != 1:
raise RuntimeError(f"expected one cell with id {BOOTSTRAP_ID!r}, found {len(cells)}")
(Path(notebook_path).parent / BUNDLE_NAME).write_bytes(notebook_bundle())
cells[0]["source"] = bootstrap_source().splitlines(keepends=True)
cells[0]["outputs"] = []
cells[0]["execution_count"] = None
Path(notebook_path).write_text(json.dumps(nb, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
print(f"packed {len(packed_files(extra=NOTEBOOK_DATA))} files into {Path(notebook_path).parent / BUNDLE_NAME}")
def emit(path, root=None):
"""Print a file as one tagged line. Called inside a notebook cell."""
root = Path.cwd() if root is None else Path(root)
p = Path(path)
rel = (p if not p.is_absolute() else p.relative_to(root)).as_posix()
data = (root / rel).read_bytes()
payload = base64.b64encode(gzip.compress(data, mtime=0)).decode()
print(f"{TAG}\t{rel}\t{hashlib.sha256(data).hexdigest()}\t{payload}")
def tagged_lines(nb):
for cell in nb["cells"]:
text = "".join(
"".join(o["text"]) if isinstance(o["text"], list) else o["text"]
for o in cell.get("outputs", []) if o.get("output_type") == "stream"
)
for line in text.splitlines():
if line.startswith(TAG + "\t"):
yield line
def safe_relative(rel):
p = Path(rel)
if p.is_absolute() or ".." in p.parts or not p.parts:
raise ValueError(f"refusing path {rel!r}")
return p
def write_checked(target, data):
"""Write if absent, skip if identical, extend if the old file is a prefix, keep the old file
if it already extends the new one. Otherwise fail."""
if target.exists():
old = target.read_bytes()
if old == data:
return "unchanged"
if old.startswith(data):
return "kept newer"
if not data.startswith(old):
raise RuntimeError(f"{target} differs from the emitted file and is not a prefix of it")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
return "written"
def extract(notebook_path, root=ROOT):
nb = json.loads(Path(notebook_path).read_text(encoding="utf-8"))
results = []
for line in tagged_lines(nb):
_, rel, sha, payload = line.split("\t")
data = gzip.decompress(base64.b64decode(payload))
if hashlib.sha256(data).hexdigest() != sha:
raise RuntimeError(f"hash mismatch for {rel}")
status = write_checked(Path(root) / safe_relative(rel), data)
results.append((rel, status))
print(f"{status}: {rel} ({len(data)} bytes)")
if not results:
print("no emitted files found, was the notebook saved after running?")
return results
if __name__ == "__main__":
command, target = sys.argv[1], sys.argv[2]
{"pack": pack, "extract": extract, "runner": write_runner, "unpack": unpack_results}[command](target)

Xet Storage Details

Size:
16.3 kB
·
Xet hash:
42c6125aeeabe849dda7da73795e7119529152a2c618a6991876a197501beb0e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.