test_molmo.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import unittest
  2. import pytest
  3. import requests
  4. from PIL import Image
  5. from transformers import (
  6. AutoModelForCausalLM,
  7. AutoProcessor,
  8. AutoTokenizer,
  9. GenerationConfig,
  10. )
  11. @pytest.mark.nonci
  12. class MolmoProcessorTest(unittest.TestCase):
  13. def test_molmo_demo(self):
  14. # load the processor
  15. processor = AutoProcessor.from_pretrained(
  16. "allenai/Molmo-7B-O-0924",
  17. trust_remote_code=True,
  18. torch_dtype="auto",
  19. )
  20. # load the model
  21. model = AutoModelForCausalLM.from_pretrained(
  22. "allenai/Molmo-7B-O-0924",
  23. trust_remote_code=True,
  24. torch_dtype="auto",
  25. )
  26. device = "cuda:0"
  27. model = model.to(device)
  28. # process the image and text
  29. inputs = processor.process(images=[Image.open(requests.get("https://picsum.photos/id/237/536/354", stream=True).raw)], text="Describe this image.")
  30. # move inputs to the correct device and make a batch of size 1
  31. inputs = {k: v.to(model.device).unsqueeze(0) for k, v in inputs.items()}
  32. print("Raw inputs")
  33. print(inputs)
  34. print("\nShapes")
  35. # {('input_ids', torch.Size([1, 589])), ('images', torch.Size([1, 5, 576, 588])), ('image_masks', torch.Size([1, 5, 576])), ('image_input_idx', torch.Size([1, 5, 144]))}
  36. print({(x, y.shape) for x, y in inputs.items()})
  37. print("\nTokens")
  38. print(processor.tokenizer.batch_decode(inputs["input_ids"]))
  39. # generate output; maximum 200 new tokens; stop generation when <|endoftext|> is generated
  40. output = model.generate_from_batch(inputs, GenerationConfig(max_new_tokens=200, stop_strings="<|endoftext|>"), tokenizer=processor.tokenizer)
  41. # only get generated tokens; decode them to text
  42. generated_tokens = output[0, inputs["input_ids"].size(1) :]
  43. generated_text = processor.tokenizer.decode(generated_tokens, skip_special_tokens=True)
  44. # print the generated text
  45. print(generated_text)