WilliamSotoM commited on
Commit
0798481
1 Parent(s): fea3f11

Handle Batch Sizes (v0.2)

Browse files

**Original Post (#29 v0.1)**
I hope I'm not overstepping boundaries. I tried the fix on #16 to handle batch sizes larger than 1 but stumbled upon a few issues. For example, issues processing single strings as the text input or not handling padding when the input texts are of different size.

I tried to address all the issues I had. Hope this can be of use.



@gugarosa

feel free to have a look and let me know if I'm overlooking something.

Best,
William

**Update (v0.2)**
Added `self.tokenizer.padding_side = 'left'` on line 59 to handle only-text inputs.

Files changed (1) hide show
  1. 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 can be a string or a list of strings
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
- prompt_chunks = [self.tokenizer(chunk).input_ids for chunk in re.split(pattern, texts)]
 
 
 
 
 
 
 
 
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
- offset = 0
184
- for x in insert_separator(prompt_chunks, image_ids_pad):
185
- input_ids.extend(x[offset:])
 
 
 
 
 
 
 
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))