| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import argparse |
| 8 | import asyncio |
| 9 | import json |
| 10 | import os |
| 11 | import shutil |
| 12 | import time |
| 13 | from datetime import datetime |
| 14 | from functools import partial |
| 15 | from pathlib import Path |
| 16 | from typing import Dict, List |
| 17 | |
| 18 | import httpx |
| 19 | from pydantic import BaseModel |
| 20 | |
| 21 | from termcolor import cprint |
| 22 | |
| 23 | from llama_stack.cli.subcommand import Subcommand |
| 24 | |
| 25 | |
| 26 | class Download(Subcommand): |
| 27 | """Llama cli for downloading llama toolchain assets""" |
| 28 | |
| 29 | def __init__(self, subparsers: argparse._SubParsersAction): |
| 30 | super().__init__() |
| 31 | self.parser = subparsers.add_parser( |
| 32 | "download", |
| 33 | prog="llama download", |
| 34 | description="Download a model from llama.meta.com or Hugging Face Hub", |
| 35 | formatter_class=argparse.RawTextHelpFormatter, |
| 36 | ) |
| 37 | setup_download_parser(self.parser) |
| 38 | |
| 39 | |
| 40 | def setup_download_parser(parser: argparse.ArgumentParser) -> None: |
| 41 | from llama_models.sku_list import all_registered_models |
| 42 | |
| 43 | models = all_registered_models() |
| 44 | parser.add_argument( |
| 45 | "--source", |
| 46 | choices=["meta", "huggingface"], |
| 47 | default="meta", |
| 48 | ) |
| 49 | parser.add_argument( |
| 50 | "--model-id", |
| 51 | required=False, |
| 52 | help="See `llama model list` or `llama model list --show-all` for the list of available models", |
| 53 | ) |
| 54 | parser.add_argument( |
| 55 | "--hf-token", |
| 56 | type=str, |
| 57 | required=False, |
| 58 | default=None, |
| 59 | help="Hugging Face API token. Needed for gated models like llama2/3. Will also try to read environment variable `HF_TOKEN` as default.", |
| 60 | ) |
| 61 | parser.add_argument( |
| 62 | "--meta-url", |
| 63 | type=str, |
| 64 | required=False, |
| 65 | help="For source=meta, URL obtained from llama.meta.com after accepting license terms", |
| 66 | ) |
| 67 | parser.add_argument( |
| 68 | "--ignore-patterns", |
| 69 | type=str, |
| 70 | required=False, |
| 71 | default="*.safetensors", |
| 72 | help=""" |
| 73 | For source=huggingface, files matching any of the patterns are not downloaded. Defaults to ignoring |
| 74 | safetensors files to avoid downloading duplicate weights. |
| 75 | """, |
| 76 | ) |
| 77 | parser.add_argument( |
| 78 | "--manifest-file", |
| 79 | type=str, |
| 80 | help="For source=meta, you can download models from a manifest file containing a file => URL mapping", |
| 81 | required=False, |
| 82 | ) |
| 83 | parser.set_defaults(func=partial(run_download_cmd, parser=parser)) |
| 84 | |
| 85 | |
| 86 | def _hf_download( |
| 87 | model: "Model", |
| 88 | hf_token: str, |
| 89 | ignore_patterns: str, |
| 90 | parser: argparse.ArgumentParser, |
| 91 | ): |
| 92 | from huggingface_hub import snapshot_download |
| 93 | from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError |
| 94 | |
| 95 | from llama_stack.distribution.utils.model_utils import model_local_dir |
| 96 | |
| 97 | repo_id = model.huggingface_repo |
| 98 | if repo_id is None: |
| 99 | raise ValueError(f"No repo id found for model {model.descriptor()}") |
| 100 | |
| 101 | output_dir = model_local_dir(model.descriptor()) |
| 102 | os.makedirs(output_dir, exist_ok=True) |
| 103 | try: |
| 104 | true_output_dir = snapshot_download( |
| 105 | repo_id, |
| 106 | local_dir=output_dir, |
| 107 | ignore_patterns=ignore_patterns, |
| 108 | token=hf_token, |
| 109 | library_name="llama-stack", |
| 110 | ) |
| 111 | except GatedRepoError: |
| 112 | parser.error( |
| 113 | "It looks like you are trying to access a gated repository. Please ensure you " |
| 114 | "have access to the repository and have provided the proper Hugging Face API token " |
| 115 | "using the option `--hf-token` or by running `huggingface-cli login`." |
| 116 | "You can find your token by visiting https://huggingface.co/settings/tokens" |
| 117 | ) |
| 118 | except RepositoryNotFoundError: |
| 119 | parser.error(f"Repository '{repo_id}' not found on the Hugging Face Hub.") |
| 120 | except Exception as e: |
| 121 | parser.error(e) |
| 122 | |
| 123 | print(f"\nSuccessfully downloaded model to {true_output_dir}") |
| 124 | |
| 125 | |
| 126 | def _meta_download(model: "Model", meta_url: str): |
| 127 | from llama_models.sku_list import llama_meta_net_info |
| 128 | |
| 129 | from llama_stack.distribution.utils.model_utils import model_local_dir |
| 130 | |
| 131 | output_dir = Path(model_local_dir(model.descriptor())) |
| 132 | os.makedirs(output_dir, exist_ok=True) |
| 133 | |
| 134 | info = llama_meta_net_info(model) |
| 135 | |
| 136 | # I believe we can use some concurrency here if needed but not sure it is worth it |
| 137 | for f in info.files: |
| 138 | output_file = str(output_dir / f) |
| 139 | url = meta_url.replace("*", f"{info.folder}/{f}") |
| 140 | total_size = info.pth_size if "consolidated" in f else 0 |
| 141 | cprint(f"Downloading `{f}`...", "white") |
| 142 | downloader = ResumableDownloader(url, output_file, total_size) |
| 143 | asyncio.run(downloader.download()) |
| 144 | |
| 145 | print(f"\nSuccessfully downloaded model to {output_dir}") |
| 146 | cprint(f"\nMD5 Checksums are at: {output_dir / 'checklist.chk'}", "white") |
| 147 | |
| 148 | |
| 149 | def run_download_cmd(args: argparse.Namespace, parser: argparse.ArgumentParser): |
| 150 | from llama_models.sku_list import resolve_model |
| 151 | |
| 152 | if args.manifest_file: |
| 153 | _download_from_manifest(args.manifest_file) |
| 154 | return |
| 155 | |
| 156 | if args.model_id is None: |
| 157 | parser.error("Please provide a model id") |
| 158 | return |
| 159 | |
| 160 | model = resolve_model(args.model_id) |
| 161 | if model is None: |
| 162 | parser.error(f"Model {args.model_id} not found") |
| 163 | return |
| 164 | |
| 165 | if args.source == "huggingface": |
| 166 | _hf_download(model, args.hf_token, args.ignore_patterns, parser) |
| 167 | else: |
| 168 | meta_url = args.meta_url |
| 169 | if not meta_url: |
| 170 | meta_url = input( |
| 171 | "Please provide the signed URL you received via email (e.g., https://llama3-1.llamameta.net/*?Policy...): " |
| 172 | ) |
| 173 | assert meta_url is not None and "llamameta.net" in meta_url |
| 174 | _meta_download(model, meta_url) |
| 175 | |
| 176 | |
| 177 | class ModelEntry(BaseModel): |
| 178 | model_id: str |
| 179 | files: Dict[str, str] |
| 180 | |
| 181 | class Config: |
| 182 | protected_namespaces = () |
| 183 | |
| 184 | |
| 185 | class Manifest(BaseModel): |
| 186 | models: List[ModelEntry] |
| 187 | expires_on: datetime |
| 188 | |
| 189 | |
| 190 | def _download_from_manifest(manifest_file: str): |
| 191 | from llama_stack.distribution.utils.model_utils import model_local_dir |
| 192 | |
| 193 | with open(manifest_file, "r") as f: |
| 194 | d = json.load(f) |
| 195 | manifest = Manifest(**d) |
| 196 | |
| 197 | if datetime.now() > manifest.expires_on: |
| 198 | raise ValueError(f"Manifest URLs have expired on {manifest.expires_on}") |
| 199 | |
| 200 | for entry in manifest.models: |
| 201 | print(f"Downloading model {entry.model_id}...") |
| 202 | output_dir = Path(model_local_dir(entry.model_id)) |
| 203 | os.makedirs(output_dir, exist_ok=True) |
| 204 | |
| 205 | if any(output_dir.iterdir()): |
| 206 | cprint(f"Output directory {output_dir} is not empty.", "red") |
| 207 | |
| 208 | while True: |
| 209 | resp = input( |
| 210 | "Do you want to (C)ontinue download or (R)estart completely? (continue/restart): " |
| 211 | ) |
| 212 | if resp.lower() == "restart" or resp.lower() == "r": |
| 213 | shutil.rmtree(output_dir) |
| 214 | os.makedirs(output_dir, exist_ok=True) |
| 215 | break |
| 216 | elif resp.lower() == "continue" or resp.lower() == "c": |
| 217 | print("Continuing download...") |
| 218 | break |
| 219 | else: |
| 220 | cprint("Invalid response. Please try again.", "red") |
| 221 | |
| 222 | for fname, url in entry.files.items(): |
| 223 | output_file = str(output_dir / fname) |
| 224 | downloader = ResumableDownloader(url, output_file) |
| 225 | asyncio.run(downloader.download()) |
| 226 | |
| 227 | |
| 228 | class ResumableDownloader: |
| 229 | def __init__( |
| 230 | self, |
| 231 | url: str, |
| 232 | output_file: str, |
| 233 | total_size: int = 0, |
| 234 | buffer_size: int = 32 * 1024, |
| 235 | ): |
| 236 | self.url = url |
| 237 | self.output_file = output_file |
| 238 | self.buffer_size = buffer_size |
| 239 | self.total_size = total_size |
| 240 | self.downloaded_size = 0 |
| 241 | self.start_size = 0 |
| 242 | self.start_time = 0 |
| 243 | |
| 244 | async def get_file_info(self, client: httpx.AsyncClient) -> None: |
| 245 | if self.total_size > 0: |
| 246 | return |
| 247 | |
| 248 | # Force disable compression when trying to retrieve file size |
| 249 | response = await client.head( |
| 250 | self.url, follow_redirects=True, headers={"Accept-Encoding": "identity"} |
| 251 | ) |
| 252 | response.raise_for_status() |
| 253 | self.url = str(response.url) # Update URL in case of redirects |
| 254 | self.total_size = int(response.headers.get("Content-Length", 0)) |
| 255 | if self.total_size == 0: |
| 256 | raise ValueError( |
| 257 | "Unable to determine file size. The server might not support range requests." |
| 258 | ) |
| 259 | |
| 260 | async def download(self) -> None: |
| 261 | self.start_time = time.time() |
| 262 | async with httpx.AsyncClient(follow_redirects=True) as client: |
| 263 | await self.get_file_info(client) |
| 264 | |
| 265 | if os.path.exists(self.output_file): |
| 266 | self.downloaded_size = os.path.getsize(self.output_file) |
| 267 | self.start_size = self.downloaded_size |
| 268 | if self.downloaded_size >= self.total_size: |
| 269 | print(f"Already downloaded `{self.output_file}`, skipping...") |
| 270 | return |
| 271 | |
| 272 | additional_size = self.total_size - self.downloaded_size |
| 273 | if not self.has_disk_space(additional_size): |
| 274 | M = 1024 * 1024 # noqa |
| 275 | print( |
| 276 | f"Not enough disk space to download `{self.output_file}`. " |
| 277 | f"Required: {(additional_size // M):.2f} MB" |
| 278 | ) |
| 279 | raise ValueError( |
| 280 | f"Not enough disk space to download `{self.output_file}`" |
| 281 | ) |
| 282 | |
| 283 | while True: |
| 284 | if self.downloaded_size >= self.total_size: |
| 285 | break |
| 286 | |
| 287 | # Cloudfront has a max-size limit |
| 288 | max_chunk_size = 27_000_000_000 |
| 289 | request_size = min( |
| 290 | self.total_size - self.downloaded_size, max_chunk_size |
| 291 | ) |
| 292 | headers = { |
| 293 | "Range": f"bytes={self.downloaded_size}-{self.downloaded_size + request_size}" |
| 294 | } |
| 295 | print(f"Downloading `{self.output_file}`....{headers}") |
| 296 | try: |
| 297 | async with client.stream( |
| 298 | "GET", self.url, headers=headers |
| 299 | ) as response: |
| 300 | response.raise_for_status() |
| 301 | with open(self.output_file, "ab") as file: |
| 302 | async for chunk in response.aiter_bytes(self.buffer_size): |
| 303 | file.write(chunk) |
| 304 | self.downloaded_size += len(chunk) |
| 305 | self.print_progress() |
| 306 | except httpx.HTTPError as e: |
| 307 | print(f"\nDownload interrupted: {e}") |
| 308 | print("You can resume the download by running the script again.") |
| 309 | except Exception as e: |
| 310 | print(f"\nAn error occurred: {e}") |
| 311 | |
| 312 | print(f"\nFinished downloading `{self.output_file}`....") |
| 313 | |
| 314 | def print_progress(self) -> None: |
| 315 | percent = (self.downloaded_size / self.total_size) * 100 |
| 316 | bar_length = 50 |
| 317 | filled_length = int(bar_length * self.downloaded_size // self.total_size) |
| 318 | bar = "█" * filled_length + "-" * (bar_length - filled_length) |
| 319 | |
| 320 | elapsed_time = time.time() - self.start_time |
| 321 | M = 1024 * 1024 # noqa |
| 322 | |
| 323 | speed = ( |
| 324 | (self.downloaded_size - self.start_size) / (elapsed_time * M) |
| 325 | if elapsed_time > 0 |
| 326 | else 0 |
| 327 | ) |
| 328 | print( |
| 329 | f"\rProgress: |{bar}| {percent:.2f}% " |
| 330 | f"({self.downloaded_size // M}/{self.total_size // M} MB) " |
| 331 | f"Speed: {speed:.2f} MiB/s", |
| 332 | end="", |
| 333 | flush=True, |
| 334 | ) |
| 335 | |
| 336 | def has_disk_space(self, file_size: int) -> bool: |
| 337 | dir_path = os.path.dirname(os.path.abspath(self.output_file)) |
| 338 | free_space = shutil.disk_usage(dir_path).free |
| 339 | return free_space > file_size |