diff --git a/notebooks/phi-3-vision/README.md b/notebooks/phi-3-vision/README.md new file mode 100644 index 00000000000..e412aacfb12 --- /dev/null +++ b/notebooks/phi-3-vision/README.md @@ -0,0 +1,21 @@ +## Visual-language assistant with Phi3-Vision and OpenVINO + +The [Phi-3-Vision-128K-Instruct](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct) is a lightweight, state-of-the-art open multimodal model built upon datasets which include - synthetic data and filtered publicly available websites - with a focus on very high-quality, reasoning dense data both on text and vision. The model belongs to the Phi-3 model family, and the multimodal version comes with 128K context length (in tokens) it can support. The model underwent a rigorous enhancement process, incorporating both supervised fine-tuning and direct preference optimization to ensure precise instruction adherence and robust safety measures. More details about model can be found in [model blog post](https://azure.microsoft.com/en-us/blog/new-models-added-to-the-phi-3-family-available-on-microsoft-azure/), [technical report](https://aka.ms/phi3-tech-report), [Phi-3-cookbook](https://github.com/microsoft/Phi-3CookBook) + +In this tutorial we consider how to launch Phi-3-vision using OpenVINO for creation multimodal chatbot. Additionally, we optimize model to low precsion using [NNCF](https://github.com/openvinotoolkit/nncf) + +## Notebook contents +The tutorial consists from following steps: + +- Install requirements +- Convert and Optimize model +- Run OpenVINO model inference +- Launch Interactive demo + +In this demonstration, you'll create interactive chatbot that can answer questions about provided image's content. + + +## Installation instructions +This is a self-contained example that relies solely on its own code.
+We recommend running the notebook in a virtual environment. You only need a Jupyter server to start. +For details, please refer to [Installation Guide](../../README.md). \ No newline at end of file diff --git a/notebooks/phi-3-vision/gradio_helper.py b/notebooks/phi-3-vision/gradio_helper.py new file mode 100644 index 00000000000..bd9172dffd3 --- /dev/null +++ b/notebooks/phi-3-vision/gradio_helper.py @@ -0,0 +1,97 @@ +from pathlib import Path +import requests +import gradio as gr +from PIL import Image +from threading import Thread +from transformers import TextIteratorStreamer + +def make_demo(model, processor): + example_image_urls = [ + ( + "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/1d6a0188-5613-418d-a1fd-4560aae1d907", + "bee.jpg", + ), + ( + "https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/6cc7feeb-0721-4b5d-8791-2576ed9d2863", + "baklava.png", + ), + ("https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/dd5105d6-6a64-4935-8a34-3058a82c8d5d", "small.png"), + ("https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/1221e2a8-a6da-413a-9af6-f04d56af3754", "chart.png"),] + + for url, file_name in example_image_urls: + if not Path(file_name).exists(): + Image.open(requests.get(url, stream=True).raw).save(file_name) + + def bot_streaming(message, history): + print(f'message is - {message}') + print(f'history is - {history}') + if message["files"]: + # message["files"][-1] is a Dict or just a string + if type(message["files"][-1]) == dict: + image = message["files"][-1]["path"] + else: + image = message["files"][-1] + else: + # if there's no image uploaded for this turn, look for images in the past turns + # kept inside tuples, take the last one + for hist in history: + if type(hist[0]) == tuple: + image = hist[0][0] + try: + if image is None: + # Handle the case where image is None + raise gr.Error("You need to upload an image for Phi3-Vision to work. Close the error and try again with an Image.") + except NameError: + # Handle the case where 'image' is not defined at all + raise gr.Error("You need to upload an image for Phi3-Vision to work. Close the error and try again with an Image.") + + conversation = [] + flag=False + for user, assistant in history: + if assistant is None: + #pass + flag=True + conversation.extend([{"role": "user", "content":""}]) + continue + if flag==True: + conversation[0]['content'] = f"<|image_1|>\n{user}" + conversation.extend([{"role": "assistant", "content": assistant}]) + flag=False + continue + conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]) + + if len(history) == 0: + conversation.append({"role": "user", "content": f"<|image_1|>\n{message['text']}"}) + else: + conversation.append({"role": "user", "content": message['text']}) + print(f"prompt is -\n{conversation}") + prompt = processor.tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True) + image = Image.open(image) + inputs = processor(prompt, image, return_tensors="pt") + + streamer = TextIteratorStreamer(processor, **{"skip_special_tokens": True, "skip_prompt": True, 'clean_up_tokenization_spaces':False,}) + generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024, do_sample=False, temperature=0.0, eos_token_id=processor.tokenizer.eos_token_id,) + + thread = Thread(target=model.generate, kwargs=generation_kwargs) + thread.start() + + buffer = "" + for new_text in streamer: + buffer += new_text + yield buffer + + demo = gr.ChatInterface( + fn=bot_streaming, + title="Phi3 Vision 128K Instruct with OpenVINO", + examples=[ + {"text": "What is on the flower?", "files": ["./bee.jpg"]}, + {"text": "How to make this pastry?", "files": ["./baklava.png"]}, + {"text": "What is the text saying?", "files": ["./small.png"]}, + {"text": "What does the chart display?", "files": ["./chart.png"]}, + ], + description="Try the [Phi3-Vision model](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct) from Microsoft wiht OpenVINO. Upload an image and start chatting about it, or simply try one of the examples below. If you won't upload an image, you will receive an error.", + stop_btn="Stop Generation", + multimodal=True, + ) + + return demo \ No newline at end of file diff --git a/notebooks/phi-3-vision/ov_phi3_vision.py b/notebooks/phi-3-vision/ov_phi3_vision.py new file mode 100644 index 00000000000..2654a869d3c --- /dev/null +++ b/notebooks/phi-3-vision/ov_phi3_vision.py @@ -0,0 +1,532 @@ +from pathlib import Path +import types +from typing import Optional, Tuple, Union +import gc +import openvino as ov +import torch +from transformers import AutoModelForCausalLM +from transformers import AutoProcessor +from transformers.generation import GenerationConfig, GenerationMixin +from transformers.modeling_outputs import CausalLMOutputWithPast, BaseModelOutputWithPast +from transformers import AutoConfig + +from typing import Optional, Tuple, List +from openvino.runtime import opset13 +import numpy as np +import nncf + + +def model_has_state(ov_model: ov.Model): + return len(ov_model.get_sinks()) > 0 + + +def model_has_input_output_name(ov_model: ov.Model, name: str): + """ + Helper function for checking that model has specified input or output name + + Parameters: + ov_model (ov.Model): + name (str): + name of input or output + + Returns: + True if input or output with requested name exists else False + """ + return name in sum([list(t.get_names()) for t in ov_model.inputs + ov_model.outputs], []) + + +def fuse_cache_reorder( + ov_model: ov.Model, + not_kv_inputs: List[str], + key_value_input_names: List[str], + gather_dim: int, +): + """ + Fuses reored_cache during generate cycle into ov.Model. Used with stateful models, because we can not modify model state directly. + + Adds a new beam_idx parameter and Gather op per each kv-cache input in a given model. + Should be run before make_stateful. Implements optimumum's _reorder_cache + inside the model in the beginning of each iteration. + Gather works along given gather_dim dimension that may vary from model to model. + KV-cache inputs are identified based on names in key_value_input_names. + Append the new beam_idx parameter to not_kv_inputs. + + Parameters: + ov_model (`ov.Model`): + openvino model for processing + not_kv_inputs (`List[str]`): + list of input nodes in model that not related to past key values + key_value_input_names (`List[str]`): + list of names for key value input layers + gather_dim (int): + dimension for gathering cache during reorder pass + """ + + if model_has_input_output_name(ov_model, "beam_idx"): + raise ValueError("Model already has fused cache") + input_batch = ov_model.input("inputs_embeds").get_partial_shape()[0] + beam_idx = opset13.parameter(name="beam_idx", dtype=ov.Type.i32, shape=ov.PartialShape([input_batch])) + beam_idx.output(0).get_tensor().add_names({"beam_idx"}) # why list is not accepted? + ov_model.add_parameters([beam_idx]) + not_kv_inputs.append(ov_model.inputs[-1]) + # Go over all cache parameters and fuse _reorder_cache with indices provided by the new parameter beam_idx + for input_name in key_value_input_names: + parameter_output_port = ov_model.input(input_name) + consumers = parameter_output_port.get_target_inputs() + gather = opset13.gather(parameter_output_port, beam_idx, opset13.constant(gather_dim)) + for consumer in consumers: + consumer.replace_source_output(gather.output(0)) + ov_model.validate_nodes_and_infer_types() + + +def build_state_initializer(ov_model: ov.Model, batch_dim: int): + """ + Build initialization ShapeOf Expression for all ReadValue ops + + Parameters: + ov_model (ov.Model): + openvino model + batch_dim (int): + index of dimension corresponding to batch size + """ + input_ids = ov_model.input("inputs_embeds") + batch = opset13.gather( + opset13.shape_of(input_ids, output_type="i64"), + opset13.constant([0]), + opset13.constant(0), + ) + for op in ov_model.get_ops(): + if op.get_type_name() == "ReadValue": + dims = [dim.min_length for dim in list(op.get_output_partial_shape(0))] + dims[batch_dim] = batch + dims = [(opset13.constant(np.array([dim], dtype=np.int64)) if isinstance(dim, int) else dim) for dim in dims] + shape = opset13.concat(dims, axis=0) + broadcast = opset13.broadcast(opset13.constant(0.0, dtype=op.get_output_element_type(0)), shape) + op.set_arguments([broadcast]) + ov_model.validate_nodes_and_infer_types() + + +def make_stateful( + ov_model: ov.Model, + not_kv_inputs: List[str], + key_value_input_names: List[str], + key_value_output_names: List[str], + batch_dim: int, + num_attention_heads: int, + num_beams_and_batch: int = None, +): + """ + Hides kv-cache inputs and outputs inside the model as variables. + + Parameters: + ov_model (ov.Model): + openvino model + not_kv_inputs (`List[str]`): + list of input nodes in model that not related to past key values + key_value_input_names (`List[str]`): + list of names for key value input layers + key_value_output_names (`List[str]`): + list of names for key value input layers + batch_dim (int): + index of batch dimension in key value layers + num_attention_heads (int): + number of attention heads for batch dimension initialization + num_beams_an_batch (int): + precalculated number of beams and batch for shapes initialization + """ + from openvino._offline_transformations import apply_make_stateful_transformation + + input_output_map = {} + + if num_beams_and_batch is not None: + # Set batch size for input_ids and attention mask to avoid dynamic dimension got propagated from the end of the model back to ReadValue + for input in not_kv_inputs: + shape = input.get_partial_shape() + if shape.rank.get_length() <= 2: # == 1 for beam_index + shape[0] = num_beams_and_batch + input.get_node().set_partial_shape(shape) + for kv_name_pair in zip(key_value_input_names, key_value_output_names): + input_output_map[kv_name_pair[0]] = kv_name_pair[1] + if num_beams_and_batch is not None: + input = ov_model.input(kv_name_pair[0]) + shape = input.get_partial_shape() + shape[batch_dim] = num_beams_and_batch * num_attention_heads + input.get_node().set_partial_shape(shape) + + if num_beams_and_batch is not None: + # Re-validation model if shapes are altered above + ov_model.validate_nodes_and_infer_types() + + apply_make_stateful_transformation(ov_model, input_output_map) + if num_beams_and_batch is None: + build_state_initializer(ov_model, batch_dim) + + +def patch_stateful(ov_model): + key_value_input_names = [key.get_any_name() for key in ov_model.inputs[2:-1]] + key_value_output_names = [key.get_any_name() for key in ov_model.outputs[1:]] + not_kv_inputs = [input for input in ov_model.inputs if not any(name in key_value_input_names for name in input.get_names())] + if not key_value_input_names or not key_value_output_names: + return + batch_dim = 0 + num_attention_heads = 1 + + fuse_cache_reorder(ov_model, not_kv_inputs, key_value_input_names, batch_dim) + make_stateful( + ov_model, + not_kv_inputs, + key_value_input_names, + key_value_output_names, + batch_dim, + num_attention_heads, + None, + ) + + +core = ov.Core() + +def cleanup_torchscript_cache(): + """ + Helper for removing cached model representation + """ + torch._C._jit_clear_class_registry() + torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore() + torch.jit._state._clear_class_state() + + +def convert_phi3_model(model_id, output_dir, quantization_config): + output_dir = Path(output_dir) + + lang_model_path = output_dir / "language_model.xml" + image_embed_path = output_dir / "image_embed.xml" + img_projection_path = output_dir / "img_projection.xml" + embed_token_path = output_dir / "embed_token.xml" + + if all([lang_model_path.exists(), image_embed_path.exists(), img_projection_path.exists(), embed_token_path.exists()]): + return + model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, _attn_implementation="eager") + processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True) + model.config.save_pretrained(output_dir) + processor.save_pretrained(output_dir) + + if not embed_token_path.exists(): + ov_model = ov.convert_model(model.model.embed_tokens, example_input=torch.ones([2, 2], dtype=torch.int64)) + ov.save_model(ov_model, embed_token_path) + del ov_model + cleanup_torchscript_cache() + gc.collect() + + vision_embed_tokens = model.model.vision_embed_tokens + if not image_embed_path.exists(): + vision_embed_tokens.forward = vision_embed_tokens.get_img_features + ov_model = ov.convert_model(vision_embed_tokens, example_input=torch.ones([17, 3, 336, 336])) + ov.save_model(ov_model, image_embed_path) + del ov_model + cleanup_torchscript_cache() + gc.collect() + + + if not img_projection_path.exists(): + ov_model = ov.convert_model(vision_embed_tokens.img_projection, example_input=torch.ones([1, 1921, 4096])) + ov.save_model(ov_model, img_projection_path) + del ov_model + cleanup_torchscript_cache() + gc.collect() + + if not lang_model_path.exists(): + def forward_wrap(self, attention_mask, position_ids=None, past_key_values=None, inputs_embeds=None): + result = self._orig_forward( + input_ids=None, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds + ) + return tuple(result.values()) + + model._orig_forward = model.forward + model.forward = types.MethodType(forward_wrap, model) + llm_input = torch.zeros([2, 2, 3072]) + pkv = model(inputs_embeds=llm_input, attention_mask=torch.ones((2, 2), dtype=torch.int64))[1] + model_inputs = ["attention_mask", "position_ids"] + model_outputs = ["logits"] + for idx in range(len(pkv)): + model_inputs.extend([f"past_key_values.{idx}.key", f"past_key_values.{idx}.value"]) + model_outputs.extend([f"present.{idx}.key", f"present.{idx}.value"]) + model_inputs.append("inputs_embeds") + position_ids = torch.tensor([[2, 3], [2, 3]]) + ov_model = ov.convert_model( + model, + example_input={ + "inputs_embeds": llm_input, + "attention_mask": torch.ones([2, 4], dtype=torch.int64), + "past_key_values": pkv, + "position_ids": position_ids, + }, + ) + + for input, input_name in zip(ov_model.inputs, model_inputs): + input.get_tensor().set_names({input_name}) + + for output, output_name in zip(ov_model.outputs, model_outputs): + output.get_tensor().set_names({output_name}) + patch_stateful(ov_model) + + if quantization_config is not None: + ov_model = nncf.compress_weights(ov_model, **quantization_config) + + ov.save_model(ov_model, lang_model_path) + del ov_model + cleanup_torchscript_cache() + del model + gc.collect() + + +class OvPhi3Vision(GenerationMixin): + def __init__(self, model_dir, device): + model_dir = Path(model_dir) + self.model = core.read_model(model_dir / "language_model.xml") + self.image_embed = core.compile_model(model_dir / "image_embed.xml", device) + self.img_projection = core.compile_model(model_dir / "img_projection.xml", device) + self.embed_tokem = core.compile_model(model_dir / "embed_token.xml", device) + self.input_names = {key.get_any_name(): idx for idx, key in enumerate(self.model.inputs)} + self.output_names = {key.get_any_name(): idx for idx, key in enumerate(self.model.outputs)} + compiled_model = core.compile_model(self.model, device) + self.request = compiled_model.create_infer_request() + self.config = AutoConfig.from_pretrained(model_dir, trust_remote_code=True) + self.generation_config = GenerationConfig.from_model_config(self.config) + self.main_input_name = "input_ids" + self.device = torch.device("cpu") + self.num_pkv = 2 + self._supports_cache_class = False + self.next_beam_idx = None + self._past_length = None + self.hd_transform_order = 'glb_sub' + self.num_img_tokens = self.config.img_processor['num_img_tokens'] + self.image_dim_out = self.config.img_processor['image_dim_out'] + self.glb_GN = torch.zeros([1, 1, self.image_dim_out * 4]) + self.sub_GN = torch.zeros([1, 1, 1, self.image_dim_out * 4]) + + def can_generate(self): + """Returns True to validate the check that the model using `GenerationMixin.generate()` can indeed generate.""" + return True + + def __call__( + self, + input_ids: torch.LongTensor, + pixel_values: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + position_ids: Optional[torch.LongTensor] = None, + image_sizes=None, + **kwargs, + ) -> CausalLMOutputWithPast: + return self.forward( + input_ids=input_ids, + pixel_values=pixel_values, + attention_mask=attention_mask, + past_key_values=past_key_values, + position_ids=position_ids, + image_sizes=image_sizes, + **kwargs, + ) + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + pixel_values: Optional[torch.FloatTensor] = None, + image_sizes: Optional[torch.LongTensor] = None, + **kwargs + ) -> Union[Tuple, BaseModelOutputWithPast]: + if inputs_embeds is None: + if pixel_values is not None and image_sizes is not None: + inputs_embeds = self.vision_embed_tokens(input_ids, pixel_values=pixel_values, image_sizes=image_sizes) + else: + inputs_embeds = self.embed_token(input_ids)[0] + if past_key_values is None: + self.request.reset_state() + self.next_beam_idx = np.arange(inputs_embeds.shape[0], dtype=int) + self._past_length = 0 + inputs = {} + inputs["inputs_embeds"] = inputs_embeds + inputs["attention_mask"] = attention_mask + inputs["position_ids"] = position_ids + if "beam_idx" in self.input_names: + inputs["beam_idx"] = self.next_beam_idx if self.next_beam_idx is not None else np.arange(inputs_embeds.shape[0], dtype=int) + self.request.start_async(inputs, share_inputs=True) + self.request.wait() + logits = self.request.get_tensor("logits").data + logits = torch.from_numpy(logits).to(self.device) + past_key_values = ((),) + self._past_length += inputs["inputs_embeds"].shape[1] + + return CausalLMOutputWithPast(logits=logits, past_key_values=past_key_values) + + def _reorder_cache(self, past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]: + """ + This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or + [`~PreTrainedModel.beam_sample`] is called. + This is required to match `past_key_values` with the correct beam_idx at every generation step. + """ + self.next_beam_idx = np.array(beam_idx) # save beam_idx to be used as an input in the next iteration + return past_key_values + + def _get_past_length(self, past_key_values=None): + if past_key_values is None: + return 0 + return self._past_length + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, pixel_values=None, image_sizes=None, **kwargs + ): + if past_key_values is not None: + past_length = self._get_past_length(past_key_values) + + # Keep only the unprocessed tokens: + # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where + # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as + # input) + if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: + input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] + # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard + # input_ids based on the past_length. + elif past_length < input_ids.shape[1]: + input_ids = input_ids[:, past_length:] + + position_ids = kwargs.get("position_ids", None) + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -input_ids.shape[1] :] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "position_ids": position_ids, + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + "pixel_values": pixel_values, + "image_sizes": image_sizes, + }) + return model_inputs + + def vision_embed_tokens(self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_sizes=None) -> torch.FloatTensor: + + MAX_INPUT_ID = int(1e9) + img_embeds = pixel_values + img_sizes = image_sizes + + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + + with torch.no_grad(): + positions = torch.nonzero((input_ids < 0) & (input_ids > -MAX_INPUT_ID), as_tuple=False) + + select = False + if len(positions.tolist()) > 0: + g_values = abs(input_ids[positions[:, 0], positions[:, 1]]) + + if img_sizes is not None and len(img_sizes): + hd_transform = True + bs = img_embeds.shape[0] + # Nx(HW)xC + img_features = torch.from_numpy(self.image_embed(img_embeds.flatten(0, 1))[0]) + base_feat_height = base_feat_width = int(img_features.shape[1] ** 0.5) + + # bs x max_num_crops x (24x24) x C + img_features = img_features.view(bs, -1, base_feat_height * base_feat_width, self.image_dim_out) + C = self.image_dim_out + H = base_feat_height + + output_imgs = [] + output_len = [] + # training is tensor, inference is list + if isinstance(img_sizes, torch.Tensor): + img_sizes = img_sizes.view(-1, 2) + for _bs in range(bs): + h, w = img_sizes[_bs] + h = h // 336 + w = w // 336 + B_ = h * w + + # 1 x (24x24) x 1024 + global_img_feature = img_features[_bs, :1] + + # 1 x 12 x 12 x 4096 + glb_img = global_img_feature.reshape(1,H,H,C).reshape(1,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(1,H//2,H//2,4*C).contiguous() + temp_glb_GN = self.sub_GN.repeat(1, H//2, 1, 1) + + # 1 x 156 x 4096 + glb_img = torch.cat([glb_img, temp_glb_GN], dim=2).reshape(1,-1,4*C) + + # (max_num_crops-1) x (12x12) x C + sub_img = img_features[_bs, 1:] + # 16x574x1024 + # get rid of padding sub_img + sub_img = sub_img[:B_] + + # (num_crops, 12, 2, 12, 2, 1024) -> (num_crops, 12, 12, 2, 2, 1024) -> (num_crops, 12*12, 4*1024) + sub_img = sub_img.reshape(B_,H,H,C).reshape(B_,H//2,2,H//2,2,C).contiguous().permute(0,1,3,2,4,5).reshape(B_,-1,4*C).contiguous() + sub_img = sub_img.reshape(1, h, w, 12, 12, -1).permute(0,1,3,2,4,5).reshape(1,h*12,w*12,4*C) + temp_sub_GN = self.sub_GN.repeat(1, h*12, 1, 1) + sub_img = torch.cat([sub_img, temp_sub_GN], dim=2).reshape(1,-1,4*C) + # (1, num_img_tokens, 1024*4) + + # glb + sub + if self.hd_transform_order == 'glb_sub': + output_imgs.append(torch.cat([glb_img, self.glb_GN, sub_img], dim=1)) + elif self.hd_transform_order == 'sub_glb': + output_imgs.append(torch.cat([sub_img, self.glb_GN, glb_img], dim=1)) + else: + raise NotImplementedError(f'hd_transform_order = {self.hd_transform_order}, not implemented') + + temp_len = int((h*w+1)*144 + 1 + (h+1)*12) + output_len.append(temp_len) + + num_img_tokens = output_len + img_set_tensor = [] + for _output_img in output_imgs: + img_feature_proj = torch.from_numpy(self.img_projection(_output_img)[0]) + img_set_tensor.append(img_feature_proj) + elif img_embeds.ndim == 4: + selected_g_values = g_values[::self.num_img_tokens] + tt = self.image_embed(img_embeds).reshape(-1, self.image_dim_out)[0] + img_set_tensor = torch.from_numpy(self.img_projection(tt)[0]) # adapted visual features. + elif img_embeds.ndim == 3: + selected_g_values = g_values[::self.num_img_tokens] + tt = ( + img_embeds.view(-1, self.image_dim_out) + ) + img_set_tensor = torch.from_numpy(self.img_projection(tt)[0]) # adapted visual features. + else: + raise NotImplementedError + select = True + input_ids.clamp_min_(0).clamp_max_(self.config.vocab_size) + + hidden_states = torch.from_numpy(self.embed_tokem(input_ids)[0]) + if select: + if hd_transform: + idx = 0 + for i, cnt in enumerate(num_img_tokens): + hidden_states[positions[idx, 0], positions[idx, 1] : positions[idx, 1] + cnt] = ( + img_set_tensor[i] + ) + idx += cnt + else: + idx = 0 + for i, g in enumerate(selected_g_values): + cnt = self.num_img_tokens + hidden_states[positions[idx, 0], positions[idx, 1] : positions[idx, 1] + cnt] = ( + img_set_tensor[i * cnt : (i + 1) * cnt] + ) + idx += cnt + + return hidden_states \ No newline at end of file diff --git a/notebooks/phi-3-vision/phi-3-vision.ipynb b/notebooks/phi-3-vision/phi-3-vision.ipynb new file mode 100644 index 00000000000..f97332ca6c5 --- /dev/null +++ b/notebooks/phi-3-vision/phi-3-vision.ipynb @@ -0,0 +1,385 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "156802c2-dc0e-4618-8626-36c2cea04a4b", + "metadata": {}, + "source": [ + "## Visual-language assistant with Phi3-Vision and OpenVINO\n", + "\n", + "The [Phi-3-Vision-128K-Instruct](https://huggingface.co/microsoft/Phi-3-vision-128k-instruct) is a lightweight, state-of-the-art open multimodal model built upon datasets which include - synthetic data and filtered publicly available websites - with a focus on very high-quality, reasoning dense data both on text and vision. The model belongs to the Phi-3 model family, and the multimodal version comes with 128K context length (in tokens) it can support. The model underwent a rigorous enhancement process, incorporating both supervised fine-tuning and direct preference optimization to ensure precise instruction adherence and robust safety measures. More details about model can be found in [model blog post](https://azure.microsoft.com/en-us/blog/new-models-added-to-the-phi-3-family-available-on-microsoft-azure/), [technical report](https://aka.ms/phi3-tech-report), [Phi-3-cookbook](https://github.com/microsoft/Phi-3CookBook)\n", + "\n", + "In this tutorial we consider how to launch Phi-3-vision using OpenVINO for creation multimodal chatbot. Additionally, we optimize model to low precsion using [NNCF](https://github.com/openvinotoolkit/nncf)\n", + "#### Table of contents:\n", + "\n", + "- [Prerequisites](#Prerequisites)\n", + "- [Convert and Optimize model](#Convert-and-Optimize-model)\n", + " - [Compress model weights to 4-bit](#Compress-model-weights-to-4-bit)\n", + "- [Select inference device](#Select-inference-device)\n", + "- [Run OpenVINO model](#Run-OpenVINO-model)\n", + "- [Interactive demo](#Interactive-demo)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "e33c16be-c8da-4c28-81c8-05da62bf7a43", + "metadata": {}, + "source": [ + "## Prerequisites\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "install required packages and setup helper functions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e786566c-c085-4d10-bb79-cbd52b79adae", + "metadata": {}, + "outputs": [], + "source": [ + "%pip install -q \"torch>=2.1\" \"transformers>=4.40\" \"gradio>=4.26\" \"Pillow\" \"accelerate\" \"tqdm\" --extra-index-url https://download.pytorch.org/whl/cpu\n", + "%pip install -q \"openvino>=2024.2.0\" \"nncf>=2.11.0\"" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "c2f0d0ee-a9dc-4e83-927b-488b9aa5ced0", + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "from pathlib import Path\n", + "\n", + "if not Path(\"ov_phi3_vision.py\").exists():\n", + " r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/phi-3-vision/ov_phi3_vision.py\")\n", + " open(\"ov_phi3_vision.py\", \"w\").write(r.text)\n", + " \n", + "\n", + "if not Path(\"gradio_helper.py\").exists():\n", + " r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/phi-3-vision/gradio_helper.py\")\n", + " open(\"gradio_helper.py\", \"w\").write(r.text)" + ] + }, + { + "cell_type": "markdown", + "id": "9c04fc64-d0c4-4de2-9a26-b6ae80e77026", + "metadata": {}, + "source": [ + "## Convert and Optimize model\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "Phi-3-vision is PyTorch model. OpenVINO supports PyTorch models via conversion to OpenVINO Intermediate Representation (IR). [OpenVINO model conversion API](https://docs.openvino.ai/2024/openvino-workflow/model-preparation.html#convert-a-model-with-python-convert-model) should be used for these purposes. `ov.convert_model` function accepts original PyTorch model instance and example input for tracing and returns `ov.Model` representing this model in OpenVINO framework. Converted model can be used for saving on disk using `ov.save_model` function or directly loading on device using `core.complie_model`. \n", + "`ov_phi3_model.py` script contains helper function for model conversion, please check its content if you interested in conversion details.\n", + "\n", + "
\n", + " Click here for more detailed explanation of conversion steps\n", + "Phi-3-vision is autoregressive transformer generative model, it means that each next model step depends from model output from previous step. The generation approach is based on the assumption that the probability distribution of a word sequence can be decomposed into the product of conditional next word distributions. In other words, model predicts the next token in the loop guided by previously generated tokens until the stop-condition will be not reached (generated sequence of maximum length or end of string token obtained). The way the next token will be selected over predicted probabilities is driven by the selected decoding methodology. You can find more information about the most popular decoding methods in this [blog](https://huggingface.co/blog/how-to-generate). The entry point for the generation process for models from the Hugging Face Transformers library is the `generate` method. You can find more information about its parameters and configuration in the [documentation](https://huggingface.co/docs/transformers/v4.26.1/en/main_classes/text_generation#transformers.GenerationMixin.generate). To preserve flexibility in the selection decoding methodology, we will convert only model inference for one step.\n", + "\n", + "The inference flow has difference on first step and for the next. On the first step, model accept preprocessed input instruction and image, that transformed to the unified embedding space using `input_embedding` and `image_encoder` models, after that `language model`, LLM-based part of model, runs on input embeddings to predict probability of next generated tokens. On the next step, `language_model` accepts only next token id selected based on sampling strategy and processed by `input_embedding` model and cached attention key and values. Since the output side is auto-regressive, an output token hidden state remains the same once computed for every further generation step. Therefore, recomputing it every time you want to generate a new token seems wasteful. With the cache, the model saves the hidden state once it has been computed. The model only computes the one for the most recently generated output token at each time step, re-using the saved ones for hidden tokens. This reduces the generation complexity from $O(n^3)$ to $O(n^2)$ for a transformer model. More details about how it works can be found in this [article](https://scale.com/blog/pytorch-improvements#Text%20Translation). For improving support images of varaious resolution, input image splitted on patches and processed by `image feature extractor` and `imgae projector` that are part of image encoder.\n", + "\n", + "To sum up above, model consists of 4 parts:\n", + "\n", + "* **Image feature extractor** and **Image projector** for encoding input images into embedding space.\n", + "* **Input Embedding** for conversion input text tokens into embedding space\n", + "* **Language Model** for generation answer based on input embeddings provided by Image Encoder and Input Embedding models.\n", + "\n", + "
\n", + "\n", + "\n", + "### Compress model weights to 4-bit\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "For reducing memory consumption, weights compression optimization can be applied using [NNCF](https://github.com/openvinotoolkit/nncf). \n", + "\n", + "
\n", + " Click here for more details about weight compression\n", + "Weight compression aims to reduce the memory footprint of a model. It can also lead to significant performance improvement for large memory-bound models, such as Large Language Models (LLMs). LLMs and other models, which require extensive memory to store the weights during inference, can benefit from weight compression in the following ways:\n", + "\n", + "* enabling the inference of exceptionally large models that cannot be accommodated in the memory of the device;\n", + "\n", + "* improving the inference performance of the models by reducing the latency of the memory access when computing the operations with weights, for example, Linear layers.\n", + "\n", + "[Neural Network Compression Framework (NNCF)](https://github.com/openvinotoolkit/nncf) provides 4-bit / 8-bit mixed weight quantization as a compression method primarily designed to optimize LLMs. The main difference between weights compression and full model quantization (post-training quantization) is that activations remain floating-point in the case of weights compression which leads to a better accuracy. Weight compression for LLMs provides a solid inference performance improvement which is on par with the performance of the full model quantization. In addition, weight compression is data-free and does not require a calibration dataset, making it easy to use.\n", + "\n", + "`nncf.compress_weights` function can be used for performing weights compression. The function accepts an OpenVINO model and other compression parameters. Compared to INT8 compression, INT4 compression improves performance even more, but introduces a minor drop in prediction quality.\n", + "\n", + "More details about weights compression, can be found in [OpenVINO documentation](https://docs.openvino.ai/2024/openvino-workflow/model-optimization-guide/weight-compression.html).\n", + "
" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "7efafbc8", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "2024-07-16 22:48:20.553025: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n", + "2024-07-16 22:48:20.554842: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n", + "2024-07-16 22:48:20.591401: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n", + "2024-07-16 22:48:20.592630: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n", + "To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n", + "2024-07-16 22:48:21.277744: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n" + ] + } + ], + "source": [ + "from pathlib import Path\n", + "import nncf\n", + "from ov_phi3_vision import convert_phi3_model\n", + "\n", + "\n", + "model_id = \"microsoft/Phi-3-vision-128k-instruct\"\n", + "out_dir = Path(\"model/INT4\")\n", + "compression_configuration = {\n", + " \"mode\": nncf.CompressWeightsMode.INT4_SYM,\n", + " \"group_size\": 64,\n", + " \"ratio\": 0.6,\n", + "}\n", + "convert_phi3_model(model_id, out_dir, compression_configuration)" + ] + }, + { + "cell_type": "markdown", + "id": "1b6c3845-3008-4517-9cc5-5360b54fe7c6", + "metadata": {}, + "source": [ + "## Select inference device\n", + "[back to top ⬆️](#Table-of-contents:)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "881cfdca", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "d4422ae78d5245c2a437f0e8d899cdbb", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Dropdown(description='Device:', options=('CPU', 'GPU.0', 'GPU.1', 'AUTO'), value='CPU')" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import openvino as ov\n", + "import ipywidgets as widgets\n", + "\n", + "core = ov.Core()\n", + "\n", + "support_devices = core.available_devices\n", + "if \"NPU\" in support_devices:\n", + " support_devices.remove(\"NPU\")\n", + "\n", + "device = widgets.Dropdown(\n", + " options=support_devices + [\"AUTO\"],\n", + " value=\"CPU\",\n", + " description=\"Device:\",\n", + " disabled=False,\n", + ")\n", + "\n", + "device" + ] + }, + { + "cell_type": "markdown", + "id": "36ae95c1-bfac-4898-a759-8ad0aebfeb5e", + "metadata": {}, + "source": [ + "## Run OpenVINO model\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "`OvPhi3vison` class provides convinient way for running model. It accepts directory with converted model and inference device s arguments. For running model we will use `generate` method." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "22e6d173-1a44-4a40-a29d-186e4c1de60d", + "metadata": {}, + "outputs": [], + "source": [ + "from ov_phi3_vision import OvPhi3Vision\n", + "\n", + "model = OvPhi3Vision(out_dir, device.value)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "24d3eed7", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/transformers/models/auto/image_processing_auto.py:510: FutureWarning: The image_processor_class argument is deprecated and will be removed in v4.42. Please use `slow_image_processor_class`, or `fast_image_processor_class` instead\n", + " warnings.warn(\n", + "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The unusual aspect of this picture is the presence of a cat inside a cardboard box. Cats are known for their curiosity and playfulness, and they often find comfort in small, enclosed spaces. In this image, the cat is lying\n" + ] + } + ], + "source": [ + "import requests\n", + "from PIL import Image\n", + "from transformers import AutoProcessor, TextStreamer\n", + "\n", + "messages = [ \n", + " {\"role\": \"user\", \"content\": \"<|image_1|>\\nWhat is unusual on this picture?\"}, \n", + "] \n", + "\n", + "processor = AutoProcessor.from_pretrained(out_dir, trust_remote_code=True)\n", + "url = \"https://github.com/openvinotoolkit/openvino_notebooks/assets/29454499/d5fbbd1a-d484-415c-88cb-9986625b7b11\" \n", + "image = Image.open(requests.get(url, stream=True).raw) \n", + "\n", + "prompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n", + "\n", + "inputs = processor(prompt, [image], return_tensors=\"pt\")\n", + "\n", + "generation_args = { \n", + " \"max_new_tokens\": 50, \n", + " \"do_sample\": False,\n", + " \"streamer\": TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)\n", + "} \n", + "\n", + "generate_ids = model.generate(**inputs, eos_token_id=processor.tokenizer.eos_token_id, **generation_args) " + ] + }, + { + "cell_type": "markdown", + "id": "ba71ff7f-c48a-4644-99bd-7a60cdec05e6", + "metadata": {}, + "source": [ + "## Interactive demo\n", + "[back to top ⬆️](#Table-of-contents:)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "ba58378b", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Running on local URL: http://127.0.0.1:7860\n", + "IMPORTANT: You are using gradio version 4.26.0, however version 4.29.0 is available, please upgrade.\n", + "--------\n", + "\n", + "To create a public link, set `share=True` in `launch()`.\n" + ] + }, + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from gradio_helper import make_demo\n", + "\n", + "demo = make_demo(model, processor)\n", + "\n", + "try:\n", + " demo.launch(debug=True)\n", + "except Exception:\n", + " demo.launch(debug=True, share=True)\n", + "# if you are launching remotely, specify server_name and server_port\n", + "# demo.launch(server_name='your server name', server_port='server port in int')\n", + "# Read more in the docs: https://gradio.app/docs/" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.10" + }, + "openvino_notebooks": { + "imageUrl": "https://github.com/user-attachments/assets/a0c07db9-69d4-4dea-a8fc-424c02ccebf4", + "tags": { + "categories": [ + "Model Demos", + "AI Trends" + ], + "libraries": [], + "other": [], + "tasks": [ + "Visual Question Answering", + "Image-to-Text", + "Text Generation" + ] + } + }, + "widgets": { + "application/vnd.jupyter.widget-state+json": { + "state": {}, + "version_major": 2, + "version_minor": 0 + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}