|
| 1 | +"""Loading ONNX models with external data from a huggingface_hub cache. |
| 2 | +
|
| 3 | +onnxruntime>=1.24 refuses external data that, once symlinks are resolved, is located outside of |
| 4 | +the directory of the model file, and of the directory the model file resolves to (a fallback of |
| 5 | +1.24.2, pyproject.toml excludes 1.24.0 and 1.24.1). Since huggingface_hub 1.32, a snapshot is made |
| 6 | +of symlinks into a blob store shared by the whole cache and sharded by hash, where a model and its |
| 7 | +data may resolve into different directories. Then the model and its data are hardlinked into |
| 8 | +`ONNX_SNAPSHOTS_DIR` of the repo cache, laid out as in the snapshot, which takes no extra space. |
| 9 | +""" |
| 10 | + |
| 11 | +import contextlib |
| 12 | +import os |
| 13 | +import shutil |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +# Next to `snapshots` in the cache of a huggingface_hub repo: `onnx_snapshots/<revision>/...` |
| 17 | +ONNX_SNAPSHOTS_DIR = "onnx_snapshots" |
| 18 | + |
| 19 | + |
| 20 | +def link_external_data(model_dir: Path, model_file: str, additional_files: list[str]) -> Path: |
| 21 | + """Returns a path of `model_file` from which onnxruntime can load its external data. |
| 22 | +
|
| 23 | + Args: |
| 24 | + model_dir (Path): The directory with the model files, e.g. a huggingface_hub snapshot. |
| 25 | + model_file (str): The path of the ONNX file, relative to `model_dir`. |
| 26 | + additional_files (list[str]): Other files of the model, relative to `model_dir`, |
| 27 | + among which its external data. |
| 28 | +
|
| 29 | + Returns: |
| 30 | + Path: The ONNX file to load, `model_dir / model_file` unless it had to be linked. |
| 31 | +
|
| 32 | + Raises: |
| 33 | + OSError: If the files had to be linked, but couldn't be, e.g. in a read-only cache or |
| 34 | + on a filesystem without hardlinks. |
| 35 | + """ |
| 36 | + model_path = model_dir / model_file |
| 37 | + snapshots_dir = model_dir.parent |
| 38 | + repo_dir = snapshots_dir.parent |
| 39 | + if snapshots_dir.name != "snapshots" or not repo_dir.name.startswith("models--"): |
| 40 | + return model_path # not a huggingface_hub cache, there is no place of ours to link into |
| 41 | + if not model_path.exists(): |
| 42 | + return model_path # onnxruntime reports it more clearly than a failed hardlink would |
| 43 | + |
| 44 | + # external data is located relative to the model file, so it can't be anywhere else |
| 45 | + data_paths = [ |
| 46 | + path |
| 47 | + for path in (model_dir / file for file in additional_files) |
| 48 | + if path.parent.is_relative_to(model_path.parent) and path.exists() |
| 49 | + ] |
| 50 | + # onnxruntime accepts data within these, as in the caches of older huggingface_hub versions |
| 51 | + real_model_dirs = ( |
| 52 | + os.path.realpath(model_path.parent), |
| 53 | + os.path.dirname(os.path.realpath(model_path)), |
| 54 | + ) |
| 55 | + if all( |
| 56 | + any(Path(os.path.realpath(path)).is_relative_to(d) for d in real_model_dirs) |
| 57 | + for path in data_paths |
| 58 | + ): |
| 59 | + return model_path |
| 60 | + |
| 61 | + links_dir = repo_dir / ONNX_SNAPSHOTS_DIR |
| 62 | + for path in (model_path, *data_paths): |
| 63 | + _link_file(path, links_dir / model_dir.name / path.relative_to(model_dir)) |
| 64 | + |
| 65 | + # the links keep the blobs on disk, so drop those of revisions deleted from the cache |
| 66 | + for revision_dir in links_dir.iterdir(): |
| 67 | + if not (snapshots_dir / revision_dir.name).is_dir(): |
| 68 | + shutil.rmtree(revision_dir, ignore_errors=True) |
| 69 | + |
| 70 | + return links_dir / model_dir.name / model_file |
| 71 | + |
| 72 | + |
| 73 | +def _link_file(source: Path, link: Path) -> None: |
| 74 | + """Makes `link` a hardlink to the file `source` resolves to, unless it already is one.""" |
| 75 | + target = os.path.realpath(source) |
| 76 | + try: |
| 77 | + if os.path.samefile(link, target): |
| 78 | + return |
| 79 | + # a link to a blob downloaded again since, or a copy of the cache without its hardlinks |
| 80 | + link.unlink() |
| 81 | + except FileNotFoundError: |
| 82 | + pass |
| 83 | + except OSError: |
| 84 | + # e.g. such a copy on a read-only filesystem, which works all the same |
| 85 | + if os.path.getsize(link) != os.path.getsize(target): |
| 86 | + raise |
| 87 | + return |
| 88 | + link.parent.mkdir(parents=True, exist_ok=True) |
| 89 | + # os.link is atomic, so if the link exists, another process loading the model just made it |
| 90 | + with contextlib.suppress(FileExistsError): |
| 91 | + os.link(target, link) |
0 commit comments