|
| 1 | +"""Model Wrapper for generative models.""" |
| 2 | + |
| 3 | +from collections.abc import Iterable |
| 4 | +import io |
| 5 | +import logging |
| 6 | +import time |
| 7 | +from typing import Literal, Optional, Union |
| 8 | +from vertexai import vision_models |
| 9 | +from lit_nlp.api import model as lit_model |
| 10 | +from lit_nlp.api import types as lit_types |
| 11 | +from lit_nlp.lib import image_utils |
| 12 | +from PIL import Image |
| 13 | + |
| 14 | +_MAX_NUM_RETRIES = 5 |
| 15 | + |
| 16 | +_DEFAULT_CANDIDATE_COUNT = 1 |
| 17 | + |
| 18 | +_DEFAULT_MAX_OUTPUT_TOKENS = 256 |
| 19 | + |
| 20 | +_IMAGE_PREFIX = 'data:image/png;base64,' |
| 21 | + |
| 22 | + |
| 23 | +class VertexModelGardenModel(lit_model.BatchedRemoteModel): |
| 24 | + """VertexModelGardenModel is a wrapper for Vertex AI Model Garden model. |
| 25 | +
|
| 26 | + Attributes: |
| 27 | + model_name: The name of the model to load. |
| 28 | + max_concurrent_requests: The maximum number of concurrent requests to the |
| 29 | + model. |
| 30 | + max_qps: The maximum number of queries per second to the model. |
| 31 | + temperature: The temperature to use for the model. |
| 32 | + candidate_count: The number of candidates to generate. |
| 33 | + max_output_tokens: The maximum number of tokens to generate. |
| 34 | +
|
| 35 | + Please note the model will predict all examples at a fixed temperature. |
| 36 | + """ |
| 37 | + |
| 38 | + def __init__( |
| 39 | + self, |
| 40 | + model_name: str = 'imagen-3.0-generate-002', |
| 41 | + max_concurrent_requests: int = 4, |
| 42 | + max_qps: Union[int, float] = 25, |
| 43 | + aspect_ratio: Optional[ |
| 44 | + Literal['16:9', '1:1', '3:4', '4:3', '9:16'] |
| 45 | + ] = None, |
| 46 | + width: int = 256, |
| 47 | + height: int = 256, |
| 48 | + ): |
| 49 | + super().__init__(max_concurrent_requests, max_qps) |
| 50 | + # Connect to the remote model. |
| 51 | + self._model = vision_models.ImageGenerationModel.from_pretrained(model_name) |
| 52 | + self._aspect_ratio = aspect_ratio |
| 53 | + self._width = width |
| 54 | + self._height = height |
| 55 | + |
| 56 | + def query_model(self, prompt: str, **unused_kw) -> list[lit_types.JsonDict]: |
| 57 | + num_attempts = 0 |
| 58 | + predictions = None |
| 59 | + exception = None |
| 60 | + width = self._width |
| 61 | + height = self._height |
| 62 | + |
| 63 | + while num_attempts < _MAX_NUM_RETRIES and predictions is None: |
| 64 | + num_attempts += 1 |
| 65 | + |
| 66 | + try: |
| 67 | + predictions = self._model.generate_images( |
| 68 | + prompt=prompt, |
| 69 | + aspect_ratio=self._aspect_ratio, |
| 70 | + ) |
| 71 | + except Exception as e: # pylint: disable=broad-except |
| 72 | + wait_time = 2**num_attempts |
| 73 | + exception = e |
| 74 | + logging.warning('Waiting %ds to retry... (%s)', wait_time, e) |
| 75 | + time.sleep(2**num_attempts) |
| 76 | + |
| 77 | + if predictions is None: |
| 78 | + raise ValueError( |
| 79 | + f'Failed to get predictions. ({exception})' |
| 80 | + ) from exception |
| 81 | + |
| 82 | + if not isinstance(predictions, Iterable): |
| 83 | + raise ValueError(f'Predictions is not an Iterable: {type(predictions)}') |
| 84 | + |
| 85 | + images = [] |
| 86 | + for image_ in predictions.images: |
| 87 | + pil_img = Image.open(io.BytesIO(getattr(image_, '_image_bytes'))) |
| 88 | + pil_img = pil_img.resize((width, height)) |
| 89 | + images.append(image_utils.convert_pil_to_image_str(pil_img)) |
| 90 | + |
| 91 | + return images |
| 92 | + |
| 93 | + def predict_minibatch( |
| 94 | + self, inputs: list[lit_types.JsonDict] |
| 95 | + ) -> list[lit_types.JsonDict]: |
| 96 | + """The model can generate up to 8 images per run, but LIT may only show one due to frontend limitations. |
| 97 | +
|
| 98 | + In MinDalle demos, the grid_size parameter controls layout—for example, |
| 99 | + grid_size=2 creates a 2x2 grid of sub-images, rendered as a single final |
| 100 | + image. That’s why only one image might appear even if multiple are |
| 101 | + generated. |
| 102 | +
|
| 103 | + Args: |
| 104 | + inputs: A list of input dictionaries, each containing a 'prompt'. |
| 105 | +
|
| 106 | + Returns: |
| 107 | + A list of dictionaries, each containing the generated 'image' and the |
| 108 | + original 'prompt'. |
| 109 | + """ |
| 110 | + results = [] |
| 111 | + for inp in inputs: |
| 112 | + prompt = inp['prompt'] |
| 113 | + b64_strs = self.query_model(prompt) |
| 114 | + if not b64_strs: |
| 115 | + raise ValueError(f'No images generated for prompt: {prompt}') |
| 116 | + results.append({ |
| 117 | + 'image': b64_strs[0], |
| 118 | + 'prompt': prompt, |
| 119 | + }) |
| 120 | + return results |
| 121 | + |
| 122 | + @classmethod |
| 123 | + def init_spec(cls) -> lit_types.Spec: |
| 124 | + return { |
| 125 | + 'model_name': lit_types.String( |
| 126 | + default='imagen-3.0-generate-002', required=True |
| 127 | + ), |
| 128 | + 'aspect_ratio': lit_types.String(default='1:1', required=False), |
| 129 | + 'width': lit_types.Integer(default=256, required=False), |
| 130 | + 'height': lit_types.Integer(default=256, required=False), |
| 131 | + } |
| 132 | + |
| 133 | + def input_spec(self) -> lit_types.Spec: |
| 134 | + return { |
| 135 | + 'prompt': lit_types.TextSegment(), |
| 136 | + } |
| 137 | + |
| 138 | + def output_spec(self): |
| 139 | + return { |
| 140 | + 'image': lit_types.ImageBytesList(), |
| 141 | + } |
0 commit comments