|
| 1 | +""" |
| 2 | +@huggingface step decorator: pluggable auth for HuggingFace models (Part 1). |
| 3 | +
|
| 4 | +Provides current.huggingface.models[key] -> local path. Supports models=[] and |
| 5 | +model_mapping={alias: repo_id@revision}. Uses huggingface_hub for download. |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +from typing import Dict, List, Optional, Tuple |
| 10 | + |
| 11 | +from metaflow.decorators import StepDecorator |
| 12 | +from metaflow.exception import MetaflowException |
| 13 | +from metaflow.metaflow_current import current |
| 14 | + |
| 15 | + |
| 16 | +# Minimal object exposed as current.huggingface with a .models mapping |
| 17 | +class HuggingFaceContext: |
| 18 | + """ |
| 19 | + Context object attached to current.huggingface when @huggingface is used. |
| 20 | + models maps user-facing key (alias or repo_id) to local filesystem path (str). |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, models: Dict[str, str]): |
| 24 | + self.models = models |
| 25 | + |
| 26 | + |
| 27 | +def _parse_repo_spec(value: str) -> Tuple[str, str]: |
| 28 | + """Parse 'repo_id' or 'repo_id@revision' into (repo_id, revision).""" |
| 29 | + value = (value or "").strip() |
| 30 | + if not value: |
| 31 | + raise MetaflowException( |
| 32 | + "@huggingface: empty model spec; use repo_id or repo_id@revision" |
| 33 | + ) |
| 34 | + if "@" in value: |
| 35 | + repo_id, revision = value.rsplit("@", 1) |
| 36 | + repo_id = repo_id.strip() |
| 37 | + revision = revision.strip() |
| 38 | + if not repo_id or not revision: |
| 39 | + raise MetaflowException( |
| 40 | + "@huggingface: invalid spec '%s'; use repo_id@revision" % value |
| 41 | + ) |
| 42 | + return repo_id, revision |
| 43 | + return value, "main" |
| 44 | + |
| 45 | + |
| 46 | +def _build_spec_map( |
| 47 | + models: Optional[List[str]], model_mapping: Optional[Dict[str, str]] |
| 48 | +) -> Dict[str, Tuple[str, str]]: |
| 49 | + """Build key -> (repo_id, revision). Key is alias or repo_id.""" |
| 50 | + spec_map = {} |
| 51 | + if models: |
| 52 | + for v in models: |
| 53 | + if not isinstance(v, str): |
| 54 | + raise MetaflowException( |
| 55 | + "@huggingface: models must be a list of strings, got %s" % type(v) |
| 56 | + ) |
| 57 | + repo_id, revision = _parse_repo_spec(v) |
| 58 | + spec_map[repo_id] = (repo_id, revision) |
| 59 | + if model_mapping: |
| 60 | + for k, v in model_mapping.items(): |
| 61 | + if not isinstance(k, str) or not isinstance(v, str): |
| 62 | + raise MetaflowException( |
| 63 | + "@huggingface: model_mapping must be dict of str -> str" |
| 64 | + ) |
| 65 | + repo_id, revision = _parse_repo_spec(v) |
| 66 | + spec_map[k] = (repo_id, revision) |
| 67 | + return spec_map |
| 68 | + |
| 69 | + |
| 70 | +def _get_auth_provider(): |
| 71 | + from metaflow.metaflow_config import METAFLOW_HUGGINGFACE_AUTH_PROVIDER |
| 72 | + from metaflow.plugins import HF_AUTH_PROVIDERS |
| 73 | + |
| 74 | + provider_type = METAFLOW_HUGGINGFACE_AUTH_PROVIDER or "env" |
| 75 | + provider_cls = next( |
| 76 | + (p for p in HF_AUTH_PROVIDERS if getattr(p, "TYPE", None) == provider_type), |
| 77 | + None, |
| 78 | + ) |
| 79 | + if provider_cls is None: |
| 80 | + from metaflow.plugins.huggingface.env_auth_provider import ( |
| 81 | + EnvHuggingFaceAuthProvider, |
| 82 | + ) |
| 83 | + |
| 84 | + return EnvHuggingFaceAuthProvider() |
| 85 | + return provider_cls() |
| 86 | + |
| 87 | + |
| 88 | +def _download_model( |
| 89 | + repo_id: str, revision: str, token: Optional[str], local_dir: str |
| 90 | +) -> str: |
| 91 | + try: |
| 92 | + from huggingface_hub import snapshot_download |
| 93 | + except ImportError as e: |
| 94 | + raise MetaflowException( |
| 95 | + "@huggingface requires the 'huggingface_hub' package. " |
| 96 | + "Install it with: pip install huggingface_hub. Error: %s" % e |
| 97 | + ) from e |
| 98 | + path = snapshot_download( |
| 99 | + repo_id=repo_id, |
| 100 | + revision=revision, |
| 101 | + token=token, |
| 102 | + local_dir=local_dir, |
| 103 | + local_dir_use_symlinks=False, |
| 104 | + ) |
| 105 | + return path |
| 106 | + |
| 107 | + |
| 108 | +class HuggingFaceDecorator(StepDecorator): |
| 109 | + """ |
| 110 | + Declares HuggingFace models needed for this step. Auth is pluggable; |
| 111 | + model paths are exposed via current.huggingface.models[key]. |
| 112 | +
|
| 113 | + Parameters |
| 114 | + ---------- |
| 115 | + models : list, optional |
| 116 | + List of repo ids (and optional revisions), e.g. |
| 117 | + ["meta-llama/Llama-2-7b", "bert-base-uncased@v1.0"]. |
| 118 | + model_mapping : dict, optional |
| 119 | + Alias -> repo spec, e.g. |
| 120 | + {"llama": "meta-llama/Llama-2-7b@main", "bert": "bert-base-uncased"}. |
| 121 | + Access in step via current.huggingface.models["llama"]. |
| 122 | +
|
| 123 | + MF Add To Current |
| 124 | + ----------------- |
| 125 | + huggingface -> HuggingFaceContext |
| 126 | + Object with a ``models`` attribute: dict-like mapping from model key |
| 127 | + (alias or repo_id) to local filesystem path (str). Use |
| 128 | + current.huggingface.models["key"] to get the path for loading with |
| 129 | + transformers or other HF APIs. |
| 130 | + """ |
| 131 | + |
| 132 | + name = "huggingface" |
| 133 | + defaults = {"models": None, "model_mapping": None} |
| 134 | + |
| 135 | + def step_init( |
| 136 | + self, flow, graph, step_name, decorators, environment, flow_datastore, logger |
| 137 | + ): |
| 138 | + models = self.attributes.get("models") |
| 139 | + model_mapping = self.attributes.get("model_mapping") |
| 140 | + if not models and not model_mapping: |
| 141 | + raise MetaflowException( |
| 142 | + "@huggingface: specify at least one of 'models' or 'model_mapping'" |
| 143 | + ) |
| 144 | + self._spec_map = _build_spec_map(models, model_mapping) |
| 145 | + if not self._spec_map: |
| 146 | + raise MetaflowException( |
| 147 | + "@huggingface: at least one model or model_mapping entry is required" |
| 148 | + ) |
| 149 | + |
| 150 | + def task_pre_step( |
| 151 | + self, |
| 152 | + step_name, |
| 153 | + task_datastore, |
| 154 | + metadata, |
| 155 | + run_id, |
| 156 | + task_id, |
| 157 | + flow, |
| 158 | + graph, |
| 159 | + retry_count, |
| 160 | + max_user_code_retries, |
| 161 | + ubf_context, |
| 162 | + inputs, |
| 163 | + ): |
| 164 | + token = None |
| 165 | + try: |
| 166 | + auth_provider = _get_auth_provider() |
| 167 | + token = auth_provider.get_token() |
| 168 | + except Exception as e: |
| 169 | + raise MetaflowException( |
| 170 | + "@huggingface: auth provider failed: %s" % e |
| 171 | + ) from e |
| 172 | + |
| 173 | + base_dir = os.path.join(current.tempdir or "/tmp", "metaflow_huggingface") |
| 174 | + os.makedirs(base_dir, exist_ok=True) |
| 175 | + path_map = {} # key -> local path |
| 176 | + |
| 177 | + for key, (repo_id, revision) in self._spec_map.items(): |
| 178 | + task_subdir = os.path.join( |
| 179 | + base_dir, "%s_%s" % (repo_id.replace("/", "_"), revision) |
| 180 | + ) |
| 181 | + local_path = _download_model(repo_id, revision, token, task_subdir) |
| 182 | + path_map[key] = local_path |
| 183 | + |
| 184 | + ctx = HuggingFaceContext(models=path_map) |
| 185 | + current._update_env({"huggingface": ctx}) |
0 commit comments