|
| 1 | +# |
| 2 | +# Copyright 2016 The BigDL Authors. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | + |
| 17 | + |
| 18 | +from typing import List, Tuple, Optional, Union |
| 19 | +import math |
| 20 | +import timm |
| 21 | +import torch |
| 22 | +import torch.nn.functional as F |
| 23 | + |
| 24 | +# patched: `timm` has limited support for XPU backend, so we need to use CPU as a workaround |
| 25 | +def resample_abs_pos_embed( |
| 26 | + posemb: torch.Tensor, |
| 27 | + new_size: List[int], |
| 28 | + old_size: Optional[List[int]] = None, |
| 29 | + num_prefix_tokens: int = 1, |
| 30 | + interpolation: str = 'bicubic', |
| 31 | + antialias: bool = True, |
| 32 | + verbose: bool = False, |
| 33 | +): |
| 34 | + # sort out sizes, assume square if old size not provided |
| 35 | + num_pos_tokens = posemb.shape[1] |
| 36 | + num_new_tokens = new_size[0] * new_size[1] + num_prefix_tokens |
| 37 | + if num_new_tokens == num_pos_tokens and new_size[0] == new_size[1]: |
| 38 | + return posemb |
| 39 | + |
| 40 | + if old_size is None: |
| 41 | + hw = int(math.sqrt(num_pos_tokens - num_prefix_tokens)) |
| 42 | + old_size = hw, hw |
| 43 | + |
| 44 | + if num_prefix_tokens: |
| 45 | + posemb_prefix, posemb = posemb[:, :num_prefix_tokens], posemb[:, num_prefix_tokens:] |
| 46 | + else: |
| 47 | + posemb_prefix, posemb = None, posemb |
| 48 | + |
| 49 | + # do the interpolation |
| 50 | + embed_dim = posemb.shape[-1] |
| 51 | + orig_dtype = posemb.dtype |
| 52 | + posemb = posemb.float() # interpolate needs float32 |
| 53 | + posemb = posemb.reshape(1, old_size[0], old_size[1], -1).permute(0, 3, 1, 2) |
| 54 | + #posemb = F.interpolate(posemb, size=new_size, mode=interpolation, antialias=antialias) |
| 55 | + posemb = F.interpolate(posemb.to("cpu"), size=new_size, mode=interpolation, antialias=antialias).to(posemb.device) |
| 56 | + posemb = posemb.permute(0, 2, 3, 1).reshape(1, -1, embed_dim) |
| 57 | + posemb = posemb.to(orig_dtype) |
| 58 | + |
| 59 | + # add back extra (class, etc) prefix tokens |
| 60 | + if posemb_prefix is not None: |
| 61 | + posemb = torch.cat([posemb_prefix, posemb], dim=1) |
| 62 | + |
| 63 | + if not torch.jit.is_scripting() and verbose: |
| 64 | + _logger.info(f'Resized position embedding: {old_size} to {new_size}.') |
| 65 | + |
| 66 | + return posemb |
| 67 | + |
| 68 | + |
| 69 | +def _pos_embed(self, x: torch.Tensor) -> torch.Tensor: |
| 70 | + if self.pos_embed is None: |
| 71 | + return x.view(x.shape[0], -1, x.shape[-1]) |
| 72 | + |
| 73 | + if self.dynamic_img_size: |
| 74 | + B, H, W, C = x.shape |
| 75 | + pos_embed = resample_abs_pos_embed( |
| 76 | + self.pos_embed, |
| 77 | + (H, W), |
| 78 | + num_prefix_tokens=0 if self.no_embed_class else self.num_prefix_tokens, |
| 79 | + ) |
| 80 | + x = x.view(B, -1, C) |
| 81 | + else: |
| 82 | + pos_embed = self.pos_embed |
| 83 | + |
| 84 | + to_cat = [] |
| 85 | + if self.cls_token is not None: |
| 86 | + to_cat.append(self.cls_token.expand(x.shape[0], -1, -1)) |
| 87 | + if self.reg_token is not None: |
| 88 | + to_cat.append(self.reg_token.expand(x.shape[0], -1, -1)) |
| 89 | + |
| 90 | + if self.no_embed_class: |
| 91 | + # deit-3, updated JAX (big vision) |
| 92 | + # position embedding does not overlap with class token, add then concat |
| 93 | + x = x + pos_embed |
| 94 | + if to_cat: |
| 95 | + x = torch.cat(to_cat + [x], dim=1) |
| 96 | + else: |
| 97 | + # original timm, JAX, and deit vit impl |
| 98 | + # pos_embed has entry for class token, concat then add |
| 99 | + if to_cat: |
| 100 | + x = torch.cat(to_cat + [x], dim=1) |
| 101 | + x = x + pos_embed |
| 102 | + |
| 103 | + return self.pos_drop(x) |
| 104 | + |
| 105 | + |
| 106 | +setattr(timm.models.VisionTransformer, "_pos_embed", _pos_embed) |
| 107 | + |
| 108 | +import os |
| 109 | +import time |
| 110 | +import argparse |
| 111 | +import requests |
| 112 | +from PIL import Image |
| 113 | +from ipex_llm.transformers import AutoModel |
| 114 | +from transformers import AutoTokenizer |
| 115 | + |
| 116 | + |
| 117 | +if __name__ == '__main__': |
| 118 | + parser = argparse.ArgumentParser(description='Predict Tokens using `generate()` API for openbmb/MiniCPM-V model') |
| 119 | + parser.add_argument('--repo-id-or-model-path', type=str, default="openbmb/MiniCPM-V", |
| 120 | + help='The huggingface repo id for the openbmb/MiniCPM-V model to be downloaded' |
| 121 | + ', or the path to the huggingface checkpoint folder') |
| 122 | + parser.add_argument('--image-url-or-path', type=str, |
| 123 | + default='http://farm6.staticflickr.com/5268/5602445367_3504763978_z.jpg', |
| 124 | + help='The URL or path to the image to infer') |
| 125 | + parser.add_argument('--prompt', type=str, default="What is in the image?", |
| 126 | + help='Prompt to infer') |
| 127 | + parser.add_argument('--n-predict', type=int, default=32, |
| 128 | + help='Max tokens to predict') |
| 129 | + |
| 130 | + args = parser.parse_args() |
| 131 | + model_path = args.repo_id_or_model_path |
| 132 | + image_path = args.image_url_or_path |
| 133 | + |
| 134 | + # Load model in 4 bit, |
| 135 | + # which convert the relevant layers in the model into INT4 format |
| 136 | + # When running LLMs on Intel iGPUs for Windows users, we recommend setting `cpu_embedding=True` in the from_pretrained function. |
| 137 | + # This will allow the memory-intensive embedding layer to utilize the CPU instead of iGPU. |
| 138 | + model = AutoModel.from_pretrained(model_path, |
| 139 | + load_in_4bit=True, |
| 140 | + optimize_model=False, |
| 141 | + trust_remote_code=True, |
| 142 | + modules_to_not_convert=["vpm", "resampler"], |
| 143 | + use_cache=True) |
| 144 | + model = model.float().to(device='xpu') |
| 145 | + tokenizer = AutoTokenizer.from_pretrained(model_path, |
| 146 | + trust_remote_code=True) |
| 147 | + model.eval() |
| 148 | + |
| 149 | + query = args.prompt |
| 150 | + if os.path.exists(image_path): |
| 151 | + image = Image.open(image_path).convert('RGB') |
| 152 | + else: |
| 153 | + image = Image.open(requests.get(image_path, stream=True).raw).convert('RGB') |
| 154 | + |
| 155 | + # Generate predicted tokens |
| 156 | + # here the prompt tuning refers to https://huggingface.co/openbmb/MiniCPM-V/blob/main/README.md |
| 157 | + msgs = [{'role': 'user', 'content': args.prompt}] |
| 158 | + st = time.time() |
| 159 | + res, context, _ = model.chat( |
| 160 | + image=image, |
| 161 | + msgs=msgs, |
| 162 | + context=None, |
| 163 | + tokenizer=tokenizer, |
| 164 | + sampling=True, |
| 165 | + temperature=0.7 |
| 166 | + ) |
| 167 | + end = time.time() |
| 168 | + print(f'Inference time: {end-st} s') |
| 169 | + print('-'*20, 'Input', '-'*20) |
| 170 | + print(image_path) |
| 171 | + print('-'*20, 'Prompt', '-'*20) |
| 172 | + print(args.prompt) |
| 173 | + output_str = res |
| 174 | + print('-'*20, 'Output', '-'*20) |
| 175 | + print(output_str) |
0 commit comments