tempest_fastapi_sdk.genai.hub¶
Ciclo de vida dos pesos do HuggingFace que o serviço hospeda: download, cache e verificação.
hub
¶
Weight lifecycle for the HuggingFace models a service self-hosts.
Loading a model by id is the easy half. The other half is everything the
first from_pretrained call hides: which commit you actually got, how
many gigabytes it wrote to which directory, whether the disk had room,
and how to make the next boot reproduce the same weights without a
network.
This module owns that half.
- :class:
ModelRef— the identity of a set of weights (id + revision + cache + token + offline/remote-code flags). Every loader in :mod:tempest_fastapi_sdk.genaibuilds one and forwards it, so pinning a revision is the same keyword everywhere. - :func:
resolve_revision— turn a moving branch ("main") into the immutable commit sha to pin in configuration. - :func:
model_disk_bytes— how much the repo weighs, read from the Hub metadata, without downloading it. - :func:
download_model— fetch the weights ahead of the first request (image build, deploy step, warm-up task), refusing to start when the disk cannot hold them. - :func:
list_cached_models/ :func:cache_size_bytes/ :func:remove_cached_model— see and reclaim what the cache holds.
huggingface_hub is imported inside the functions that need it, so
this module imports with no extra installed and the schemas stay usable
(and testable) on a host that will never download anything.
ModelRef
¶
Bases: BaseSchema
Everything needed to resolve one set of weights, reproducibly.
A bare model id names a moving target: the author pushes to main
and the next restart loads different weights. Pinning revision
to a commit sha (see :func:resolve_revision) makes a deployment
reproducible and removes a supply-chain surface — the weights a
service runs stop depending on when it happened to boot.
Example:
>>> ref = ModelRef(
... model_id="Qwen/Qwen2.5-0.5B-Instruct",
... revision="a8b602d",
... local_files_only=True,
... )
>>> ref.loader_kwargs()
{'revision': 'a8b602d', 'local_files_only': True}
Attributes:
| Name | Type | Description |
|---|---|---|
model_id |
str
|
The Hub model id ( |
revision |
str | None
|
Branch, tag or commit sha. |
cache_dir |
str | None
|
Where weights are cached. |
token |
str | None
|
Hub token for gated or private repositories.
|
local_files_only |
bool | None
|
When |
trust_remote_code |
bool
|
When |
loader_kwargs
¶
Return the from_pretrained keywords this ref implies.
Only non-default values are emitted. That keeps the call
byte-identical to what the loaders sent before this ref existed
when nothing was pinned, and it keeps the same dictionary usable
with narrower loaders (tokenizers.Tokenizer.from_pretrained
accepts revision but not trust_remote_code).
model_id is not included — it is the positional argument.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Keywords to splat into |
download_kwargs
¶
Return the snapshot_download keywords this ref implies.
Same values as :meth:loader_kwargs minus trust_remote_code,
which is a load-time decision and means nothing while fetching
files.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Keywords to splat into |
ModelSnapshot
¶
Bases: BaseSchema
The result of materializing one revision on local disk.
Attributes:
| Name | Type | Description |
|---|---|---|
model_id |
str
|
The Hub model id that was downloaded. |
revision |
str | None
|
The revision asked for ( |
path |
str
|
Local directory holding the snapshot. |
size_bytes |
int
|
Total size of the downloaded files. |
file_count |
int
|
Number of files in the snapshot. |
CachedRevision
¶
Bases: BaseSchema
One revision of a model present in the local cache.
Attributes:
| Name | Type | Description |
|---|---|---|
revision |
str
|
The commit sha the snapshot belongs to. |
refs |
list[str]
|
Branch/tag names pointing at this commit. |
size_bytes |
int
|
Bytes this revision occupies on disk. |
path |
str
|
The snapshot directory. |
last_modified |
float | None
|
Unix timestamp of the last change,
or |
CachedModel
¶
Bases: BaseSchema
One model repository present in the local cache.
Attributes:
| Name | Type | Description |
|---|---|---|
model_id |
str
|
The Hub model id. |
size_bytes |
int
|
Total bytes the repository occupies, counting every cached revision once (blobs shared between revisions are not double-counted). |
path |
str
|
The repository directory inside the cache. |
revisions |
list[CachedRevision]
|
The cached revisions, largest first. |
resolve_revision
¶
resolve_revision(
model_id: str, *, revision: str = "main", token: str | None = None
) -> str | None
Resolve a branch or tag to the immutable commit sha behind it.
Pin the returned sha in configuration and the service stops loading
whatever main happens to hold at boot.
Example:
>>> sha = resolve_revision("Qwen/Qwen2.5-0.5B-Instruct")
>>> isinstance(sha, str) or sha is None
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
The Hub model id. |
required |
revision
|
str
|
Branch, tag or sha to resolve. Defaults to
|
'main'
|
token
|
str | None
|
Token for gated or private repositories. |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The commit sha, or |
str | None
|
reached or the repository/revision does not exist. Callers treat |
str | None
|
|
str | None
|
silently — the caller decides whether to proceed unpinned. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
model_disk_bytes
¶
model_disk_bytes(
model_id: str,
*,
revision: str | None = None,
token: str | None = None,
allow_patterns: list[str] | None = None,
ignore_patterns: list[str] | None = None,
) -> int | None
Return how many bytes a repository would occupy, without fetching it.
Reads the file sizes from the Hub metadata. Use it to decide whether
a download is worth starting — :func:can_run sizes RAM and VRAM,
this sizes the disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
The Hub model id. |
required |
revision
|
str | None
|
Branch, tag or sha; |
None
|
token
|
str | None
|
Token for gated or private repositories. |
None
|
allow_patterns
|
list[str] | None
|
Count only files matching these
globs — the same filter :func: |
None
|
ignore_patterns
|
list[str] | None
|
Leave out files matching these globs. |
None
|
Returns:
| Type | Description |
|---|---|
int | None
|
int | None: Total size in bytes of the selected files, or |
int | None
|
when the Hub is unreachable or reports no per-file sizes. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
download_model
¶
download_model(
model_id: str,
*,
revision: str | None = None,
cache_dir: str | None = None,
token: str | None = None,
local_files_only: bool | None = None,
allow_patterns: list[str] | None = None,
ignore_patterns: list[str] | None = None,
check_disk: bool = True,
disk_margin: float = 1.1,
) -> ModelSnapshot
Materialize a model's weights on local disk, ahead of first use.
Left to itself, the first /generate request pays for a
multi-gigabyte download inside the request. Call this from the image
build, the deploy step or a warm-up task instead, and the request
path only ever loads from disk.
check_disk refuses to start a download the filesystem cannot
hold. Failing in two seconds with a number beats failing forty
minutes later with a half-written cache. The estimate counts only the
files allow_patterns / ignore_patterns select (filtered by the
same huggingface_hub function snapshot_download uses) and
leaves out the ones already in the cache for that revision.
Example:
>>> snapshot = download_model(
... "Qwen/Qwen2.5-0.5B-Instruct",
... revision="main",
... allow_patterns=["*.json", "*.safetensors"],
... )
>>> snapshot.size_bytes > 0
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
The Hub model id. |
required |
revision
|
str | None
|
Branch, tag or sha; |
None
|
cache_dir
|
str | None
|
Where to write; |
None
|
token
|
str | None
|
Token for gated or private repositories. |
None
|
local_files_only
|
bool
|
Resolve from the cache without touching the network (turns this call into a "is it already here?" check). |
None
|
allow_patterns
|
list[str] | None
|
Only fetch files matching
these globs — e.g. skip the |
None
|
ignore_patterns
|
list[str] | None
|
Skip files matching these globs. |
None
|
check_disk
|
bool
|
Verify free space before downloading — the bytes of the selected files that are not cached yet. |
True
|
disk_margin
|
float
|
Multiplier applied to the estimated size for the free-space check. The default 1.1 covers the temporary files the download writes next to the blobs. |
1.1
|
Returns:
| Name | Type | Description |
|---|---|---|
ModelSnapshot |
ModelSnapshot
|
Where the weights landed, how big they are and |
ModelSnapshot
|
how many files they span. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
OSError
|
When |
list_cached_models
¶
list_cached_models(cache_dir: str | None = None) -> list[CachedModel]
Report the models currently held in the local weight cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
str | None
|
The cache to scan; |
None
|
Returns:
| Type | Description |
|---|---|
list[CachedModel]
|
list[CachedModel]: One entry per cached model repository, largest |
list[CachedModel]
|
first. Empty when the cache directory does not exist yet — an |
list[CachedModel]
|
empty cache is a valid state, not an error. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
cache_size_bytes
¶
Return the total size of the cached model repositories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
str | None
|
The cache to scan; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total bytes across every cached model, or |
int
|
cache does not exist yet. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
remove_cached_model
¶
remove_cached_model(
model_id: str,
*,
revision: str | None = None,
cache_dir: str | None = None,
dry_run: bool = False,
) -> int
Delete a model from the local cache and report the space freed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
The Hub model id to remove. |
required |
revision
|
str | None
|
Remove only this revision (sha or ref
name). |
None
|
cache_dir
|
str | None
|
The cache to operate on; |
None
|
dry_run
|
bool
|
Compute the freed size without deleting. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Bytes freed (or that would be freed under |
int
|
|
|
int
|
which is a successful no-op rather than an error. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |