davanstrien HF Staff commited on
Commit
eb8edde
·
verified ·
1 Parent(s): 9c2126e

Sync from GitHub via hub-sync

Browse files
Files changed (1) hide show
  1. vlm-classify.py +126 -53
vlm-classify.py CHANGED
@@ -60,7 +60,7 @@ import logging
60
  import os
61
  import sys
62
  from collections import Counter
63
- from typing import List, Optional, Union, Dict, Any
64
 
65
  from PIL import Image
66
  from datasets import load_dataset
@@ -68,6 +68,9 @@ from huggingface_hub import login
68
  from toolz import partition_all
69
  from tqdm.auto import tqdm
70
 
 
 
 
71
  # torch and vllm are imported inside main(), so `uv run vlm-classify.py --help` works
72
  # without them. On HF Jobs they come from the vLLM image (see the header).
73
 
@@ -128,6 +131,60 @@ def create_classification_messages(
128
  ]
129
 
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  def main(
132
  input_dataset: str,
133
  output_dataset: str,
@@ -186,6 +243,10 @@ def main(
186
  dataset = dataset.select(range(min(max_samples, len(dataset))))
187
  logger.info(f"Limited to {len(dataset)} samples")
188
 
 
 
 
 
189
  # Log resizing configuration
190
  if max_size:
191
  logger.info(f"Image resizing enabled: max dimension = {max_size}px")
@@ -219,70 +280,84 @@ def main(
219
  structured_outputs=structured,
220
  )
221
 
222
- # Process images in batches to avoid memory issues
 
 
223
  logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
224
 
225
- all_classifications = []
 
226
 
227
- # Process in batches using lazy loading
228
  for batch_indices in tqdm(
229
  partition_all(batch_size, range(len(dataset))),
230
  total=(len(dataset) + batch_size - 1) // batch_size,
231
  desc="Classifying images",
232
  ):
233
- batch_indices = list(batch_indices)
234
-
235
- # Load only this batch's images
236
- batch_images = []
237
- valid_batch_indices = []
238
-
239
  for idx in batch_indices:
240
  try:
241
  image = dataset[idx][image_column]
242
- batch_images.append(image)
243
- valid_batch_indices.append(idx)
 
 
244
  except Exception as e:
245
- logger.warning(f"Skipping image at index {idx}: {e}")
246
- all_classifications.append(None)
247
 
248
- if not batch_images:
249
  continue
250
 
251
  try:
252
- # Create messages for just this batch
253
- batch_messages = [
254
- create_classification_messages(img, prompt, max_size=max_size)
255
- for img in batch_images
256
- ]
257
-
258
- # Process with vLLM
259
- outputs = llm.chat(
260
- messages=batch_messages,
261
- sampling_params=sampling_params,
262
- use_tqdm=False, # Already have outer progress bar
263
- )
264
-
265
- # Extract classifications
266
- for output in outputs:
267
- if output.outputs:
268
- label = output.outputs[0].text.strip()
269
- all_classifications.append(label)
270
- else:
271
- all_classifications.append(None)
272
- logger.warning("Empty output for an image")
273
-
274
  except Exception as e:
275
- logger.error(f"Error processing batch: {e}")
276
- # Add None for failed batch
277
- all_classifications.extend([None] * len(batch_images))
 
 
 
 
 
 
 
 
 
 
278
 
279
- # Ensure we have the right number of classifications
280
- while len(all_classifications) < len(dataset):
281
- all_classifications.append(None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
  # Add classifications to dataset
284
  logger.info("Adding classifications to dataset...")
285
- dataset = dataset.add_column("label", all_classifications[: len(dataset)])
286
 
287
  # Push to hub
288
  logger.info(f"Pushing to {output_dataset}...")
@@ -290,18 +365,16 @@ def main(
290
 
291
  # Print summary
292
  logger.info("Classification complete!")
293
- logger.info(f"Processed {len(all_classifications)} images")
294
  logger.info(f"Output dataset: {output_dataset}")
295
 
296
- # Show distribution of classifications
297
- label_counts = Counter(all_classifications)
298
  logger.info("Classification distribution:")
299
- for label, count in sorted(label_counts.items()):
300
- if label is not None: # Skip None values in summary
301
- percentage = (
302
- (count / len(all_classifications)) * 100 if all_classifications else 0
303
- )
304
- logger.info(f" {label}: {count} ({percentage:.1f}%)")
305
 
306
 
307
  if __name__ == "__main__":
 
60
  import os
61
  import sys
62
  from collections import Counter
63
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
64
 
65
  from PIL import Image
66
  from datasets import load_dataset
 
68
  from toolz import partition_all
69
  from tqdm.auto import tqdm
70
 
71
+ if TYPE_CHECKING:
72
+ from vllm import LLM, SamplingParams
73
+
74
  # torch and vllm are imported inside main(), so `uv run vlm-classify.py --help` works
75
  # without them. On HF Jobs they come from the vLLM image (see the header).
76
 
 
131
  ]
132
 
133
 
134
+ def classify_messages(
135
+ llm: "LLM", sampling_params: "SamplingParams", messages: List[List[Dict]]
136
+ ) -> List[Optional[str]]:
137
+ """Run one vLLM chat call; return one label per message (None for an empty output)."""
138
+ outputs = llm.chat(
139
+ messages=messages,
140
+ sampling_params=sampling_params,
141
+ use_tqdm=False, # Already have outer progress bar
142
+ )
143
+ if len(outputs) != len(messages):
144
+ raise RuntimeError(
145
+ f"vLLM returned {len(outputs)} outputs for {len(messages)} prompts"
146
+ )
147
+
148
+ labels = []
149
+ for output in outputs:
150
+ text = output.outputs[0].text.strip() if output.outputs else ""
151
+ labels.append(text or None)
152
+ return labels
153
+
154
+
155
+ def is_input_error(error: Exception) -> bool:
156
+ """True if one bad input caused the error, so retrying the other rows can help.
157
+
158
+ vLLM 0.32 raises VLLMValidationError for a bad request (for example a prompt
159
+ longer than --max-model-len); older vLLM and the multimodal processors raise
160
+ ValueError. Anything else (a dead engine, CUDA out of memory, a broken output
161
+ count) is not about one row and stops the run. The vLLM class is matched by
162
+ name so the script does not depend on where vLLM defines it.
163
+ """
164
+ names = {cls.__name__ for cls in type(error).__mro__}
165
+ return "VLLMValidationError" in names or isinstance(error, ValueError)
166
+
167
+
168
+ def classify_one_at_a_time(
169
+ llm: "LLM",
170
+ sampling_params: "SamplingParams",
171
+ rows: List[int],
172
+ messages: List[List[Dict]],
173
+ errors: Dict[int, str],
174
+ ) -> List[Optional[str]]:
175
+ """Retry a failed batch row by row. Record each failing row in errors."""
176
+ labels = []
177
+ for idx, row_messages in zip(rows, messages):
178
+ try:
179
+ labels.extend(classify_messages(llm, sampling_params, [row_messages]))
180
+ except Exception as e:
181
+ if not is_input_error(e):
182
+ raise
183
+ errors[idx] = str(e)
184
+ labels.append(None)
185
+ return labels
186
+
187
+
188
  def main(
189
  input_dataset: str,
190
  output_dataset: str,
 
243
  dataset = dataset.select(range(min(max_samples, len(dataset))))
244
  logger.info(f"Limited to {len(dataset)} samples")
245
 
246
+ if len(dataset) == 0:
247
+ logger.error(f"Split '{split}' of {input_dataset} has no rows to classify.")
248
+ sys.exit(1)
249
+
250
  # Log resizing configuration
251
  if max_size:
252
  logger.info(f"Image resizing enabled: max dimension = {max_size}px")
 
280
  structured_outputs=structured,
281
  )
282
 
283
+ # Process images in batches to avoid memory issues.
284
+ # labels[i] is the label for dataset row i; rows that fail keep None and get an
285
+ # entry in errors, so a failure can never shift labels onto other rows.
286
  logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
287
 
288
+ labels: List[Optional[str]] = [None] * len(dataset)
289
+ errors: Dict[int, str] = {}
290
 
 
291
  for batch_indices in tqdm(
292
  partition_all(batch_size, range(len(dataset))),
293
  total=(len(dataset) + batch_size - 1) // batch_size,
294
  desc="Classifying images",
295
  ):
296
+ # Load and encode only this batch's images. A row that cannot be loaded
297
+ # is recorded as failed and left out of the batch.
298
+ batch_rows = []
299
+ batch_messages = []
 
 
300
  for idx in batch_indices:
301
  try:
302
  image = dataset[idx][image_column]
303
+ batch_messages.append(
304
+ create_classification_messages(image, prompt, max_size=max_size)
305
+ )
306
+ batch_rows.append(idx)
307
  except Exception as e:
308
+ errors[idx] = f"could not load image: {e}"
 
309
 
310
+ if not batch_rows:
311
  continue
312
 
313
  try:
314
+ batch_labels = classify_messages(llm, sampling_params, batch_messages)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  except Exception as e:
316
+ # Stop on engine or runtime failures (see is_input_error): retrying
317
+ # them row by row would walk the rest of the dataset and push nulls.
318
+ if not is_input_error(e):
319
+ raise
320
+ # One bad input (for example an image whose prompt is longer than
321
+ # --max-model-len) fails the whole vLLM call, so retry the batch's
322
+ # rows one at a time and lose only the rows that fail on their own.
323
+ logger.warning(
324
+ f"Batch failed ({str(e)[:200]}); retrying its {len(batch_rows)} images one at a time"
325
+ )
326
+ batch_labels = classify_one_at_a_time(
327
+ llm, sampling_params, batch_rows, batch_messages, errors
328
+ )
329
 
330
+ for idx, label in zip(batch_rows, batch_labels):
331
+ labels[idx] = label
332
+ if label is None and idx not in errors:
333
+ errors[idx] = "empty model output"
334
+
335
+ # Report failures before pushing. If nothing was labelled, stop: an all-null
336
+ # label column looks like a finished dataset but holds no results.
337
+ labelled = sum(1 for label in labels if label is not None)
338
+ if errors:
339
+ all_failed = labelled == 0
340
+ log = logger.error if all_failed else logger.warning
341
+ if all_failed:
342
+ log(f"All {len(dataset)} images failed, so nothing was pushed. First errors:")
343
+ else:
344
+ log(
345
+ f"{len(errors)} of {len(dataset)} images have no label "
346
+ "(null in the 'label' column). First errors:"
347
+ )
348
+ for idx, message in list(errors.items())[:3]:
349
+ log(f" row {idx}: {message[:300]}")
350
+ if any("longer than the maximum model length" in m for m in errors.values()):
351
+ log(
352
+ "Some images need more tokens than --max-model-len allows: "
353
+ "set --max-size (for example 768) or raise --max-model-len."
354
+ )
355
+ if labelled == 0:
356
+ sys.exit(1)
357
 
358
  # Add classifications to dataset
359
  logger.info("Adding classifications to dataset...")
360
+ dataset = dataset.add_column("label", labels)
361
 
362
  # Push to hub
363
  logger.info(f"Pushing to {output_dataset}...")
 
365
 
366
  # Print summary
367
  logger.info("Classification complete!")
368
+ logger.info(f"Labelled {labelled} of {len(dataset)} images")
369
  logger.info(f"Output dataset: {output_dataset}")
370
 
371
+ # Show distribution of classifications, including rows with no label
372
+ label_counts = Counter(labels)
373
  logger.info("Classification distribution:")
374
+ for label, count in sorted(label_counts.items(), key=lambda item: str(item[0])):
375
+ percentage = (count / len(labels)) * 100 if labels else 0
376
+ name = label if label is not None else "(no label)"
377
+ logger.info(f" {name}: {count} ({percentage:.1f}%)")
 
 
378
 
379
 
380
  if __name__ == "__main__":