File size: 10,136 Bytes
9126e0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Frozen GPU inference, image-level caching, and label-isolated CACP evaluation."""
from pathlib import Path
import argparse,json,time,os,hashlib,collections,platform
import numpy as np
from PIL import Image
from repair import query_plan,repaired_maps,visual_features,score_mask
ROOT=Path(__file__).resolve().parents[1]

class ClipSeg:
    threshold=.5
    def __init__(self):
        import torch
        from transformers import CLIPSegProcessor,CLIPSegForImageSegmentation
        self.torch=torch;path=ROOT/'assets/models/clipseg'
        self.processor=CLIPSegProcessor.from_pretrained(str(path),local_files_only=True)
        self.model=CLIPSegForImageSegmentation.from_pretrained(str(path),local_files_only=True).eval().cuda()
    def predict(self,image,texts):
        t=self.torch;out={}
        with t.inference_mode():
            for k in range(0,len(texts),8):
                batch=texts[k:k+8]
                inputs=self.processor(text=batch,images=[image]*len(batch),padding=True,truncation=True,return_tensors='pt').to('cuda')
                logits=self.model(**inputs,interpolate_pos_encoding=True).logits
                if logits.ndim==2:logits=logits[None]
                probs=t.nn.functional.interpolate(logits[:,None],size=(image.height,image.width),mode='bilinear',align_corners=False)[:,0].sigmoid()
                for q,p in zip(batch,probs):out[q]=p.float().cpu().numpy()
        return out,{'language_queries':len(texts),'sam_boxes':0,'truncated_boxes':0}

class GroundedSam:
    threshold=.25
    def __init__(self):
        import torch
        from transformers import AutoProcessor,AutoModelForZeroShotObjectDetection,SamProcessor,SamModel,GroundingDinoConfig
        self.torch=torch;p=ROOT/'assets/models/groundingdino';s=ROOT/'assets/models/sam'
        self.processor=AutoProcessor.from_pretrained(str(p),local_files_only=True)
        cfg=GroundingDinoConfig.from_pretrained(str(p),local_files_only=True);cfg.disable_custom_kernels=True
        self.model=AutoModelForZeroShotObjectDetection.from_pretrained(str(p),config=cfg,local_files_only=True).eval().cuda()
        self.samproc=SamProcessor.from_pretrained(str(s),local_files_only=True)
        self.sam=SamModel.from_pretrained(str(s),local_files_only=True).eval().cuda()
    def predict(self,image,texts):
        t=self.torch;allboxes=[];detections={};truncated=0;out={}
        with t.inference_mode():
            for k in range(0,len(texts),2):
                batch=texts[k:k+2]
                inputs=self.processor(images=[image]*len(batch),text=[q.strip(' .')+'.' for q in batch],padding=True,truncation=True,return_tensors='pt').to('cuda')
                pred=self.model(**inputs)
                det=self.processor.post_process_grounded_object_detection(pred,inputs.input_ids,box_threshold=.25,text_threshold=.25,target_sizes=[(image.height,image.width)]*len(batch))
                for q,d in zip(batch,det):
                    order=d['scores'].argsort(descending=True);truncated+=max(0,len(order)-30);order=order[:30]
                    entries=[]
                    for box,score in zip(d['boxes'][order].cpu().tolist(),d['scores'][order].cpu().tolist()):
                        box=[max(0,min(v,image.width if j%2==0 else image.height)) for j,v in enumerate(box)]
                        if box[2]-box[0]<1 or box[3]-box[1]<1:continue
                        key=tuple(round(v,1) for v in box)
                        if key not in allboxes:allboxes.append(key)
                        entries.append((allboxes.index(key),float(score)))
                    detections[q]=entries
            masks=[]
            if allboxes:
                ip=self.samproc(images=image,return_tensors='pt').to('cuda')
                emb=self.sam.get_image_embeddings(ip.pixel_values)
                for k in range(0,len(allboxes),16):
                    ins=self.samproc(images=image,input_boxes=[[list(b) for b in allboxes[k:k+16]]],return_tensors='pt').to('cuda')
                    pr=self.sam(image_embeddings=emb,input_boxes=ins.input_boxes,multimask_output=True)
                    chosen=pr.iou_scores[0].argmax(dim=-1)
                    low=pr.pred_masks[:,t.arange(len(chosen),device='cuda'),chosen,: ,:][:,:,None]
                    # Official postprocessing restores original image resolution.
                    full=self.samproc.image_processor.post_process_masks(low,ins.original_sizes,ins.reshaped_input_sizes,binarize=True)[0]
                    masks.extend(full[:,0].cpu().numpy().astype(bool))
            for q in texts:
                p=np.zeros((image.height,image.width),np.float32)
                for idx,score in detections[q]:p=np.maximum(p,masks[idx]*score)
                out[q]=p
        return out,{'language_queries':len(texts),'sam_boxes':len(allboxes),'truncated_boxes':truncated}

def main():
    p=argparse.ArgumentParser();p.add_argument('--model',choices=['clipseg','groundedsam'],required=True)
    p.add_argument('--shard',type=int,default=0);p.add_argument('--shards',type=int,default=1)
    p.add_argument('--pilot',action='store_true');p.add_argument('--limit',type=int,default=0)
    args=p.parse_args();print('IMPORT_START',vars(args),flush=True)
    import torch,transformers
    torch.set_num_threads(4);torch.manual_seed(20260906);np.random.seed(20260906)
    assert torch.cuda.is_available(),'GPU required: submit with Slurm'
    records=[json.loads(x) for x in (ROOT/'data/manifest.jsonl').read_text().splitlines()]
    if args.pilot:
        # Infrastructure / implementation checks see fit examples only.
        records=[r for r in records if r['split']=='fit']
        records=[r for r in records if (r['domain']=='controlled' and r['scene_id']=='s11_0000') or r['domain']=='natural']
    groups=collections.defaultdict(list)
    for r in records:groups[r['image_path']].append(r)
    selected=sorted(groups)
    if args.pilot:selected=selected[:1]+[x for x in selected if '/natural/' in x][:3]
    elif args.limit:selected=selected[:args.limit]
    selected=selected[args.shard::args.shards]
    suffix=f'{args.model}_{"pilot" if args.pilot else "main"}_{args.shard}of{args.shards}'
    cache=ROOT/'cache'/args.model;cache.mkdir(parents=True,exist_ok=True)
    resultfile=ROOT/'results'/f'{suffix}.jsonl';timingfile=ROOT/'results'/f'{suffix}_timings.jsonl'
    engine=ClipSeg() if args.model=='clipseg' else GroundedSam()
    print('MODEL_READY',torch.cuda.get_device_name(0),'images',len(selected),flush=True)
    started=time.time();nrecord=0;queries=0;gpu_seconds=0;hits=0
    with resultfile.open('w') as result,timingfile.open('w') as timing:
        for index,ipath in enumerate(selected):
            group=groups[ipath];texts=[]
            for r in group:
                _,qs=query_plan(r['query']);texts.extend(qs)
            texts=list(dict.fromkeys(texts));image=Image.open(ROOT/ipath).convert('RGB')
            digest=hashlib.sha256((ipath+'\n'+'\n'.join(texts)).encode()).hexdigest()[:24];cp=cache/(digest+'.npz')
            elapsed=0.;stats={'language_queries':0,'sam_boxes':0,'truncated_boxes':0}
            if cp.exists():
                z=np.load(cp);assert z['texts'].tolist()==texts;maps={q:z[f'p{i}'].astype(np.float32) for i,q in enumerate(texts)};hits+=1
            else:
                torch.cuda.synchronize();t0=time.perf_counter();maps,stats=engine.predict(image,texts);torch.cuda.synchronize();elapsed=time.perf_counter()-t0
                # Quantize identically before both scoring and storage, so replay
                # and initial evaluation see exactly the same cached scores.
                maps={q:maps[q].astype(np.float16).astype(np.float32) for q in texts}
                assert all(np.isfinite(v).all() and v.min()>=0 and v.max()<=1 for v in maps.values())
                tmp=cp.with_suffix('.partial.npz');np.savez_compressed(tmp,texts=np.array(texts),**{f'p{i}':maps[q].astype(np.float16) for i,q in enumerate(texts)});tmp.replace(cp)
            gpu_seconds+=elapsed;queries+=stats['language_queries']
            # Ground truth is loaded only after all model predictions are fixed.
            for r in group:
                gt=np.asarray(Image.open(ROOT/r['gt_path']))>0
                oracle=np.asarray(Image.open(ROOT/r['anchor_gt_path']))>0 if 'anchor_gt_path' in r else None
                preds,flags=repaired_maps(r['query'],maps,engine.threshold,oracle_anchor=oracle)
                row={k:r[k] for k in ['id','scene_id','domain','split','mode','pair_id','endpoint','target_count','seed','template','corruption']}
                row.update(model=args.model,flags=flags,features=visual_features(maps[query_plan(r['query'])[0].original],preds['cacp'],engine.threshold),scores={m:score_mask(pred,gt) for m,pred in preds.items()},cache_path=str(cp.relative_to(ROOT)),query_count=len(query_plan(r['query'])[1]))
                result.write(json.dumps(row)+'\n');nrecord+=1
            timing.write(json.dumps(dict(image_path=ipath,records=len(group),requested_unique_queries=len(texts),cached=elapsed==0,seconds=elapsed,**stats))+'\n');result.flush();timing.flush()
            if index%20==0:print(json.dumps({'image':index+1,'of':len(selected),'records':nrecord,'new_queries':queries,'forward_seconds':round(gpu_seconds,2),'wall_seconds':round(time.time()-started,2)}),flush=True)
    meta={'status':'COMPLETE','model':args.model,'images':len(selected),'records':nrecord,'unique_queries_executed':queries,'cache_hits':hits,'forward_seconds':gpu_seconds,'wall_seconds':time.time()-started,'gpu':torch.cuda.get_device_name(0),'torch':torch.__version__,'transformers':transformers.__version__,'numpy':np.__version__,'python':platform.python_version(),'slurm_job_id':os.getenv('SLURM_JOB_ID'),'node':os.getenv('SLURMD_NODENAME'),'args':vars(args),'manifest_sha256':hashlib.sha256((ROOT/'data/manifest.jsonl').read_bytes()).hexdigest(),'code_sha256':{x:hashlib.sha256((ROOT/'code'/x).read_bytes()).hexdigest() for x in ['infer.py','repair.py']}}
    (ROOT/'results'/f'{suffix}_meta.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True)
if __name__=='__main__':main()