Skip to content

Commit deb92d6

Browse files
Fix PaliGemma labels for unpadded batches
1 parent e35e1a5 commit deb92d6

2 files changed

Lines changed: 20 additions & 3 deletions

File tree

‎src/transformers/models/paligemma/processing_paligemma.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,10 @@ def __call__(
127127
# NOTE: ideally users should build 'labels' with data collator, since we return token_type_ids.
128128
# Kept only for BC!
129129
if "token_type_ids" in result:
130-
labels = np.array(result["input_ids"])
131-
labels[np.array(result["token_type_ids"]) == 0] = -100
132-
result["labels"] = labels
130+
result["labels"] = [
131+
np.where(np.asarray(token_type_ids) == 0, -100, input_ids)
132+
for input_ids, token_type_ids in zip(result["input_ids"], result["token_type_ids"])
133+
]
133134

134135
return BatchFeature(data=result, tensor_type=return_tensors)
135136

‎tests/models/paligemma/test_processing_paligemma.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,22 @@ def test_call_with_suffix(self):
8383
self.assertTrue("labels" in inputs)
8484
self.assertEqual(len(inputs["labels"][0]), len(inputs["input_ids"][0]))
8585

86+
def test_unpadded_batch_with_suffix(self):
87+
processor = self.get_processor()
88+
images = self.prepare_images_inputs(batch_size=2)
89+
text = ["<image>Describe the image.", "<image>Describe the image in more detail."]
90+
suffix = ["A cat.", "A cat sitting on a wooden bench."]
91+
92+
inputs = processor(images=images, text=text, suffix=suffix)
93+
94+
self.assertNotEqual(len(inputs["input_ids"][0]), len(inputs["input_ids"][1]))
95+
for index in range(2):
96+
single = processor(images=images[index], text=text[index], suffix=suffix[index])
97+
self.assertEqual(inputs["input_ids"][index], single["input_ids"][0])
98+
self.assertEqual(list(inputs["labels"][index]), list(single["labels"][0]))
99+
self.assertIn(-100, inputs["labels"][index])
100+
self.assertTrue(any(label != -100 for label in inputs["labels"][index]))
101+
86102
def test_text_with_image_tokens(self):
87103
image_processor = self.get_component("image_processor")
88104
tokenizer = self.get_component("tokenizer")

0 commit comments

Comments
 (0)