File size: 7,160 Bytes
b4975b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
139
140
import argparse
import json
import os
import sys
import time
from pathlib import Path

import h5py
import torch
import torch.nn.functional as F

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
from prompts import DATASETS, TEMPLATES, class_phrases, generic, tag

ARM = 'short'
CRITERION = 'filtered-class'
KEEP = pp.KEEP_PATCHES
TOP1_ROOT = Path(os.environ.get('TOP1_ROOT', ROOT / 'data/packets/patch/top1'))
RUNS = {'native': ('native-261010', 'native-261005', 'native-build'), 'multiscale': ('multiscale-261010', 'multiscale-261005', 'multiscale-build')}


def top1_packet(dataset, enc, scale):
    name = f'{tag(dataset, enc, scale, ARM, CRITERION)}.pt'
    for run in RUNS['native' if scale == 'native' else 'multiscale']:
        path = TOP1_ROOT / run / 'packets' / name
        if path.exists():
            return path
    raise FileNotFoundError(f'{name} not found under {TOP1_ROOT}')


def build_cell(dataset, enc_name, scale, enc, templates, TN, out, limit, filter_info=None):
    path = out / f'{tag(dataset, enc_name, scale, ARM, CRITERION)}--patches{"-smoke" if limit else ""}.pt'
    if path.exists():
        print('skip (exists)', path.name, flush=True)
        return
    spec = DATASETS[dataset]
    canon_file = top1_packet(dataset, enc_name, scale)
    canon = torch.load(canon_file, map_location='cpu', weights_only=False)
    stems = list(canon['stems'])
    W = torch.stack([pp.concept_embedding(enc, p, templates) for p in class_phrases(dataset, ARM)])
    if W.size(0) != int(canon['n_classes']):
        raise ValueError(f'{dataset}: bank has {W.size(0)} classes, packet {canon["n_classes"]}')
    count = limit or len(stems)
    feats, scores, margin, index, coords, n_rows, n_all = [], [], [], [], [], [], []
    start = time.time()
    for i, stem in enumerate(stems[:count]):
        with h5py.File(pp.slide_path(spec, enc_name, scale, stem)) as h:
            x = enc.image(torch.tensor(h['features'][:]).float())
            xy = torch.tensor(h['coords'][:]).long()
        q = (x @ TN[0]) - (x @ TN[1])
        kept = pp.margin_order(q, min(KEEP, len(q)))
        s = x @ W.T
        rank = kept[torch.sort(-s.max(1).values[kept], stable=True).indices]
        pad = KEEP - rank.numel()
        feats.append(F.pad(x[rank], (0, 0, 0, pad)))
        scores.append(F.pad(s[rank], (0, 0, 0, pad)))
        margin.append(F.pad(q[rank], (0, pad)))
        index.append(F.pad(rank.int(), (0, pad), value=-1))
        coords.append(F.pad(xy[rank], (0, 0, 0, pad), value=-1))
        n_rows.append(rank.numel())
        n_all.append(len(q))
        if (i + 1) % 100 == 0:
            print(f'{dataset} {enc_name} {scale}: {i + 1}/{count} slides, {time.time() - start:.0f} s', flush=True)
    feats = torch.stack(feats)
    gap = float((feats[:, 0].float() - canon['z'][:count]).abs().max())
    if gap > 2e-3 and filter_info is None:
        raise ValueError(f'{dataset} {enc_name} {scale}: rank-1 patch differs from the top-1 packet z by {gap}')
    blob = {'stems': stems[:count], 'feats': feats, 'class_scores': torch.stack(scores), 'tumour_margin': torch.stack(margin),
            'patch_index': torch.stack(index), 'coords': torch.stack(coords),
            'count': torch.tensor(n_rows, dtype=torch.long), 'slide_patches': torch.tensor(n_all, dtype=torch.long),
            'provenance': {'dataset': dataset, 'encoder': enc_name, 'scale': scale, 'arm': ARM, 'criterion': CRITERION, 'rows': KEEP,
                           'ranking': 'the 100 patches with the largest tumour-minus-contrast margin, ordered by best class score (rank 1 first); any top-k is the first k rows',
                           'feats': 'encoder image vectors, unit length from the encoder, float32, zero padded',
                           'class_scores': 'unit patch vector times each class text embedding, before any temperature',
                           'padding': 'rows beyond count are zero (index and coords -1)', 'rank1_check_gap': gap,
                           'filter': filter_info or 'generic tumour and contrast phrases (data/prompts/generic.json)',
                           'top1_packet': canon_file.name, 'created': time.strftime('%Y-%m-%d %H:%M:%S %z')}}
    tmp = path.with_suffix('.tmp')
    torch.save(blob, tmp)
    tmp.replace(path)
    print(f'wrote {path.name} (rank-1 gap {gap:.1e}, {time.time() - start:.0f} s)', flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--encoder', required=True, choices=list(ENCODERS))
    ap.add_argument('--datasets', nargs='+', required=True, choices=list(DATASETS))
    ap.add_argument('--scales', nargs='+', default=['native', '1024px', '2048px'], choices=['native', '1024px', '2048px'])
    ap.add_argument('--out-dir', required=True)
    ap.add_argument('--limit', type=int, default=0)
    ap.add_argument('--threads', type=int, default=4)
    ap.add_argument('--filter-prompts', default=None, help='json with tumour and contrast phrases per dataset (data/prompts/detailed-pilot.json); default the generic phrases for every dataset')
    ap.add_argument('--dry-run', action='store_true', help='print the phrases and the files that would be written, load nothing')
    a = ap.parse_args()
    torch.set_num_threads(a.threads)
    out = Path(a.out_dir)
    out.mkdir(parents=True, exist_ok=True)
    prompts = json.load(open(a.filter_prompts))['datasets'] if a.filter_prompts else None
    if a.dry_run:
        for dataset in a.datasets:
            tumour, contrast = phrases(prompts, dataset)
            print(dataset, 'tumour', len(tumour), tumour, 'contrast', len(contrast), contrast)
            for scale in a.scales:
                print('  would write', out / f'{tag(dataset, a.encoder, scale, ARM, CRITERION)}--patches.pt')
        return
    enc = ENCODERS[a.encoder]()
    templates = TEMPLATES[a.encoder]
    embed = lambda tumour, contrast: torch.stack([pp.concept_embedding(enc, tumour, templates), pp.concept_embedding(enc, contrast, templates)])
    for dataset in a.datasets:
        tumour, contrast = phrases(prompts, dataset)
        TN = embed(tumour, contrast)
        info = {'phrases': a.filter_prompts, 'sha256': prompt_hash(a.filter_prompts), 'tumour': tumour, 'contrast': contrast} if prompts else None
        for scale in a.scales:
            try:
                build_cell(dataset, a.encoder, scale, enc, templates, TN, out, a.limit, info)
            except FileNotFoundError as e:
                print(f'skip {dataset} {a.encoder} {scale}: {e}', flush=True)


# the phrases that rank the patches of a dataset: its own detailed ones when a phrase file is given, otherwise the generic ones
def phrases(prompts, dataset):
    if prompts is None:
        return generic()
    entry = prompts[dataset]
    return [p['text'] for p in entry['tumour']], [p['text'] for p in entry['contrast']]


def prompt_hash(path):
    import hashlib
    return hashlib.sha256(Path(path).read_bytes()).hexdigest() if path else None


if __name__ == '__main__':
    main()