|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +"""Generate onnx-genai ``inference_metadata.yaml`` sidecars.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import os |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +import onnx_ir as ir |
| 12 | + |
| 13 | +from mobius._model_package import ModelPackage |
| 14 | + |
| 15 | +_DTYPE_NAMES = { |
| 16 | + ir.DataType.FLOAT: "float32", |
| 17 | + ir.DataType.FLOAT16: "float16", |
| 18 | + ir.DataType.BFLOAT16: "bfloat16", |
| 19 | +} |
| 20 | +_DEFAULT_MAX_SEQUENCE_LENGTH = 4096 |
| 21 | + |
| 22 | + |
| 23 | +def _positive_int(config: object, name: str) -> int: |
| 24 | + value = getattr(config, name, None) |
| 25 | + if not isinstance(value, int) or value <= 0: |
| 26 | + raise ValueError( |
| 27 | + f"onnx-genai inference metadata requires a positive {name}, got {value!r}." |
| 28 | + ) |
| 29 | + return value |
| 30 | + |
| 31 | + |
| 32 | +def _kv_dtype(config: object) -> str: |
| 33 | + dtype = getattr(config, "dtype", None) |
| 34 | + try: |
| 35 | + return _DTYPE_NAMES[dtype] |
| 36 | + except KeyError: |
| 37 | + raise ValueError( |
| 38 | + "onnx-genai inference metadata supports float32, float16, or bfloat16 " |
| 39 | + f"KV caches, got {dtype!r}." |
| 40 | + ) from None |
| 41 | + |
| 42 | + |
| 43 | +def _max_sequence_length(config: object, requested: int | None) -> int: |
| 44 | + model_max = _positive_int(config, "max_position_embeddings") |
| 45 | + if requested is None: |
| 46 | + return min(model_max, _DEFAULT_MAX_SEQUENCE_LENGTH) |
| 47 | + if not isinstance(requested, int) or requested <= 0: |
| 48 | + raise ValueError( |
| 49 | + f"onnx-genai max_sequence_length must be a positive integer, got {requested!r}." |
| 50 | + ) |
| 51 | + if requested > model_max: |
| 52 | + raise ValueError( |
| 53 | + f"onnx-genai max_sequence_length {requested} exceeds the model limit {model_max}." |
| 54 | + ) |
| 55 | + return requested |
| 56 | + |
| 57 | + |
| 58 | +def generate_inference_metadata( |
| 59 | + config: object, *, max_sequence_length: int | None = None |
| 60 | +) -> dict[str, Any]: |
| 61 | + """Map a decoder config to metadata with a conservative serving KV capacity.""" |
| 62 | + num_attention_heads = _positive_int(config, "num_attention_heads") |
| 63 | + num_kv_heads = _positive_int(config, "num_key_value_heads") |
| 64 | + head_dim = _positive_int(config, "head_dim") |
| 65 | + max_sequence_length = _max_sequence_length(config, max_sequence_length) |
| 66 | + kv_dtype = _kv_dtype(config) |
| 67 | + |
| 68 | + is_gqa = num_kv_heads != num_attention_heads |
| 69 | + capabilities = ["grouped_query_attention" if is_gqa else "multi_head_attention"] |
| 70 | + |
| 71 | + attention: dict[str, Any] = { |
| 72 | + "type": "group_query_attention" if is_gqa else "multi_head_attention", |
| 73 | + "num_kv_heads": num_kv_heads, |
| 74 | + "num_attention_heads": num_attention_heads, |
| 75 | + "head_dim": head_dim, |
| 76 | + } |
| 77 | + sliding_window = getattr(config, "sliding_window", None) |
| 78 | + if isinstance(sliding_window, int) and sliding_window > 0: |
| 79 | + attention["sliding_window"] = sliding_window |
| 80 | + |
| 81 | + return { |
| 82 | + "required_capabilities": capabilities, |
| 83 | + "model": { |
| 84 | + "attention": attention, |
| 85 | + "max_sequence_length": max_sequence_length, |
| 86 | + "runtime_configurable": {"kv_cache": {"dtype": [kv_dtype]}}, |
| 87 | + }, |
| 88 | + "kv_cache": {"native_dtype": kv_dtype}, |
| 89 | + } |
| 90 | + |
| 91 | + |
| 92 | +def _to_yaml(metadata: dict[str, Any]) -> str: |
| 93 | + capabilities = metadata["required_capabilities"] |
| 94 | + attention = metadata["model"]["attention"] |
| 95 | + kv_dtypes = metadata["model"]["runtime_configurable"]["kv_cache"]["dtype"] |
| 96 | + |
| 97 | + lines = ["required_capabilities:"] |
| 98 | + if capabilities: |
| 99 | + lines.extend(f" - {capability}" for capability in capabilities) |
| 100 | + else: |
| 101 | + lines[-1] += " []" |
| 102 | + |
| 103 | + lines.extend( |
| 104 | + [ |
| 105 | + "model:", |
| 106 | + " attention:", |
| 107 | + f" type: {attention['type']}", |
| 108 | + f" num_kv_heads: {attention['num_kv_heads']}", |
| 109 | + f" num_attention_heads: {attention['num_attention_heads']}", |
| 110 | + f" head_dim: {attention['head_dim']}", |
| 111 | + ] |
| 112 | + ) |
| 113 | + if "sliding_window" in attention: |
| 114 | + lines.append(f" sliding_window: {attention['sliding_window']}") |
| 115 | + lines.extend( |
| 116 | + [ |
| 117 | + f" max_sequence_length: {metadata['model']['max_sequence_length']}", |
| 118 | + " runtime_configurable:", |
| 119 | + " kv_cache:", |
| 120 | + " dtype:", |
| 121 | + *(f" - {dtype}" for dtype in kv_dtypes), |
| 122 | + "kv_cache:", |
| 123 | + f" native_dtype: {metadata['kv_cache']['native_dtype']}", |
| 124 | + ] |
| 125 | + ) |
| 126 | + return "\n".join(lines) + "\n" |
| 127 | + |
| 128 | + |
| 129 | +def write_inference_metadata( |
| 130 | + pkg: ModelPackage, |
| 131 | + directory: str, |
| 132 | + *, |
| 133 | + max_sequence_length: int | None = None, |
| 134 | +) -> str: |
| 135 | + """Write ``inference_metadata.yaml`` for an already-built model package.""" |
| 136 | + config = getattr(pkg, "config", None) |
| 137 | + if config is None: |
| 138 | + raise ValueError( |
| 139 | + "write_inference_metadata requires ModelPackage.config to be set. " |
| 140 | + "This is set automatically when building with mobius.build()." |
| 141 | + ) |
| 142 | + |
| 143 | + os.makedirs(directory, exist_ok=True) |
| 144 | + path = os.path.join(directory, "inference_metadata.yaml") |
| 145 | + with open(path, "w", encoding="utf-8") as file: |
| 146 | + file.write( |
| 147 | + _to_yaml( |
| 148 | + generate_inference_metadata(config, max_sequence_length=max_sequence_length) |
| 149 | + ) |
| 150 | + ) |
| 151 | + return path |
0 commit comments