|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import torch |
| 7 | +from pipeline_utils import load_pipeline |
| 8 | + |
| 9 | +from ts.handler_utils.timer import timed |
| 10 | +from ts.torch_handler.base_handler import BaseHandler |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class DiffusionFastHandler(BaseHandler): |
| 16 | + """ |
| 17 | + Diffusion-Fast handler class for text to image generation. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self): |
| 21 | + super().__init__() |
| 22 | + self.initialized = False |
| 23 | + |
| 24 | + def initialize(self, ctx): |
| 25 | + """In this initialize function, the Diffusion Fast model is loaded and |
| 26 | + initialized here. |
| 27 | + Args: |
| 28 | + ctx (context): It is a JSON Object containing information |
| 29 | + pertaining to the model artifacts parameters. |
| 30 | + """ |
| 31 | + self.context = ctx |
| 32 | + self.manifest = ctx.manifest |
| 33 | + properties = ctx.system_properties |
| 34 | + model_dir = properties.get("model_dir") |
| 35 | + |
| 36 | + if torch.cuda.is_available() and properties.get("gpu_id") is not None: |
| 37 | + self.map_location = "cuda" |
| 38 | + self.device = torch.device( |
| 39 | + self.map_location + ":" + str(properties.get("gpu_id")) |
| 40 | + ) |
| 41 | + else: |
| 42 | + self.map_location = "cpu" |
| 43 | + self.device = torch.device(self.map_location) |
| 44 | + |
| 45 | + self.num_inference_steps = ctx.model_yaml_config["handler"][ |
| 46 | + "num_inference_steps" |
| 47 | + ] |
| 48 | + |
| 49 | + # Parameters for the model |
| 50 | + compile_unet = ctx.model_yaml_config["handler"]["compile_unet"] |
| 51 | + compile_vae = ctx.model_yaml_config["handler"]["compile_vae"] |
| 52 | + compile_mode = ctx.model_yaml_config["handler"]["compile_mode"] |
| 53 | + enable_fused_projections = ctx.model_yaml_config["handler"][ |
| 54 | + "enable_fused_projections" |
| 55 | + ] |
| 56 | + do_quant = ctx.model_yaml_config["handler"]["do_quant"] |
| 57 | + change_comp_config = ctx.model_yaml_config["handler"]["change_comp_config"] |
| 58 | + no_sdpa = ctx.model_yaml_config["handler"]["no_sdpa"] |
| 59 | + no_bf16 = ctx.model_yaml_config["handler"]["no_bf16"] |
| 60 | + upcast_vae = ctx.model_yaml_config["handler"]["upcast_vae"] |
| 61 | + |
| 62 | + # Load model weights |
| 63 | + model_path = Path(ctx.model_yaml_config["handler"]["model_path"]) |
| 64 | + ckpt = os.path.join(model_dir, model_path) |
| 65 | + |
| 66 | + self.pipeline = load_pipeline( |
| 67 | + ckpt=ckpt, |
| 68 | + compile_unet=compile_unet, |
| 69 | + compile_vae=compile_vae, |
| 70 | + compile_mode=compile_mode, |
| 71 | + enable_fused_projections=enable_fused_projections, |
| 72 | + do_quant=do_quant, |
| 73 | + change_comp_config=change_comp_config, |
| 74 | + no_bf16=no_bf16, |
| 75 | + no_sdpa=no_sdpa, |
| 76 | + upcast_vae=upcast_vae, |
| 77 | + ) |
| 78 | + |
| 79 | + logger.info("Diffusion Fast model loaded successfully") |
| 80 | + |
| 81 | + self.initialized = True |
| 82 | + |
| 83 | + @timed |
| 84 | + def preprocess(self, requests): |
| 85 | + """Basic text preprocessing, of the user's prompt. |
| 86 | + Args: |
| 87 | + requests (str): The Input data in the form of text is passed on to the preprocess |
| 88 | + function. |
| 89 | + Returns: |
| 90 | + list : The preprocess function returns a list of prompts. |
| 91 | + """ |
| 92 | + |
| 93 | + assert ( |
| 94 | + len(requests) == 1 |
| 95 | + ), "Diffusion Fast is currently only supported with batch_size=1" |
| 96 | + |
| 97 | + inputs = [] |
| 98 | + for _, data in enumerate(requests): |
| 99 | + input_text = data.get("data") |
| 100 | + if input_text is None: |
| 101 | + input_text = data.get("body") |
| 102 | + if isinstance(input_text, (bytes, bytearray)): |
| 103 | + input_text = input_text.decode("utf-8") |
| 104 | + inputs.append(input_text) |
| 105 | + return inputs |
| 106 | + |
| 107 | + @timed |
| 108 | + def inference(self, inputs): |
| 109 | + """Generates the image relevant to the received text. |
| 110 | + Args: |
| 111 | + input_batch (list): List of Text from the pre-process function is passed here |
| 112 | + Returns: |
| 113 | + list : It returns a list of the generate images for the input text |
| 114 | + """ |
| 115 | + # Handling inference for sequence_classification. |
| 116 | + inferences = self.pipeline( |
| 117 | + inputs, num_inference_steps=self.num_inference_steps, height=768, width=768 |
| 118 | + ).images |
| 119 | + |
| 120 | + return inferences |
| 121 | + |
| 122 | + @timed |
| 123 | + def postprocess(self, inference_output): |
| 124 | + """Post Process Function converts the generated image into Torchserve readable format. |
| 125 | + Args: |
| 126 | + inference_output (list): It contains the generated image of the input text. |
| 127 | + Returns: |
| 128 | + (list): Returns a list of the images. |
| 129 | + """ |
| 130 | + images = [] |
| 131 | + for image in inference_output: |
| 132 | + images.append(np.array(image).tolist()) |
| 133 | + return images |
0 commit comments