|
| 1 | +# ruff: noqa: RUF002 |
| 2 | +r"""End-to-end translation example for Hy-MT1.5-1.8B via ORT GenAI. |
| 3 | +
|
| 4 | +Demonstrates loading a mobius-built Hy-MT1.5 export with |
| 5 | +``onnxruntime-genai`` (no PyTorch at inference time). The HF model_type |
| 6 | +``hunyuan_v1_dense`` is mapped to ORT GenAI's generic ``decoder`` LLM |
| 7 | +type (see ``onnxruntime-genai/src/models/model_type.h``); this script |
| 8 | +verifies that the resulting ``genai_config.json`` loads and that |
| 9 | +``Generator`` produces real translations end-to-end. |
| 10 | +
|
| 11 | +Two model variants are supported, selected by ``--variant``: |
| 12 | +
|
| 13 | +* ``bf16`` - full-precision export from the HuggingFace safetensors. |
| 14 | + Note: BF16 MatMul isn't implemented on the ORT CPU EP, so this |
| 15 | + variant only runs on CUDA / DML / WebGPU. |
| 16 | +* ``Q1_0`` - 2-bit-quantized export from the AngelSlim GGUF (Tencent |
| 17 | + SEQ codebook; default mobius packing is ``MatMulNBits bits=4`` |
| 18 | + inflated form for fast CPU decode). |
| 19 | +
|
| 20 | +Tokenizer caveat: the Hy-MT1.5 BPE vocab uses a custom regex |
| 21 | +pre-tokenizer that ort-extensions does not currently round-trip |
| 22 | +(``"Hello, world!"`` tokenizes to a single space token, ``"你好"`` |
| 23 | +tokenizes to an empty sequence). By default this example tokenizes |
| 24 | +and detokenizes with the HuggingFace tokenizer and feeds raw token |
| 25 | +IDs to ``og.Generator``, which still exercises the full ORT GenAI |
| 26 | +inference path. Pass ``--use-ort-tokenizer`` to force the broken |
| 27 | +``og.Tokenizer`` path for reproduction / debugging. |
| 28 | +
|
| 29 | +Expected output (Q1_0 on CPU EP):: |
| 30 | +
|
| 31 | + $ python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx \\ |
| 32 | + --prompt 'Translate to Spanish: The cat is sleeping on the chair.' |
| 33 | + El gato está durmiendo en la silla. |
| 34 | +
|
| 35 | + $ python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx \\ |
| 36 | + --prompt 'Translate to French: Knowledge is power.' |
| 37 | + La connaissance est puissance. |
| 38 | +
|
| 39 | + $ python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx |
| 40 | + # default prompt: Translate the following Chinese text to English: 你好,世界! |
| 41 | + Hello, world! |
| 42 | +
|
| 43 | +Usage:: |
| 44 | +
|
| 45 | + # Build + run the Q1_0 quantized variant on CPU |
| 46 | + huggingface-cli download AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF \\ |
| 47 | + Hy-MT1.5-1.8B-2bit.gguf --local-dir ./gguf |
| 48 | + python examples/hy_mt1_5.py --variant Q1_0 --build \\ |
| 49 | + --gguf ./gguf/Hy-MT1.5-1.8B-2bit.gguf --out ./hy-mt-q1_0-onnx |
| 50 | +
|
| 51 | + # Reuse an existing build (no --build) |
| 52 | + python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx |
| 53 | +""" |
| 54 | + |
| 55 | +from __future__ import annotations |
| 56 | + |
| 57 | +import argparse |
| 58 | +import sys |
| 59 | +from pathlib import Path |
| 60 | + |
| 61 | +HF_MODEL_ID = "tencent/Hy-MT1.5-1.8B-2bit" |
| 62 | + |
| 63 | +_DEFAULT_PROMPT = "Translate the following Chinese text to English: 你好,世界!" # noqa: RUF001 |
| 64 | + |
| 65 | + |
| 66 | +def _build_bf16(output_dir: Path) -> None: |
| 67 | + """Build the BF16 ONNX model + ORT-GenAI config in-process.""" |
| 68 | + import mobius |
| 69 | + from mobius.integrations.ort_genai.auto_export import write_ort_genai_config |
| 70 | + |
| 71 | + print(f"Building bf16 -> {output_dir}") |
| 72 | + pkg = mobius.build(HF_MODEL_ID, dtype="bf16", load_weights=True) |
| 73 | + pkg.save(str(output_dir)) |
| 74 | + write_ort_genai_config(pkg, str(output_dir), hf_model_id=HF_MODEL_ID, ep="cpu") |
| 75 | + print(" genai_config.json + tokenizer files written") |
| 76 | + |
| 77 | + |
| 78 | +def _build_q1_0(gguf_path: Path, output_dir: Path) -> None: |
| 79 | + """Build the 2-bit Q1_0 ONNX model + ORT-GenAI config in-process.""" |
| 80 | + from mobius.integrations.gguf._builder import build_from_gguf |
| 81 | + from mobius.integrations.ort_genai.auto_export import write_ort_genai_config |
| 82 | + |
| 83 | + print(f"Building Q1_0 -> {output_dir}") |
| 84 | + # ep='cpu' applies the GroupQueryAttention rewrite. With standard |
| 85 | + # opset 23 Attention (ep='default'), ORT GenAI's |
| 86 | + # past_present_share_buffer mode cannot be used; mobius's |
| 87 | + # write_ort_genai_config inspects the resulting graph and turns |
| 88 | + # share_buffer off automatically when GQA is absent. |
| 89 | + pkg = build_from_gguf( |
| 90 | + str(gguf_path), keep_quantized=True, dtype="f32", execution_provider="cpu" |
| 91 | + ) |
| 92 | + pkg.save(str(output_dir)) |
| 93 | + write_ort_genai_config(pkg, str(output_dir), hf_model_id=HF_MODEL_ID, ep="cpu") |
| 94 | + print(" genai_config.json + tokenizer files written") |
| 95 | + |
| 96 | + |
| 97 | +def _ensure_built(args: argparse.Namespace) -> Path: |
| 98 | + out = Path(args.out).resolve() |
| 99 | + if args.build: |
| 100 | + out.mkdir(parents=True, exist_ok=True) |
| 101 | + if args.variant == "bf16": |
| 102 | + _build_bf16(out) |
| 103 | + elif args.variant == "Q1_0": |
| 104 | + if not args.gguf: |
| 105 | + sys.exit("--gguf is required for --variant Q1_0 --build") |
| 106 | + _build_q1_0(Path(args.gguf), out) |
| 107 | + if not (out / "genai_config.json").exists(): |
| 108 | + sys.exit( |
| 109 | + f"{out}/genai_config.json missing. Re-run with --build or point --out " |
| 110 | + "at a directory produced by `mobius build --runtime ort-genai`." |
| 111 | + ) |
| 112 | + return out |
| 113 | + |
| 114 | + |
| 115 | +def run_translation( |
| 116 | + model_dir: Path, |
| 117 | + prompt: str, |
| 118 | + max_new_tokens: int, |
| 119 | + use_hf_tokenizer: bool, |
| 120 | +) -> str: |
| 121 | + """Run a single greedy generation through ORT GenAI.""" |
| 122 | + import onnxruntime_genai as og |
| 123 | + |
| 124 | + print(f"\nLoading ORT GenAI model from {model_dir}") |
| 125 | + model = og.Model(str(model_dir)) |
| 126 | + |
| 127 | + # Apply the chat template from the model dir (works either way). |
| 128 | + chat_template_path = model_dir / "chat_template.jinja" |
| 129 | + if chat_template_path.exists(): |
| 130 | + from jinja2 import Environment |
| 131 | + |
| 132 | + template = Environment().from_string(chat_template_path.read_text()) |
| 133 | + full_prompt = template.render( |
| 134 | + messages=[{"role": "user", "content": prompt}], |
| 135 | + add_generation_prompt=True, |
| 136 | + ) |
| 137 | + else: |
| 138 | + full_prompt = prompt |
| 139 | + |
| 140 | + print(f"\nPrompt:\n {prompt!r}") |
| 141 | + |
| 142 | + if use_hf_tokenizer: |
| 143 | + # Tokenize and detokenize via HuggingFace. ORT-extensions' BPE |
| 144 | + # tokenizer does not currently round-trip the Hy-MT1.5 vocab's |
| 145 | + # custom regex pre-tokenizer, so we bypass og.Tokenizer here |
| 146 | + # while still exercising the ORT GenAI inference path. |
| 147 | + import transformers |
| 148 | + |
| 149 | + hf_tok = transformers.AutoTokenizer.from_pretrained(HF_MODEL_ID) |
| 150 | + input_tokens = hf_tok.encode(full_prompt, add_special_tokens=False) |
| 151 | + |
| 152 | + params = og.GeneratorParams(model) |
| 153 | + params.set_search_options( |
| 154 | + max_length=len(input_tokens) + max_new_tokens, do_sample=False |
| 155 | + ) |
| 156 | + generator = og.Generator(model, params) |
| 157 | + generator.append_tokens(input_tokens) |
| 158 | + |
| 159 | + print("Generating: ", end="", flush=True) |
| 160 | + generated_ids: list[int] = [] |
| 161 | + while not generator.is_done() and len(generated_ids) < max_new_tokens: |
| 162 | + generator.generate_next_token() |
| 163 | + new_token = int(generator.get_next_tokens()[0]) |
| 164 | + generated_ids.append(new_token) |
| 165 | + # Decode incrementally; some tokens are multi-byte and only |
| 166 | + # render when combined with neighbours, so we re-decode the |
| 167 | + # accumulated tail and print the delta. |
| 168 | + text_so_far = hf_tok.decode(generated_ids, skip_special_tokens=False) |
| 169 | + print(text_so_far, end="\r", flush=True) |
| 170 | + print() |
| 171 | + return hf_tok.decode(generated_ids, skip_special_tokens=False) |
| 172 | + |
| 173 | + tokenizer = og.Tokenizer(model) |
| 174 | + tokenizer_stream = tokenizer.create_stream() |
| 175 | + input_tokens = tokenizer.encode(full_prompt) |
| 176 | + |
| 177 | + params = og.GeneratorParams(model) |
| 178 | + params.set_search_options(max_length=len(input_tokens) + max_new_tokens, do_sample=False) |
| 179 | + generator = og.Generator(model, params) |
| 180 | + generator.append_tokens(input_tokens) |
| 181 | + |
| 182 | + print("Generating: ", end="", flush=True) |
| 183 | + chunks: list[str] = [] |
| 184 | + while not generator.is_done(): |
| 185 | + generator.generate_next_token() |
| 186 | + new_token = generator.get_next_tokens()[0] |
| 187 | + chunk = tokenizer_stream.decode(new_token) |
| 188 | + chunks.append(chunk) |
| 189 | + print(chunk, end="", flush=True) |
| 190 | + print() |
| 191 | + return "".join(chunks) |
| 192 | + |
| 193 | + |
| 194 | +def main() -> None: |
| 195 | + parser = argparse.ArgumentParser( |
| 196 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter |
| 197 | + ) |
| 198 | + parser.add_argument("--variant", choices=("bf16", "Q1_0"), default="bf16") |
| 199 | + parser.add_argument( |
| 200 | + "--out", default=None, help="ONNX model directory (will be created with --build)" |
| 201 | + ) |
| 202 | + parser.add_argument("--build", action="store_true", help="Build the model before running") |
| 203 | + parser.add_argument( |
| 204 | + "--gguf", |
| 205 | + default=None, |
| 206 | + help="Path to the Tencent SEQ GGUF (required with --variant Q1_0 --build)", |
| 207 | + ) |
| 208 | + parser.add_argument("--prompt", default=_DEFAULT_PROMPT) |
| 209 | + parser.add_argument("--max-new-tokens", type=int, default=64) |
| 210 | + parser.add_argument( |
| 211 | + "--use-ort-tokenizer", |
| 212 | + action="store_true", |
| 213 | + help=( |
| 214 | + "Use ort-extensions' tokenizer (og.Tokenizer) instead of the " |
| 215 | + "HuggingFace one. The Hy-MT1.5 vocab's custom regex pre-tokenizer " |
| 216 | + "is not currently round-tripped by ort-extensions, so by default " |
| 217 | + "we tokenize with HF and feed raw token IDs to og.Generator. " |
| 218 | + "Enable this flag to exercise the full og.Tokenizer path." |
| 219 | + ), |
| 220 | + ) |
| 221 | + args = parser.parse_args() |
| 222 | + |
| 223 | + if args.out is None: |
| 224 | + args.out = f"./hy-mt-{args.variant.lower()}-onnx" |
| 225 | + |
| 226 | + out = _ensure_built(args) |
| 227 | + text = run_translation( |
| 228 | + out, |
| 229 | + args.prompt, |
| 230 | + args.max_new_tokens, |
| 231 | + use_hf_tokenizer=not args.use_ort_tokenizer, |
| 232 | + ) |
| 233 | + |
| 234 | + print("\n--- Full response ---") |
| 235 | + print(text) |
| 236 | + |
| 237 | + |
| 238 | +if __name__ == "__main__": |
| 239 | + main() |
0 commit comments