Skip to content

Commit c289382

Browse files
justinchubyCopilot
andauthored
build_from_gguf: accept HF repo references; hy_mt1_5 demo is one-shot (#304)
## What `build_from_gguf` now accepts a HuggingFace Hub reference in addition to a local `.gguf` path: ```python build_from_gguf('AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF') # auto-pick the single .gguf build_from_gguf('AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF:foo.gguf') # multi-file repo ``` Downloads go through `huggingface_hub.hf_hub_download` into the standard local cache, so re-runs are free. If the repo contains multiple .gguf files and no `:filename` is given, we raise with a list of available files. ## Why The `examples/hy_mt1_5.py` script now demos the full mobius pipeline in a single command — handy when handing off to a PM or a teammate: ```bash python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx \ --prompt 'Translate the following Chinese text to English: 黄河之水天上来' # -> downloads GGUF, builds Q1_0 ONNX + genai_config.json into --out, runs translation # 'The Yellow River rises from the sky.' ``` Subsequent runs reuse the build in `--out`. `--build` still forces a rebuild; `--gguf` still accepts a local path. ## Tests - `pytest src/mobius/integrations/gguf/ -q` → 144 passed - Manual end-to-end on a clean directory: fresh download + build + translation works (output above) --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 42573f4 commit c289382

2 files changed

Lines changed: 103 additions & 30 deletions

File tree

‎examples/hy_mt1_5.py‎

Lines changed: 49 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,15 @@
4242
4343
Usage::
4444
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 \\
45+
# One-shot demo: downloads the GGUF from AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF
46+
# (cached by huggingface_hub), builds the ONNX model into --out, and runs
47+
# translation. Re-running rebuilds the ONNX (the network download is cached).
48+
python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx \\
49+
--prompt 'Translate to Spanish: The cat is sleeping on the chair.'
50+
51+
# Build from a local GGUF instead of letting mobius download it
52+
python examples/hy_mt1_5.py --variant Q1_0 \\
4953
--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
5354
"""
5455

5556
from __future__ import annotations
@@ -60,6 +61,10 @@
6061

6162
HF_MODEL_ID = "tencent/Hy-MT1.5-1.8B-2bit"
6263

64+
# Source of the 2-bit GGUF. mobius's build_from_gguf accepts this directly and
65+
# downloads via huggingface_hub on first use.
66+
GGUF_HF_REF = "AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF"
67+
6368
_DEFAULT_PROMPT = "Translate the following Chinese text to English: 你好,世界!" # noqa: RUF001
6469

6570

@@ -75,39 +80,46 @@ def _build_bf16(output_dir: Path) -> None:
7580
print(" genai_config.json + tokenizer files written")
7681

7782

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."""
83+
def _build_q1_0(gguf_ref: str, output_dir: Path) -> None:
84+
"""Build the 2-bit Q1_0 ONNX model + ORT-GenAI config in-process.
85+
86+
``gguf_ref`` may be a local ``.gguf`` path or a HuggingFace reference
87+
like ``"AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF"`` (mobius downloads it via
88+
huggingface_hub on first use).
89+
"""
8090
from mobius.integrations.gguf._builder import build_from_gguf
8191
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
8292

83-
print(f"Building Q1_0 -> {output_dir}")
93+
print(f"Building Q1_0 from {gguf_ref} -> {output_dir}")
8494
# ep='cpu' applies the GroupQueryAttention rewrite. With standard
8595
# opset 23 Attention (ep='default'), ORT GenAI's
8696
# past_present_share_buffer mode cannot be used; mobius's
8797
# write_ort_genai_config inspects the resulting graph and turns
8898
# 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-
)
99+
pkg = build_from_gguf(gguf_ref, keep_quantized=True, dtype="f32", execution_provider="cpu")
92100
pkg.save(str(output_dir))
93101
write_ort_genai_config(pkg, str(output_dir), hf_model_id=HF_MODEL_ID, ep="cpu")
94102
print(" genai_config.json + tokenizer files written")
95103

96104

97-
def _ensure_built(args: argparse.Namespace) -> Path:
105+
def _build(args: argparse.Namespace) -> Path:
106+
"""Always (re)build the model into ``--out``.
107+
108+
HuggingFace Hub caches the source (safetensors for bf16, GGUF for Q1_0),
109+
so re-runs are cheap on the network side; the in-process ONNX construction
110+
runs every time. This keeps the example dead-simple: no marker files, no
111+
reuse logic, no chance of silently running a stale or wrong-variant build.
112+
"""
98113
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)
114+
out.mkdir(parents=True, exist_ok=True)
115+
if args.variant == "bf16":
116+
_build_bf16(out)
117+
elif args.variant == "Q1_0":
118+
_build_q1_0(args.gguf or GGUF_HF_REF, out)
107119
if not (out / "genai_config.json").exists():
108120
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`."
121+
f"Build did not produce {out / 'genai_config.json'}; check the "
122+
f"preceding output for the underlying failure."
111123
)
112124
return out
113125

@@ -197,13 +209,22 @@ def main() -> None:
197209
)
198210
parser.add_argument("--variant", choices=("bf16", "Q1_0"), default="bf16")
199211
parser.add_argument(
200-
"--out", default=None, help="ONNX model directory (will be created with --build)"
212+
"--out",
213+
default=None,
214+
help=(
215+
"Directory to write the ONNX model + ORT GenAI config into. "
216+
"Always overwritten on each run (HuggingFace cache handles "
217+
"the underlying source download). Defaults to ./hy-mt-<variant>-onnx."
218+
),
201219
)
202-
parser.add_argument("--build", action="store_true", help="Build the model before running")
203220
parser.add_argument(
204221
"--gguf",
205222
default=None,
206-
help="Path to the Tencent SEQ GGUF (required with --variant Q1_0 --build)",
223+
help=(
224+
"Path to a local Tencent SEQ GGUF for --variant Q1_0. When omitted, "
225+
"mobius downloads the GGUF from AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF "
226+
"(cached locally by huggingface_hub)."
227+
),
207228
)
208229
parser.add_argument("--prompt", default=_DEFAULT_PROMPT)
209230
parser.add_argument("--max-new-tokens", type=int, default=64)
@@ -223,7 +244,7 @@ def main() -> None:
223244
if args.out is None:
224245
args.out = f"./hy-mt-{args.variant.lower()}-onnx"
225246

226-
out = _ensure_built(args)
247+
out = _build(args)
227248
text = run_translation(
228249
out,
229250
args.prompt,

‎src/mobius/integrations/gguf/_builder.py‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,58 @@
2323
from pathlib import Path
2424

2525
import tqdm
26+
from huggingface_hub import HfApi, hf_hub_download
2627

2728
from mobius._model_package import ModelPackage
2829

2930
logger = logging.getLogger(__name__)
3031

3132

33+
def _looks_like_hf_repo_id(value: str) -> bool:
34+
"""Heuristic: ``value`` matches ``owner/repo`` (no path separators, no .gguf suffix)."""
35+
if value.startswith((".", "/", "~")):
36+
return False
37+
parts = value.split("/")
38+
return len(parts) == 2 and all(p and not p.endswith(".gguf") for p in parts)
39+
40+
41+
def _resolve_gguf_path(gguf_path: str | Path) -> str:
42+
"""Resolve a GGUF reference to a local file path.
43+
44+
Accepts:
45+
- An existing local filesystem path (returned unchanged).
46+
- A HuggingFace Hub reference ``"owner/repo"`` — the repo must contain
47+
exactly one ``*.gguf`` file, which is downloaded.
48+
- A HuggingFace Hub reference ``"owner/repo:filename.gguf"`` to pick a
49+
specific file from a multi-file repo.
50+
"""
51+
raw = str(gguf_path)
52+
if Path(raw).exists():
53+
return raw
54+
55+
# Split the optional ":filename" suffix before classifying so HF refs like
56+
# "owner/repo:weights.gguf" are not mistaken for a local path ending in .gguf.
57+
repo_id, _, filename = raw.partition(":")
58+
if not _looks_like_hf_repo_id(repo_id):
59+
# Looks like a local path that doesn't exist; let GGUFModel raise
60+
# FileNotFoundError with the original path.
61+
return raw
62+
63+
if not filename:
64+
files = [f for f in HfApi().list_repo_files(repo_id) if f.endswith(".gguf")]
65+
if not files:
66+
raise FileNotFoundError(f"No *.gguf files found in HF repo {repo_id!r}")
67+
if len(files) > 1:
68+
raise ValueError(
69+
f"HF repo {repo_id!r} contains multiple .gguf files: {files}. "
70+
f"Specify one via '{repo_id}:<filename.gguf>'."
71+
)
72+
filename = files[0]
73+
74+
logger.info("Downloading %s from %s", filename, repo_id)
75+
return hf_hub_download(repo_id=repo_id, filename=filename)
76+
77+
3278
def build_from_gguf(
3379
gguf_path: str | Path,
3480
*,
@@ -51,7 +97,12 @@ def build_from_gguf(
5197
repacked into MatMulNBits format instead of dequantized.
5298
5399
Args:
54-
gguf_path: Path to the ``.gguf`` file.
100+
gguf_path: Path to the ``.gguf`` file, *or* a HuggingFace Hub
101+
reference of the form ``"owner/repo"`` (the repo must
102+
contain exactly one ``*.gguf`` file) or
103+
``"owner/repo:filename.gguf"`` to pick a specific file. HF
104+
references are downloaded via ``huggingface_hub`` into the
105+
standard local cache.
55106
task: Override the model task (e.g. ``"text-generation"``).
56107
When ``None``, the task is auto-detected from the
57108
model type.
@@ -92,7 +143,8 @@ def build_from_gguf(
92143
process_tensors,
93144
)
94145

95-
# 1. Parse GGUF file
146+
# 1. Parse GGUF file (auto-download from HF Hub when given "owner/repo[:filename]")
147+
gguf_path = _resolve_gguf_path(gguf_path)
96148
gguf_model = GGUFModel(gguf_path)
97149
gguf_arch = gguf_model.architecture
98150
logger.info("Loaded GGUF file: %s (arch=%s)", gguf_path, gguf_arch)

0 commit comments

Comments
 (0)