MCPcopy Create free account
hub / github.com/LLaVA-VL/LLaVA-NeXT / predict

Method predict

predict.py:83–137  ·  view source on GitHub ↗

Run a single prediction on the model

(
        self,
        image: Path = Input(description="Input image"),
        prompt: str = Input(description="Prompt to use for text generation"),
        top_p: float = Input(description="When decoding text, samples from the top p percentage of most likely tokens; lower to ignore less likely tokens", ge=0.0, le=1.0, default=1.0),
        temperature: float = Input(description="Adjusts randomness of outputs, greater than 1 is random and 0 is deterministic", default=0.2, ge=0.0),
        max_tokens: int = Input(description="Maximum number of tokens to generate. A word is generally 2-3 tokens", default=1024, ge=0),
    )

Source from the content-addressed store, hash-verified

81 self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model("liuhaotian/llava-v1.5-13b", model_name="llava-v1.5-13b", model_base=None, load_8bit=False, load_4bit=False)
82
83 def predict(
84 self,
85 image: Path = Input(description="Input image"),
86 prompt: str = Input(description="Prompt to use for text generation"),
87 top_p: float = Input(description="When decoding text, samples from the top p percentage of most likely tokens; lower to ignore less likely tokens", ge=0.0, le=1.0, default=1.0),
88 temperature: float = Input(description="Adjusts randomness of outputs, greater than 1 is random and 0 is deterministic", default=0.2, ge=0.0),
89 max_tokens: int = Input(description="Maximum number of tokens to generate. A word is generally 2-3 tokens", default=1024, ge=0),
90 ) -> ConcatenateIterator[str]:
91 """Run a single prediction on the model"""
92
93 conv_mode = "llava_v1"
94 conv = conv_templates[conv_mode].copy()
95
96 image_data = load_image(str(image))
97 image_tensor = self.image_processor.preprocess(image_data, return_tensors="pt")["pixel_values"].half().cuda()
98
99 # loop start
100
101 # just one turn, always prepend image token
102 inp = DEFAULT_IMAGE_TOKEN + "\n" + prompt
103 conv.append_message(conv.roles[0], inp)
104
105 conv.append_message(conv.roles[1], None)
106 prompt = conv.get_prompt()
107
108 input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
109 stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
110 keywords = [stop_str]
111 stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
112 streamer = TextIteratorStreamer(self.tokenizer, skip_prompt=True, timeout=20.0)
113
114 with torch.inference_mode():
115 thread = Thread(
116 target=self.model.generate,
117 kwargs=dict(inputs=input_ids, images=image_tensor, do_sample=True, temperature=temperature, top_p=top_p, max_new_tokens=max_tokens, streamer=streamer, use_cache=True, stopping_criteria=[stopping_criteria]),
118 )
119 thread.start()
120 # workaround: second-to-last token is always " "
121 # but we want to keep it if it's not the second-to-last token
122 prepend_space = False
123 for new_text in streamer:
124 if new_text == " ":
125 prepend_space = True
126 continue
127 if new_text.endswith(stop_str):
128 new_text = new_text[: -len(stop_str)].strip()
129 prepend_space = False
130 elif prepend_space:
131 new_text = " " + new_text
132 prepend_space = False
133 if len(new_text):
134 yield new_text
135 if prepend_space:
136 yield " "
137 thread.join()
138
139
140def load_image(image_file):

Callers

nothing calls this directly

Calls 7

tokenizer_image_tokenFunction · 0.90
copyMethod · 0.80
append_messageMethod · 0.80
get_promptMethod · 0.80
load_imageFunction · 0.70
preprocessMethod · 0.45

Tested by

no test coverage detected