Download scripts/packets/text_embeddings.py from thanminh01/WSI_Packets: direct link, hf CLI and curl.
- Browser
- Download file 4.82 kB
-
https://huggingface.co/datasets/thanminh01/WSI_Packets/resolve/main/scripts/packets/text_embeddings.py
- Command line
-
hf download hf://datasets/thanminh01/WSI_Packets/scripts/packets/text_embeddings.py
-
curl -L -o text_embeddings.py https://huggingface.co/datasets/thanminh01/WSI_Packets/resolve/main/scripts/packets/text_embeddings.py
4.82 kB
| import argparse | |
| import ast | |
| import os | |
| import sys | |
| from pathlib import Path | |
| import json | |
| import torch | |
| HERE = Path(__file__).resolve().parent | |
| ROOT = HERE.parents[2] | |
| sys.path.insert(0, str(Path(os.environ.get('TUNE_DIR', ROOT / 'experiments/miscellaneous/tune')))) | |
| import patch_packets as pp | |
| from encoders import ENCODERS, TEXT_ENCODERS | |
| from prompts import DATASETS, TEMPLATES, class_phrases | |
| ARM = 'short' | |
| def check_against_set(W, dataset, enc_name, sets_dir): | |
| files = sorted(Path(sets_dir).glob(f'{dataset}--{enc_name}--*--patches.pt')) | |
| if not files: | |
| return None | |
| b = torch.load(files[0], map_location='cpu', weights_only=False, mmap=True) | |
| n = min(64, b['feats'].size(0)) | |
| feats = b['feats'][:n].float() | |
| mask = torch.arange(feats.size(1))[None, :] < b['count'][:n, None] | |
| pred = feats @ W.T | |
| return float((pred - b['class_scores'][:n].float()).abs()[mask].max()) | |
| def builder_phrases(path): | |
| # Reads CLASS_ORDER and CLASS_PROMPTS from a packet builder script without running it. | |
| values = {} | |
| for node in ast.parse(Path(path).read_text()).body: | |
| if isinstance(node, ast.Assign) and getattr(node.targets[0], 'id', None) in ('CLASS_ORDER', 'CLASS_PROMPTS'): | |
| values[node.targets[0].id] = ast.literal_eval(node.value) | |
| return [values['CLASS_PROMPTS'][c] for c in values['CLASS_ORDER']] | |
| def check_against_packet(W, packet_path): | |
| d = torch.load(packet_path, map_location='cpu', weights_only=False) | |
| return float((d['z'].float() @ W.T - d['g'].float()).abs().max()) | |
| def main(): | |
| ap = argparse.ArgumentParser(description='Saves the class text embedding matrix W per dataset and encoder, checked against the stored class scores of the patch sets.') | |
| ap.add_argument('--encoder', required=True, choices=list(TEXT_ENCODERS)) | |
| ap.add_argument('--datasets', nargs='+', default=list(DATASETS), choices=list(DATASETS)) | |
| ap.add_argument('--out-dir', default=str(ROOT / 'data/packets/text')) | |
| ap.add_argument('--sets-dir', default=str(ROOT / 'data/packets/patch/sets')) | |
| ap.add_argument('--arm', default=ARM, help='prompt arm, short for the patch encoders') | |
| ap.add_argument('--phrases-from-builder', nargs='*', default=[], metavar='DATASET=BUILDER.py', help='slide encoders only: take the class phrases of a dataset from the CLASS_PROMPTS of the builder script that made its packet') | |
| ap.add_argument('--scales-file', default=None, help='slide encoders only: scales.json that names the packet to check against') | |
| ap.add_argument('--max-gap', type=float, default=1e-2, help='slide encoders only: write a file only when the gap to the packet scores is at most this') | |
| ap.add_argument('--threads', type=int, default=4) | |
| a = ap.parse_args() | |
| torch.set_num_threads(a.threads) | |
| out = Path(a.out_dir) | |
| out.mkdir(parents=True, exist_ok=True) | |
| if a.encoder in ENCODERS: | |
| enc = ENCODERS[a.encoder]() | |
| templates = TEMPLATES[a.encoder] | |
| else: | |
| enc = TEXT_ENCODERS[a.encoder]() | |
| templates = json.load(open(ROOT / 'data/templates' / f'{a.encoder}.json'))['templates'] | |
| for dataset in a.datasets: | |
| source = dict(x.split('=', 1) for x in a.phrases_from_builder).get(dataset) | |
| phrases = builder_phrases(source) if source else class_phrases(dataset, a.arm) | |
| if a.encoder not in ENCODERS: | |
| W = enc.class_matrix(phrases, templates) | |
| packet = ROOT / json.load(open(a.scales_file))[dataset][a.encoder]['packet'] | |
| gap = check_against_packet(W, packet) | |
| print(f'{dataset} {a.encoder} arm {a.arm}: W {tuple(W.shape)} max gap to packet g {gap:.2e}', flush=True) | |
| if gap > a.max_gap: | |
| print(f'{dataset}: gap above {a.max_gap}, no file written', flush=True) | |
| continue | |
| torch.save({'W': W, 'temperature': float(enc.temperature), 'dataset': dataset, 'encoder': a.encoder, 'arm': a.arm if not source else 'builder', | |
| 'phrases_source': source, 'class_phrases': phrases, 'templates': templates, 'packet': str(packet.name), 'max_gap_to_packet_g': gap}, | |
| out / f'{dataset}--{a.encoder}.pt') | |
| continue | |
| W = torch.stack([pp.concept_embedding(enc, p, templates) for p in phrases]).float() | |
| gap = check_against_set(W, dataset, a.encoder, a.sets_dir) | |
| blob = {'W': W, 'temperature': float(enc.temperature), 'dataset': dataset, 'encoder': a.encoder, 'arm': a.arm, | |
| 'n_templates': len(templates), 'class_phrases': phrases, 'max_gap_to_set_class_scores': gap} | |
| torch.save(blob, out / f'{dataset}--{a.encoder}.pt') | |
| print(f'{dataset} {a.encoder}: W {tuple(W.shape)} temperature {blob["temperature"]:.3f} max gap to stored class scores {gap}', flush=True) | |
| if __name__ == '__main__': | |
| main() | |