Text Generation
Transformers
Safetensors
multilingual
phi3_v
nlp
code
vision
conversational
custom_code
Instructions to use microsoft/Phi-3-vision-128k-instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use microsoft/Phi-3-vision-128k-instruct with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="microsoft/Phi-3-vision-128k-instruct", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-vision-128k-instruct", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use microsoft/Phi-3-vision-128k-instruct with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "microsoft/Phi-3-vision-128k-instruct" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "microsoft/Phi-3-vision-128k-instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/microsoft/Phi-3-vision-128k-instruct
- SGLang
How to use microsoft/Phi-3-vision-128k-instruct with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "microsoft/Phi-3-vision-128k-instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "microsoft/Phi-3-vision-128k-instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "microsoft/Phi-3-vision-128k-instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "microsoft/Phi-3-vision-128k-instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use microsoft/Phi-3-vision-128k-instruct with Docker Model Runner:
docker model run hf.co/microsoft/Phi-3-vision-128k-instruct
Handle Batch Sizes (v0.2)
#32
by WilliamSotoM - opened
- processing_phi3_v.py +27 -12
processing_phi3_v.py
CHANGED
|
@@ -52,6 +52,7 @@ class Phi3VProcessor(ProcessorMixin):
|
|
| 52 |
def __init__(self, image_processor, tokenizer):
|
| 53 |
self.image_processor = image_processor
|
| 54 |
self.tokenizer = tokenizer
|
|
|
|
| 55 |
self.num_img_tokens = image_processor.num_img_tokens
|
| 56 |
self.img_tokens = [f"<|image_{i+1}|>" for i in range(1000000)]
|
| 57 |
|
|
@@ -73,9 +74,7 @@ class Phi3VProcessor(ProcessorMixin):
|
|
| 73 |
|
| 74 |
Args:
|
| 75 |
text (`str`, `List[str]`, `List[List[str]]`):
|
| 76 |
-
The sequence or batch of sequences to be encoded. Each sequence
|
| 77 |
-
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 78 |
-
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 79 |
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 80 |
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 81 |
tensor. Both channels-first and channels-last formats are supported.
|
|
@@ -150,7 +149,15 @@ class Phi3VProcessor(ProcessorMixin):
|
|
| 150 |
return BatchFeature(data={**model_inputs})
|
| 151 |
|
| 152 |
pattern = r"<\|image_\d+\|>"
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
if 'num_img_tokens' in images:
|
| 156 |
num_img_tokens = images['num_img_tokens']
|
|
@@ -162,30 +169,38 @@ class Phi3VProcessor(ProcessorMixin):
|
|
| 162 |
images, image_sizes = images['pixel_values'], images['image_sizes']
|
| 163 |
|
| 164 |
# image_tags needs to start from 1 to n
|
| 165 |
-
image_tags = re.findall(pattern, texts)
|
| 166 |
# image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]
|
| 167 |
# image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]
|
| 168 |
-
image_ids = [int(s.split("|")[1].split("_")[-1]) for s in image_tags]
|
| 169 |
-
unique_image_ids = sorted(list(set(image_ids)))
|
| 170 |
# image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]
|
| 171 |
# check the condition
|
| 172 |
assert unique_image_ids == list(range(1, len(unique_image_ids)+1)), f"image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be {unique_image_ids}"
|
| 173 |
# total images must be the same as the number of image tags
|
| 174 |
assert len(unique_image_ids) == len(images), f"total images must be the same as the number of image tags, got {len(unique_image_ids)} image tags and {len(images)} images"
|
| 175 |
|
| 176 |
-
image_ids_pad = [[-iid]*num_img_tokens[iid-1] for iid in image_ids]
|
| 177 |
|
| 178 |
def insert_separator(X, sep_list):
|
| 179 |
if len(X) > len(sep_list):
|
| 180 |
sep_list.append([])
|
| 181 |
return [ele for sublist in zip(X, sep_list) for ele in sublist]
|
| 182 |
input_ids = []
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
|
| 188 |
attention_mask = (input_ids > -1000000).to(torch.long)
|
|
|
|
| 189 |
|
| 190 |
return BatchFeature(data={"input_ids": input_ids,
|
| 191 |
"attention_mask": attention_mask,
|
|
@@ -214,4 +229,4 @@ class Phi3VProcessor(ProcessorMixin):
|
|
| 214 |
def model_input_names(self):
|
| 215 |
tokenizer_input_names = self.tokenizer.model_input_names
|
| 216 |
image_processor_input_names = self.image_processor.model_input_names
|
| 217 |
-
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
|
|
|
| 52 |
def __init__(self, image_processor, tokenizer):
|
| 53 |
self.image_processor = image_processor
|
| 54 |
self.tokenizer = tokenizer
|
| 55 |
+
self.tokenizer.padding_side = 'left'
|
| 56 |
self.num_img_tokens = image_processor.num_img_tokens
|
| 57 |
self.img_tokens = [f"<|image_{i+1}|>" for i in range(1000000)]
|
| 58 |
|
|
|
|
| 74 |
|
| 75 |
Args:
|
| 76 |
text (`str`, `List[str]`, `List[List[str]]`):
|
| 77 |
+
The sequence or batch of sequences to be encoded. Each sequence must be a string.
|
|
|
|
|
|
|
| 78 |
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 79 |
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 80 |
tensor. Both channels-first and channels-last formats are supported.
|
|
|
|
| 149 |
return BatchFeature(data={**model_inputs})
|
| 150 |
|
| 151 |
pattern = r"<\|image_\d+\|>"
|
| 152 |
+
|
| 153 |
+
if isinstance(texts, str):
|
| 154 |
+
texts = [texts]
|
| 155 |
+
|
| 156 |
+
prompt_chunks = []
|
| 157 |
+
image_tags = []
|
| 158 |
+
for text in texts:
|
| 159 |
+
prompt_chunks.append([self.tokenizer(chunk).input_ids for chunk in re.split(pattern, text)])
|
| 160 |
+
image_tags.append(re.findall(pattern, text))
|
| 161 |
|
| 162 |
if 'num_img_tokens' in images:
|
| 163 |
num_img_tokens = images['num_img_tokens']
|
|
|
|
| 169 |
images, image_sizes = images['pixel_values'], images['image_sizes']
|
| 170 |
|
| 171 |
# image_tags needs to start from 1 to n
|
| 172 |
+
# image_tags = re.findall(pattern, texts)
|
| 173 |
# image_ids = [int(s.split("|")[1].split("_")[-1]) * -1 for s in image_tags]
|
| 174 |
# image_ids_pad = [[iid]*num_img_tokens[i] for i, iid in enumerate(image_ids)]
|
| 175 |
+
image_ids = [[int(s.split("|")[1].split("_")[-1]) for s in tags] for tags in image_tags]
|
| 176 |
+
unique_image_ids = sorted(list(set([iid for ids in image_ids for iid in ids])))
|
| 177 |
# image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be [1, 4, 5]
|
| 178 |
# check the condition
|
| 179 |
assert unique_image_ids == list(range(1, len(unique_image_ids)+1)), f"image_ids must start from 1, and must be continuous int, e.g. [1, 2, 3], cannot be {unique_image_ids}"
|
| 180 |
# total images must be the same as the number of image tags
|
| 181 |
assert len(unique_image_ids) == len(images), f"total images must be the same as the number of image tags, got {len(unique_image_ids)} image tags and {len(images)} images"
|
| 182 |
|
| 183 |
+
image_ids_pad = [[[-iid]*num_img_tokens[iid-1] for iid in ids] for ids in image_ids]
|
| 184 |
|
| 185 |
def insert_separator(X, sep_list):
|
| 186 |
if len(X) > len(sep_list):
|
| 187 |
sep_list.append([])
|
| 188 |
return [ele for sublist in zip(X, sep_list) for ele in sublist]
|
| 189 |
input_ids = []
|
| 190 |
+
for sub_prompt_chunks, sub_image_ids_pad in zip(prompt_chunks, image_ids_pad):
|
| 191 |
+
input_ids.append([])
|
| 192 |
+
offset = 0
|
| 193 |
+
for x in insert_separator(sub_prompt_chunks, sub_image_ids_pad):
|
| 194 |
+
input_ids[-1].extend(x[offset:])
|
| 195 |
+
|
| 196 |
+
max_length = max(len(ids) for ids in input_ids)
|
| 197 |
+
for i in range(len(input_ids)):
|
| 198 |
+
while len(input_ids[i]) < max_length:
|
| 199 |
+
input_ids[i] = [self.tokenizer.pad_token_id]+input_ids[i]
|
| 200 |
|
| 201 |
input_ids = torch.tensor(input_ids, dtype=torch.long).unsqueeze(0)
|
| 202 |
attention_mask = (input_ids > -1000000).to(torch.long)
|
| 203 |
+
attention_mask[input_ids == self.tokenizer.pad_token_id] = 0
|
| 204 |
|
| 205 |
return BatchFeature(data={"input_ids": input_ids,
|
| 206 |
"attention_mask": attention_mask,
|
|
|
|
| 229 |
def model_input_names(self):
|
| 230 |
tokenizer_input_names = self.tokenizer.model_input_names
|
| 231 |
image_processor_input_names = self.image_processor.model_input_names
|
| 232 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|