File size: 1,389 Bytes
a863f79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForCausalLM

path = "/repository/models/Phi-3.5-vision-instruct"
processor = AutoProcessor.from_pretrained(path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    path, torch_dtype=torch.bfloat16, device_map="cuda:0",
    trust_remote_code=True, attn_implementation="eager",
)
tok = processor.tokenizer
print("yes_ids", tok.encode("yes", add_special_tokens=False)[:3])
print("no_ids", tok.encode("no", add_special_tokens=False)[:3])
print("eos", model.generation_config.eos_token_id, "pad", tok.pad_token_id)

text = ("<|user|>\n<|image_1|>\nIs the cup to the left of the box? "
        "Respond with exactly one word: yes or no.<|end|>\n<|assistant|>\n")
inputs = processor(text=text, images=[Image.open("dataset/render_all/left_right_0000_a.png")],
                   return_tensors="pt").to("cuda:0")
dtype = next(model.parameters()).dtype
inputs = {k: (v.to(dtype) if torch.is_floating_point(v) else v) for k, v in inputs.items()}

with torch.no_grad():
    logits = model(**inputs).logits[0, -1]
values, indices = torch.topk(logits, 6)
print("top", [(tok.decode([int(i)]), round(float(v), 2)) for v, i in zip(values, indices)])
generated = model.generate(**inputs, max_new_tokens=6, do_sample=False)
print("gen", repr(tok.decode(generated[0, inputs["input_ids"].shape[1]:])))