davanstrien HF Staff commited on
Commit
519b9dc
·
verified ·
1 Parent(s): 3deed9d

Upload paddleocr-vl-1.5.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. paddleocr-vl-1.5.py +20 -40
paddleocr-vl-1.5.py CHANGED
@@ -9,7 +9,6 @@
9
  # "transformers>=5.0.0",
10
  # "accelerate",
11
  # "tqdm",
12
- # "toolz",
13
  # ]
14
  # ///
15
 
@@ -56,7 +55,6 @@ import torch
56
  from datasets import load_dataset
57
  from huggingface_hub import DatasetCard, login
58
  from PIL import Image
59
- from toolz import partition_all
60
  from tqdm.auto import tqdm
61
 
62
  logging.basicConfig(level=logging.INFO)
@@ -413,36 +411,24 @@ def main(
413
 
414
  logger.info(f"Model loaded on {next(model.parameters()).device}")
415
  max_pixels = MAX_PIXELS.get(task_mode, MAX_PIXELS["default"])
416
- logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
417
  logger.info(f"Image resizing: max_pixels={max_pixels:,} (handled by processor)")
418
 
419
- # Process images in batches
 
 
420
  all_outputs = []
421
 
422
- for batch_indices in tqdm(
423
- partition_all(batch_size, range(len(dataset))),
424
- total=(len(dataset) + batch_size - 1) // batch_size,
425
- desc=f"PaddleOCR-VL-1.5 {task_mode.upper()}",
426
- ):
427
- batch_indices = list(batch_indices)
428
- batch_images = [dataset[i][image_column] for i in batch_indices]
429
-
430
  try:
431
- # Prepare images and create messages
432
- processed_images = [prepare_image(img) for img in batch_images]
433
-
434
- # Create messages for batch
435
- batch_messages = [
436
- create_message(img, task_mode) for img in processed_images
437
- ]
438
 
439
- # Get max_pixels for image processing
440
- max_pixels = MAX_PIXELS.get(task_mode, MAX_PIXELS["default"])
441
-
442
- # Process with transformers batch inference
443
  inputs = processor.apply_chat_template(
444
- batch_messages,
445
- padding=True,
446
  add_generation_prompt=True,
447
  tokenize=True,
448
  return_dict=True,
@@ -455,7 +441,7 @@ def main(
455
  },
456
  ).to(model.device)
457
 
458
- # Generate outputs
459
  with torch.no_grad():
460
  outputs = model.generate(
461
  **inputs,
@@ -463,21 +449,15 @@ def main(
463
  do_sample=False,
464
  )
465
 
466
- # Decode outputs - skip input tokens
467
  input_len = inputs["input_ids"].shape[1]
468
- generated_ids = outputs[:, input_len:]
469
- results = processor.batch_decode(generated_ids, skip_special_tokens=True)
470
-
471
- # Add to outputs
472
- for text in results:
473
- all_outputs.append(text.strip())
474
 
475
  except Exception as e:
476
- logger.error(f"Error processing batch: {e}")
477
- # Add error placeholders for failed batch
478
- all_outputs.extend(
479
- [f"[{task_mode.upper()} ERROR: {str(e)[:100]}]"] * len(batch_images)
480
- )
481
 
482
  # Calculate processing time
483
  processing_duration = datetime.now() - start_time
@@ -656,8 +636,8 @@ Backend: Transformers batch inference (not vLLM)
656
  parser.add_argument(
657
  "--batch-size",
658
  type=int,
659
- default=8,
660
- help="Batch size for processing (default: 8)",
661
  )
662
  parser.add_argument(
663
  "--task-mode",
 
9
  # "transformers>=5.0.0",
10
  # "accelerate",
11
  # "tqdm",
 
12
  # ]
13
  # ///
14
 
 
55
  from datasets import load_dataset
56
  from huggingface_hub import DatasetCard, login
57
  from PIL import Image
 
58
  from tqdm.auto import tqdm
59
 
60
  logging.basicConfig(level=logging.INFO)
 
411
 
412
  logger.info(f"Model loaded on {next(model.parameters()).device}")
413
  max_pixels = MAX_PIXELS.get(task_mode, MAX_PIXELS["default"])
414
+ logger.info(f"Processing {len(dataset)} images (one at a time for stability)")
415
  logger.info(f"Image resizing: max_pixels={max_pixels:,} (handled by processor)")
416
 
417
+ # Process images one at a time
418
+ # Note: Batch processing with transformers VLMs can be unreliable,
419
+ # so we process individually for stability
420
  all_outputs = []
421
 
422
+ for i in tqdm(range(len(dataset)), desc=f"PaddleOCR-VL-1.5 {task_mode.upper()}"):
 
 
 
 
 
 
 
423
  try:
424
+ # Prepare image and create message
425
+ image = dataset[i][image_column]
426
+ pil_image = prepare_image(image)
427
+ messages = create_message(pil_image, task_mode)
 
 
 
428
 
429
+ # Process with transformers
 
 
 
430
  inputs = processor.apply_chat_template(
431
+ messages,
 
432
  add_generation_prompt=True,
433
  tokenize=True,
434
  return_dict=True,
 
441
  },
442
  ).to(model.device)
443
 
444
+ # Generate output
445
  with torch.no_grad():
446
  outputs = model.generate(
447
  **inputs,
 
449
  do_sample=False,
450
  )
451
 
452
+ # Decode output - skip input tokens
453
  input_len = inputs["input_ids"].shape[1]
454
+ generated_ids = outputs[0, input_len:]
455
+ result = processor.decode(generated_ids, skip_special_tokens=True)
456
+ all_outputs.append(result.strip())
 
 
 
457
 
458
  except Exception as e:
459
+ logger.error(f"Error processing image {i}: {e}")
460
+ all_outputs.append(f"[{task_mode.upper()} ERROR: {str(e)[:100]}]")
 
 
 
461
 
462
  # Calculate processing time
463
  processing_duration = datetime.now() - start_time
 
636
  parser.add_argument(
637
  "--batch-size",
638
  type=int,
639
+ default=1,
640
+ help="Batch size (currently ignored - images processed one at a time for stability)",
641
  )
642
  parser.add_argument(
643
  "--task-mode",