import argparse import csv import hashlib import json import shutil from pathlib import Path ROOT = Path(__file__).resolve().parents[3] # registers new canonical patch cells: copies their packets into data/packets and adds the rows the tuning scripts read # (hpc-run/jobs/cells.tsv, ex-042 best-top-p.csv, experiments/miscellaneous/shared/cells.json); cells already present are left alone def main(): ap = argparse.ArgumentParser(description='Register new canonical patch cells from a staging folder.') ap.add_argument('--cells', required=True, help='csv with dataset, encoder, scale, top1_bacc_rule, best_top_p') ap.add_argument('--staging', required=True, help='folder holding top1-out/{native,multiscale}-build/packets, topp-out/pooled, text-out and best-top-p-hpc.csv') ap.add_argument('--tag', required=True, help='suffix of the new top-1 folders, for example 261028') a = ap.parse_args() staging = Path(a.staging) rows = list(csv.DictReader(open(a.cells))) tsv, best_csv, cells_json = ROOT / 'embedding-acquire/hpc-run/jobs/cells.tsv', ROOT / 'experiments/ex-042-top-p/results/best-top-p.csv', ROOT / 'experiments/miscellaneous/shared/cells.json' have = {tuple(l.split('\t')[:2]) for l in tsv.read_text().splitlines()[1:]} hpc = {(r['dataset'], r['encoder'], r['scale']): r for r in csv.DictReader(open(staging / 'best-top-p-hpc.csv'))} cfg = json.loads(cells_json.read_text()) with open(tsv, 'a') as t, open(best_csv, 'a', newline='') as b: bw = csv.writer(b) for r in rows: d, e, s, p = r['dataset'], r['encoder'], r['scale'], int(r['best_top_p']) if (d, e) in have: print(f'skip {d} {e}: already a canonical cell') continue kind = 'native' if s == 'native' else 'multiscale' name = f'{d}--{e}--{s}--short--filtered-class.pt' top1 = ROOT / f'data/packets/patch/top1/{kind}-{a.tag}/packets/{name}' top1.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(staging / f'top1-out/{kind}-build/packets/{name}', top1) shutil.copy2(staging / f'text-out/{d}--{e}.pt', ROOT / f'data/packets/text/{d}--{e}.pt') if p > 1: shutil.copy2(staging / f'topp-out/pooled/{d}--{e}--{s}--P{p}.pt', ROOT / f'data/packets/patch/pooled/{d}--{e}--{s}--P{p}.pt') rel = str(top1.relative_to(ROOT)) t.write(f'{d}\t{e}\t{s}\tpatch\t{float(r["top1_bacc_rule"]):.2f}\t{rel}\t{top1.stat().st_size}\t{hashlib.sha256(top1.read_bytes()).hexdigest()}\n') h = hpc[(d, e, s)] if int(h['P']) != p: raise ValueError(f'{d} {e} {s}: best Top-P {h["P"]} in the job output differs from {p} in the cell list') bw.writerow([h[k] for k in ('dataset', 'encoder', 'scale', 'P', 'f1_weighted', 'balanced_accuracy', 'auc', 'slides', 'slides_out_of_patches')]) for setting, top_p in (('top1', 1), ('best', p)): cfg[setting][f'{d}--{e}'] = dict(dataset=d, encoder=e, scale=s, packet=rel, top_p=top_p) print(f'added {d} {e} {s} P{p}') cells_json.write_text(json.dumps(cfg, indent=1) + '\n') if __name__ == '__main__': main()