|
| 1 | +# ----------------------------------------------------------------------------- |
| 2 | +# |
| 3 | +# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries. |
| 4 | +# SPDX-License-Identifier: BSD-3-Clause |
| 5 | +# |
| 6 | +# ---------------------------------------------------------------------------- |
| 7 | + |
| 8 | +import warnings |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | + |
| 12 | +class CustomIOGenerator: |
| 13 | + """ |
| 14 | + Abstract base class for generating custom IO mappings for different model types. |
| 15 | +
|
| 16 | + Args: |
| 17 | + model (object): The model instance for which IO mappings are to be generated. |
| 18 | + cache_dir (str): Directory path where the generated YAML files will be saved. |
| 19 | + mxint8_kv_cache (bool): If True, use 'mxint8' precision for KV cache; otherwise, use 'float16'. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self, model, cache_dir=".", mxint8_kv_cache=False): |
| 23 | + self.model = model |
| 24 | + self.cache_dir = Path(cache_dir) |
| 25 | + self.kv_cache_dtype = "mxint8" if mxint8_kv_cache else "float16" |
| 26 | + self.dtype_suffix = "int8" if mxint8_kv_cache else "fp16" |
| 27 | + |
| 28 | + def dump(self, custom_io: dict, suffix: str): |
| 29 | + """ |
| 30 | + Writes the custom IO mapping to a YAML file. |
| 31 | +
|
| 32 | + Args: |
| 33 | + custom_io (dict): Dictionary containing IO names and their precision types. |
| 34 | + suffix (str): Suffix to append to the output filename. |
| 35 | + """ |
| 36 | + custom_io_yaml = self.cache_dir / f"custom_io_{suffix}.yaml" |
| 37 | + with open(custom_io_yaml, "w") as fp: |
| 38 | + for io_name, dtype in custom_io.items(): |
| 39 | + fp.write(f" - IOName: {io_name}\n Precision: {dtype}\n\n") |
| 40 | + |
| 41 | + def generate(self) -> dict: |
| 42 | + """ |
| 43 | + Abstract method to generate custom IO mappings. |
| 44 | +
|
| 45 | + Returns: |
| 46 | + dict: A dictionary of IO names and their precision types. |
| 47 | +
|
| 48 | + Raises: |
| 49 | + NotImplementedError: Must be implemented by subclasses. |
| 50 | + """ |
| 51 | + raise NotImplementedError("Subclasses must implement this method") |
| 52 | + |
| 53 | + |
| 54 | +class CausalLMIOGenerator(CustomIOGenerator): |
| 55 | + """ |
| 56 | + IO generator for causal language models. |
| 57 | + """ |
| 58 | + |
| 59 | + def generate(self) -> dict: |
| 60 | + """ |
| 61 | + Generates IO mappings for past key/value states in causal language models. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + dict: Mapping of IO names to precision types. |
| 65 | + """ |
| 66 | + custom_io = {} |
| 67 | + num_layers = getattr(self.model, "num_layers", 12) |
| 68 | + for suffix in ["", "_RetainedState"]: |
| 69 | + for i in range(num_layers): |
| 70 | + for kv in ["key", "value"]: |
| 71 | + custom_io[f"past_{kv}.{i}{suffix}"] = self.kv_cache_dtype |
| 72 | + self.dump(custom_io, self.dtype_suffix) |
| 73 | + return custom_io |
| 74 | + |
| 75 | + |
| 76 | +class DualQPCIOGenerator(CustomIOGenerator): |
| 77 | + """ |
| 78 | + IO generator for dual QPC models (e.g., vision-language models). |
| 79 | + """ |
| 80 | + |
| 81 | + def generate(self) -> dict: |
| 82 | + """ |
| 83 | + Generates IO mappings for both vision and language components. |
| 84 | +
|
| 85 | + Returns: |
| 86 | + dict: Combined mapping of IO names to precision types for vision and language outputs. |
| 87 | + """ |
| 88 | + output_names = self.model.model.get_output_names() |
| 89 | + custom_io_vision = { |
| 90 | + name: self.kv_cache_dtype if name.startswith("past_") else "float16" |
| 91 | + for name in output_names.get("vision", []) |
| 92 | + } |
| 93 | + |
| 94 | + custom_io_lang = {} |
| 95 | + for name in output_names.get("lang", []): |
| 96 | + if name.endswith("_RetainedState"): |
| 97 | + base = name[: -len("_RetainedState")] |
| 98 | + dtype = "float16" if "vision_embeds" in name else self.kv_cache_dtype |
| 99 | + custom_io_lang[base] = dtype |
| 100 | + custom_io_lang[name] = dtype |
| 101 | + |
| 102 | + self.dump(custom_io_vision, f"{self.dtype_suffix}_vision") |
| 103 | + self.dump(custom_io_lang, f"{self.dtype_suffix}_lang") |
| 104 | + warnings.warn(f"Unsupported model class via CLI: {type(self.model).__name__}", UserWarning) |
| 105 | + return {**custom_io_vision, **custom_io_lang} |
| 106 | + |
| 107 | + |
| 108 | +class SingleQPCIOGenerator(CustomIOGenerator): |
| 109 | + """ |
| 110 | + IO generator for single QPC models. |
| 111 | + """ |
| 112 | + |
| 113 | + def generate(self) -> dict: |
| 114 | + """ |
| 115 | + Generates IO mappings for retained states in single QPC models. |
| 116 | +
|
| 117 | + Returns: |
| 118 | + dict: Mapping of IO names to precision types. |
| 119 | + """ |
| 120 | + output_names = self.model.model.get_output_names() |
| 121 | + custom_io = {} |
| 122 | + for name in output_names: |
| 123 | + if name.endswith("_RetainedState"): |
| 124 | + base = name[: -len("_RetainedState")] |
| 125 | + dtype = "float16" if "pixel_values" in name else self.kv_cache_dtype |
| 126 | + custom_io[base] = dtype |
| 127 | + custom_io[name] = dtype |
| 128 | + self.dump(custom_io, self.dtype_suffix) |
| 129 | + return custom_io |
| 130 | + |
| 131 | + |
| 132 | +class SpeechSeq2SeqIOGenerator(CustomIOGenerator): |
| 133 | + """ |
| 134 | + IO generator for speech sequence-to-sequence models. |
| 135 | + """ |
| 136 | + |
| 137 | + def generate(self) -> dict: |
| 138 | + """ |
| 139 | + Generates IO mappings for input features and retained states in speech models. |
| 140 | +
|
| 141 | + Returns: |
| 142 | + dict: Mapping of IO names to precision types. |
| 143 | + """ |
| 144 | + output_names = self.model.model.get_output_names() |
| 145 | + custom_io = {"input_features": self.kv_cache_dtype} |
| 146 | + for name in output_names: |
| 147 | + if name.endswith("_RetainedState"): |
| 148 | + base = name[: -len("_RetainedState")] |
| 149 | + custom_io[base] = self.kv_cache_dtype |
| 150 | + custom_io[name] = self.kv_cache_dtype |
| 151 | + self.dump(custom_io, self.dtype_suffix) |
| 152 | + return custom_io |
| 153 | + |
| 154 | + |
| 155 | +class UnsupportedModelIOGenerator(CustomIOGenerator): |
| 156 | + """ |
| 157 | + Fallback IO generator for unsupported model types. |
| 158 | + """ |
| 159 | + |
| 160 | + def generate(self) -> dict: |
| 161 | + """ |
| 162 | + Emits a warning for unsupported model types. |
| 163 | +
|
| 164 | + Returns: |
| 165 | + dict: Empty dictionary. |
| 166 | + """ |
| 167 | + warnings.warn(f"Unsupported model class: {type(self.model).__name__}", UserWarning) |
| 168 | + return {} |
| 169 | + |
| 170 | + |
| 171 | +class CustomIOFactory: |
| 172 | + """ |
| 173 | + Factory class to instantiate the appropriate IO generator based on model type. |
| 174 | + """ |
| 175 | + |
| 176 | + @staticmethod |
| 177 | + def get_generator(model, cache_dir=".", mxint8_kv_cache=False) -> CustomIOGenerator: |
| 178 | + """ |
| 179 | + Returns the appropriate IO generator instance for the given model. |
| 180 | +
|
| 181 | + Args: |
| 182 | + model (object): The model instance. |
| 183 | + cache_dir (str): Directory to store YAML files. |
| 184 | + mxint8_kv_cache (bool): Flag to use 'mxint8' precision. |
| 185 | +
|
| 186 | + Returns: |
| 187 | + CustomIOGenerator: An instance of the appropriate subclass. |
| 188 | + """ |
| 189 | + model_class_name = type(model).__name__ |
| 190 | + mapping = { |
| 191 | + "QEFFAutoModelForCausalLM": CausalLMIOGenerator, |
| 192 | + "_QEFFAutoModelForImageTextToTextDualQPC": DualQPCIOGenerator, |
| 193 | + "_QEFFAutoModelForImageTextToTextSingleQPC": SingleQPCIOGenerator, |
| 194 | + "QEFFAutoModelForSpeechSeq2Seq": SpeechSeq2SeqIOGenerator, |
| 195 | + } |
| 196 | + generator_class = mapping.get(model_class_name, UnsupportedModelIOGenerator) |
| 197 | + return generator_class(model, cache_dir, mxint8_kv_cache) |
| 198 | + |
| 199 | + |
| 200 | +def generate_custom_io(qeff_model, cache_dir=".", mxint8_kv_cache=False) -> dict: |
| 201 | + """ |
| 202 | + Generates and returns custom IO mappings for the given QEFF model. |
| 203 | +
|
| 204 | + Args: |
| 205 | + qeff_model (object): The model instance. |
| 206 | + cache_dir (str): Directory to store YAML files. |
| 207 | + mxint8_kv_cache (bool): Flag to use 'mxint8' precision. |
| 208 | +
|
| 209 | + Returns: |
| 210 | + dict: Custom IO mapping generated by the appropriate generator. |
| 211 | + """ |
| 212 | + generator = CustomIOFactory.get_generator(qeff_model, cache_dir, mxint8_kv_cache) |
| 213 | + return generator.generate() |
0 commit comments