Repository navigation
Expand file tree
/
Copy pathhub_load.py
More file actions
54 lines (46 loc) · 1.93 KB
/
Copy pathhub_load.py
File metadata and controls
54 lines (46 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# RUN: %PYTHON %s > /dev/null
"""
Example demonstrating how to load any Hugging Face model to MLIR using Lighthouse
without initializing the model class on the user's side.
"""
import argparse
import faulthandler
import sys
from transformers import AutoModel
from lighthouse.ingress.torch import import_from_model
def load_from_hf(model_name: str, download_timeout: int) -> str:
# The download can stall indefinitely (e.g. behind a proxy): exit with the
# stalled stack instead.
# The test fails on timeout.
faulthandler.dump_traceback_later(download_timeout, exit=True)
model = AutoModel.from_pretrained(model_name)
faulthandler.cancel_dump_traceback_later()
model.eval()
# Exporting to a static graph: drop the KV cache so the output is plain tensors.
if hasattr(model.config, "use_cache"):
model.config.use_cache = False
# torch-mlir's importer requires every buffer in the state dict, but Hugging
# Face registers some (e.g. 'position_ids') as non-persistent; make them all
# persistent so they can be mapped.
for submodule in model.modules():
submodule._non_persistent_buffers_set.clear()
# Each model exposes correctly-typed example inputs, so no per-model handling.
return import_from_model(model, sample_args=(), sample_kwargs=model.dummy_inputs)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--model",
type=str,
default="hf-internal-testing/tiny-random-BertModel",
help="Hugging Face model id (e.g. 'google-bert/bert-base-uncased').",
)
parser.add_argument(
"--download-timeout",
type=int,
default=30,
help="Seconds to wait for the model download before giving up.",
)
args = parser.parse_args()
print(f"Loading model from Hugging Face: {args.model}", file=sys.stderr)
mlir_module = load_from_hf(args.model, args.download_timeout)
print(mlir_module)