File size: 2,431 Bytes
1c9b5b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run the real pretrained encoder; clearly distinguish it from full 7B inference."""
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT))
from settings import CODE, weight_paths
sys.path.insert(0,str(CODE))

if __name__=='__main__':
    import torch
    from accelerate import cpu_offload
    from model.ImageBind.models import imagebind_model
    from model.ImageBind.models.imagebind_model import ModalityType
    from model.ImageBind import data
    checkpoint = weight_paths()['imagebind']
    if not checkpoint.is_file():
        raise SystemExit('Complete verified ImageBind weights are not yet available.')
    start = time.monotonic()
    model,_ = imagebind_model.imagebind_huge(pretrained=True,store_path=str(checkpoint.parent))
    model = model.eval().half()
    cpu_offload(model,execution_device=torch.device('cuda:0'),
                preload_module_classes=['MultiheadAttention','RGBDTPreprocessor','AudioPreprocessor','ThermalPreprocessor'])
    prompts = ['A photo of a dog.','A photo of a car.','A photo of a bird.']
    image = ROOT/'examples/inputs/dog_image.jpg'
    inputs = {ModalityType.VISION:data.load_and_transform_vision_data([str(image)],'cuda').half(),
              ModalityType.TEXT:data.load_and_transform_text(prompts,'cuda')}
    torch.cuda.reset_peak_memory_stats()
    with torch.inference_mode():
        embeddings = model(inputs)
        scores = (embeddings[ModalityType.VISION]@embeddings[ModalityType.TEXT].T).softmax(dim=-1)[0]
    record = {'record_kind':'pretrained_imagebind_component_execution', 'full_nextgpt_inference':False,
        'started_at':datetime.now(timezone.utc).isoformat(),'gpu':torch.cuda.get_device_name(0),
        'input_image':'examples/inputs/dog_image.jpg','prompts':prompts,
        'scores':scores.float().cpu().tolist(),'top_prompt':prompts[int(scores.argmax())],
        'vision_embedding_shape':list(embeddings[ModalityType.VISION].shape),
        'elapsed_seconds':round(time.monotonic()-start,3),
        'peak_gpu_gib':round(torch.cuda.max_memory_allocated()/2**30,3)}
    output = ROOT/'docs/execution/imagebind-component-result.json'
    output.parent.mkdir(exist_ok=True)
    output.write_text(json.dumps(record,ensure_ascii=False,indent=2),encoding='utf-8')
    print(json.dumps(record,ensure_ascii=False,indent=2),flush=True)