Hub Python Library documentation

Buckets

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Buckets

Los buckets proporcionan almacenamiento de objetos similar a S3 en Hugging Face, impulsado por el backend de almacenamiento Xet. A diferencia de los repositorios (que se basan en git y rastrean el historial de archivos), los buckets son contenedores de almacenamiento de objetos remotos diseñados para archivos a gran escala con deduplicación direccionable por contenido. Están diseñados para casos de uso en los que se necesita un almacenamiento simple, rápido y mutable, como el almacenamiento de puntos de control de entrenamiento, registros, artefactos intermedios o cualquier colección grande de archivos que no requiera control de versiones.

Puede interactuar con los buckets mediante la API de Python (HfApi) o la CLI (hf buckets). En esta guía, repasaremos todas las operaciones disponibles.

Todos los comandos de la CLI están disponibles bajo hf buckets <command>. Ejecuta hf buckets --help para obtener más información.

Crear y gestionar cubos

Crear un bucket

Crea un bucket con create_bucket(). Debes proporcionar un nombre de bucket. Si no especificas un namespace, el bucket se crea bajo tu nombre de usuario.

>>> from huggingface_hub import create_bucket

# Create a bucket under your namespace
>>> url = create_bucket("my-bucket")
>>> url.bucket_id
'username/my-bucket'
>>> url.uri.to_uri()
'hf://buckets/username/my-bucket'

# Create a private bucket
>>> create_bucket("my-private-bucket", private=True)
BucketUrl(...)

# Don't error if bucket already exists
>>> create_bucket("my-bucket", exist_ok=True)
BucketUrl(...)

# Create a bucket in a specific region
>>> create_bucket("my-bucket", region="us")
BucketUrl(...)

O mediante la CLI:

>>> hf buckets create my-bucket
✓ Bucket created
  uri: hf://buckets/Wauplin/my-bucket
  url: https://huggingface.co/buckets/Wauplin/my-bucket

# Create a private bucket
>>> hf buckets create my-bucket --private

# Don't error if bucket already exists
>>> hf buckets create my-bucket --exist-ok

# Create a bucket in a specific region
>>> hf buckets create my-bucket --region us

También puede especificar el formato completo namespace/bucket_name para crear un bucket bajo una organización:

>>> from huggingface_hub import create_bucket
>>> create_bucket("my-org/shared-bucket")

O mediante la CLI:

>>> hf buckets create my-org/shared-bucket

Obtener información del bucket

Use bucket_info() para obtener metadatos sobre un bucket, incluida su visibilidad, tamaño total, número de archivos y fecha de creación.

>>> from huggingface_hub import bucket_info
>>> bucket_info("username/my-bucket")
BucketInfo(
  id='username/my-bucket',
  private=False,
  created_at=datetime.datetime(2026, 2, 12, 17, 42, 12,
  tzinfo=datetime.timezone.utc),
  size=8411791508,
  total_files=128
)

O mediante la CLI:

# JSON output
>>> hf buckets info username/my-bucket
{
  "id": "username/my-bucket",
  "private": false,
  ...
}

Listar cubos

Use list_buckets() para listar todos los buckets de un namespace. De forma predeterminada, lista los buckets del namespace del usuario actual.

>>> from huggingface_hub import list_buckets

# List your own buckets
>>> for bucket in list_buckets():
...     print(bucket.id, bucket.size, bucket.total_files)

# List buckets in an organization
>>> for bucket in list_buckets(namespace="huggingface"):
...     print(bucket.id)

O mediante la CLI (hf buckets ls es una abreviatura de hf buckets list):

# Table format (default)
>>> hf buckets list
ID                   PRIVATE      SIZE TOTAL_FILES CREATED_AT
-------------------- ------- --------- ----------- ----------
username/my-bucket                  32           5 2026-02-16
username/checkpoints         117609095         700 2026-02-13
username/logs                321757477        2000 2026-02-13

# Human-readable sizes
>>> hf buckets list -h
ID                   PRIVATE     SIZE TOTAL_FILES CREATED_AT
-------------------- ------- -------- ----------- ----------
username/my-bucket               32 B           5 2026-02-16
username/checkpoints         117.6 MB         700 2026-02-13
username/logs                321.8 MB        2000 2026-02-13

# List buckets in a specific namespace
>>> hf buckets ls huggingface

# Filter buckets by name
>>> hf buckets list --search "checkpoint"

También puedes filtrar cubos por nombre usando search:

>>> for bucket in list_buckets(search="checkpoint"):
...     print(bucket.id)

Puedes usar las opciones --quiet y --format json para obtener un formato de salida diferente. Esto resulta especialmente interesante si deseas enviar la salida a otra herramienta como grep o jq.

# Quiet mode: prints one bucket ID per line
>>> hf buckets list --quiet
username/my-bucket
username/checkpoints
username/logs

# JSON format
>>> hf buckets list --format json
[
  {
    "id": "username/my-bucket",
    "private": false,
    "created_at": "2026-02-16T15:28:32+00:00",
    "size": 32,
    "total_files": 5
  },
  ...
]

Cambiar la visibilidad del bucket

Use update_bucket_settings() para cambiar un bucket existente entre privado y público.

>>> from huggingface_hub import update_bucket_settings

# Make a bucket private
>>> update_bucket_settings("username/my-bucket", private=True)

# Make it public again
>>> update_bucket_settings("username/my-bucket", private=False)

O mediante la CLI:

# Make a bucket private
>>> hf buckets settings username/my-bucket --private
✓ Bucket settings updated
  bucket_id: username/my-bucket
  private: True

# Make it public again
>>> hf buckets settings username/my-bucket --public

Eliminar un bucket

Use delete_bucket() para eliminar un bucket. Esta operación es irreversible.

>>> from huggingface_hub import delete_bucket
>>> delete_bucket("username/my-bucket")

# Don't error if bucket doesn't exist
>>> delete_bucket("username/my-bucket", missing_ok=True)

O mediante la CLI:

# Prompts for confirmation
>>> hf buckets delete username/my-bucket

# Skip confirmation
>>> hf buckets delete username/my-bucket --yes

# Don't error if bucket doesn't exist
>>> hf buckets delete username/my-bucket --yes --missing-ok

Eliminar archivos

Use batch_bucket_files() con el parámetro delete para eliminar archivos de un bucket:

>>> from huggingface_hub import batch_bucket_files

# Delete specific files
>>> batch_bucket_files("username/my-bucket", delete=["old-model.bin", "logs/debug.log"])

O mediante la CLI con hf buckets rm (o hf buckets remove):

# Remove a single file
>>> hf buckets rm username/my-bucket/old-model.bin

# Remove all files under a prefix (requires --recursive)
>>> hf buckets rm username/my-bucket/logs/ --recursive

# Remove only files matching a pattern across the entire bucket
>>> hf buckets rm username/my-bucket --recursive --include "*.tmp"

# Exclude specific files from removal
>>> hf buckets rm username/my-bucket/data/ --recursive --exclude "*.safetensors"

# Preview what would be deleted
>>> hf buckets rm username/my-bucket/checkpoints/ --recursive --dry-run

Mover un bucket

Use move_bucket() para mover o renombrar un bucket. Puede renombrar dentro del mismo namespace o transferirlo a un namespace diferente (usuario u organización).

>>> from huggingface_hub import move_bucket

# Rename a bucket
>>> move_bucket(from_id="username/old-name", to_id="username/new-name")

# Transfer to an organization
>>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket")

O mediante la CLI:

# Rename a bucket
>>> hf buckets move username/old-bucket username/new-bucket

# Transfer to an organization
>>> hf buckets move username/my-bucket my-org/my-bucket

# Using the hf://buckets/ format
>>> hf buckets move hf://buckets/username/old-bucket hf://buckets/username/new-bucket

Para obtener más información sobre el traslado de repositorios y cubos, consulte la documentación de Hub.

Examinar el contenido del bucket

Listar archivos

Use list_bucket_tree() para listar archivos y directorios en un bucket.

>>> from huggingface_hub import list_bucket_tree

# List all files
>>> for item in list_bucket_tree("username/my-bucket"):
...     print(item.path, item.size)
file.txt 5
big.bin 2048
sub/nested.txt 14
sub/deep/file.txt 4

# List top-level entries only
>>> for item in list_bucket_tree("username/my-bucket", recursive=False):
...     print(item.type, item.path)
file file.txt
file big.bin
directory sub

# Filter by prefix
>>> for item in list_bucket_tree("username/my-bucket", prefix="sub"):
...     print(item.path)

O mediante la CLI, con soporte para formatos de tabla, legible por humanos y árbol ASCII. De forma predeterminada, la CLI no es recursiva.

# Default table format (non-recursive, directories shown as entries)
>>> hf buckets list username/my-bucket
        2048  2026-01-15 10:30:00  big.bin
           5  2026-01-15 10:30:00  file.txt
              2026-01-15 10:30:00  sub/

# Recursive listing (all files, including nested)
>>> hf buckets list username/my-bucket -R
        2048  2026-01-15 10:30:00  big.bin
           5  2026-01-15 10:30:00  file.txt
          14  2026-01-15 10:30:00  sub/nested.txt
           4  2026-01-15 10:30:00  sub/deep/file.txt

# Human-readable sizes and short dates
>>> hf buckets list username/my-bucket -R -h
      2.0 KB         Jan 15 10:30  big.bin
         5 B         Jan 15 10:30  file.txt
        14 B         Jan 15 10:30  sub/nested.txt
         4 B         Jan 15 10:30  sub/deep/file.txt

# ASCII tree format
>>> hf buckets list username/my-bucket --tree -h -R
2.0 KB  Jan 15 10:30  ├── big.bin
   5 B  Jan 15 10:30  ├── file.txt
                      └── sub/
                          ├── deep/
   4 B  Jan 15 10:30  │       └── file.txt
  14 B  Jan 15 10:30  └── nested.txt

# Tree structure only (no sizes/dates)
>>> hf buckets list username/my-bucket --tree --quiet -R
├── big.bin
├── file.txt
└── sub/
    ├── deep/
    │   └── file.txt
    └── nested.txt

# Quiet mode: one path per line
>>> hf buckets list username/my-bucket -q
big.bin
file.txt
sub/

# Filter by prefix
>>> hf buckets list username/my-bucket/sub -R

El comando hf buckets list acepta tanto el formato corto (username/my-bucket/sub) como el identificador completo (hf://buckets/username/my-bucket/sub) como argumentos.

Al listar un bucket con HfFileSystem, su contenido se almacena en caché. Pasa HfFileSystem(live_follow=True) para que las listas se actualicen a medida que otros pares añaden, actualizan o eliminan archivos en el bucket, consulta la guía del sistema de archivos.

Subir archivos

Subir con Python

Use batch_bucket_files() para subir archivos a un bucket. Puede subir desde rutas de archivos locales o desde bytes en bruto:

>>> from huggingface_hub import batch_bucket_files

# Upload from local file paths
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[
...         ("./model.safetensors", "models/model.safetensors"),
...         ("./config.json", "models/config.json"),
...     ],
... )

# Upload from raw bytes
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[
...         (b'{"key": "value"}', "config.json"),
...     ],
... )

También puede copiar archivos xet desde otro bucket o repositorio usando el parámetro copy. Esta es una operación del lado del servidor: no se descarga ni se vuelve a subir ningún dato:

# Copy files by xet hash (source_repo_type, source_repo_id, xet_hash, destination)
>>> batch_bucket_files(
...     "username/my-bucket",
...     copy=[
...         ("bucket", "username/source-bucket", "<xethash_1>", "models/model.safetensors"),
...         ("model", "username/my-model", "<xethash_2>", "models/config.safetensors"),
...     ],
... )

Los hashes de Xet se pueden obtener usando list_repo_tree.

También puedes eliminar archivos mientras subes otros.

# Upload and delete in one batch
>>> batch_bucket_files(
...     "username/my-bucket",
...     add=[("./new-model.safetensors", "model.safetensors")],
...     delete=["old-model.bin"],
... )

Las llamadas a batch_bucket_files() no son transaccionales. Si se produce un error durante el proceso, es posible que algunos archivos se hayan subido, copiado o eliminado, mientras que otros no. Cuando el servidor informa de que algunas operaciones fallaron, se lanza un BucketBatchError con las rutas fallidas en su atributo failures.

Subir un archivo con la CLI

Use hf buckets cp para subir un solo archivo:

hf buckets cp es un alias del comando unificado hf cp (también expuesto como hf repos cp). Los tres son idénticos, por lo que cualquier ejemplo de hf buckets cp a continuación también funciona con hf cp.

# Upload to bucket root (uses local filename as remote name)
>>> hf buckets cp ./config.json hf://buckets/username/my-bucket

# Upload to a subdirectory
>>> hf buckets cp ./data.csv hf://buckets/username/my-bucket/logs/

# Upload with a different remote filename
>>> hf buckets cp ./model.safetensors hf://buckets/username/my-bucket/v2/model.safetensors

También puede enviar el resultado de un comando directamente a un nuevo archivo usando -:

# Upload from stdin
>>> echo "hello" | hf buckets cp - hf://buckets/username/my-bucket/hello.txt
>>> cat model.safetensors | hf buckets cp - hf://buckets/username/my-bucket/model.safetensors

Subir un directorio con la CLI

Use hf buckets sync para subir un directorio local completo a un bucket:

# Upload a local directory to a bucket
>>> hf buckets sync ./data hf://buckets/username/my-bucket

# Upload to a specific prefix in the bucket
>>> hf buckets sync ./data hf://buckets/username/my-bucket/train

Consulte la sección Sincronizar directorios a continuación para ver el conjunto completo de opciones de sincronización.

Descargar archivos

Descargar con Python

Use download_bucket_files() para descargar archivos de un bucket:

>>> from huggingface_hub import download_bucket_files

# Download specific files by path
>>> download_bucket_files(
...     "username/my-bucket",
...     files=[
...         ("models/model.safetensors", "./local/model.safetensors"),
...         ("config.json", "./local/config.json"),
...     ],
... )

Para un mejor rendimiento, puede pasar objetos BucketFile obtenidos de list_bucket_tree() en lugar de rutas de cadena. Esto omite el paso de obtención de metadatos:

>>> from huggingface_hub import list_bucket_tree, download_bucket_files

# List and filter files, then download
>>> parquet_files = [
...     item for item in list_bucket_tree("username/my-bucket", recursive=True)
...     if item.type == "file" and item.path.endswith(".parquet")
... ]
>>> download_bucket_files(
...     "username/my-bucket",
...     files=[(f, f"./local/{f.path}") for f in parquet_files],
... )

Descarga un archivo individual con la CLI

Use hf buckets cp para descargar un solo archivo:

# Download to a specific file
>>> hf buckets cp hf://buckets/username/my-bucket/config.json ./config.json

# Download to a directory (uses original filename)
>>> hf buckets cp hf://buckets/username/my-bucket/config.json ./data/

# Download to current directory (omit destination)
>>> hf buckets cp hf://buckets/username/my-bucket/config.json

También puede enviar el contenido de un archivo directamente a stdout usando -:

# Download to stdout and pretty-print with jq
>>> hf buckets cp hf://buckets/username/my-bucket/config.json - | jq .

Descargar un directorio con la CLI

Use hf buckets sync para descargar todos los archivos de un bucket a un directorio local:

# Download bucket contents to a local directory
>>> hf buckets sync hf://buckets/username/my-bucket ./data

# Download only a specific prefix
>>> hf buckets sync hf://buckets/username/my-bucket/models ./local-models

Consulte la sección Sincronizar directorios a continuación para ver el conjunto completo de opciones de sincronización.

Copiar archivos al Bucket

Use copy_files() para copiar archivos ya alojados en el Hub a un Bucket:

>>> from huggingface_hub import copy_files

# Bucket to bucket (same or different bucket)
>>> copy_files(
...     "hf://buckets/username/source-bucket/checkpoints/model.safetensors",
...     "hf://buckets/username/destination-bucket/archive/model.safetensors",
... )

# Repo to bucket
>>> copy_files(
...     "hf://datasets/username/my-dataset/processed/",
...     "hf://buckets/username/my-bucket/datasets/processed/",
... )

Lo mismo está disponible desde la CLI mediante el comando unificado hf cp (también expuesto como hf buckets cp y hf repos cp — los tres son idénticos):

# Bucket to bucket
>>> hf cp hf://buckets/username/source-bucket/logs/ hf://buckets/username/destination-bucket/logs/

# Repo to bucket
>>> hf cp hf://username/my-model/config.json hf://buckets/username/my-bucket/models/config.json

Al copiar carpetas, una barra final / en la fuente usa semánticas de estilo rsync: solo se copian los contenidos de la carpeta, sin anidar la propia carpeta:

# Without trailing slash: "logs" dir is nested => destination/logs/...
>>> hf cp hf://buckets/username/source-bucket/logs hf://buckets/username/destination-bucket/

# With trailing slash: only contents of "logs" are copied => destination/...
>>> hf cp hf://buckets/username/source-bucket/logs/ hf://buckets/username/destination-bucket/

Notas:

  • La copia de un bucket a un repositorio aún no está admitida.
  • Las copias del lado del servidor solo funcionan dentro de la misma región de almacenamiento.
  • Los archivos rastreados con Xet (en cubos o repositorios) se copian en el servidor mediante su hash: no se descarga ni se vuelve a subir ningún dato.
  • Los archivos de texto pequeños que no están controlados con Xet en las fuentes del repositorio se descargan y se vuelven a subir al cubo de destino.
  • copy_files() también se puede usar para copias de un repositorio a otro. Consulte la guía de repositorios para más detalles.

Sincronizar directorios

El comando hf buckets sync (y su equivalente en la API sync_bucket()) es la forma más potente de transferir archivos entre un directorio local y un bucket. Compara el origen y el destino, y solo transfiere los archivos que han cambiado.

Sincronización básica

# Upload: local directory -> bucket
>>> hf buckets sync ./data hf://buckets/username/my-bucket

# Download: bucket -> local directory
>>> hf buckets sync hf://buckets/username/my-bucket ./data

hf sync es un alias conveniente para hf buckets sync. Ambos comandos son idénticos.

>>> hf sync ./data hf://buckets/username/my-bucket

O a través de Python:

>>> from huggingface_hub import sync_bucket

# Upload: local directory -> bucket
>>> sync_bucket("./data", "hf://buckets/username/my-bucket")

# Download: bucket -> local directory
>>> sync_bucket("hf://buckets/username/my-bucket", "./data")

Eliminar archivos innecesarios

Por defecto, sync solo añade o actualiza archivos. Use --delete (o delete=True en Python) para eliminar también los archivos del destino que no existen en el origen:

# Upload and remove remote files not present locally
>>> hf buckets sync ./data hf://buckets/username/my-bucket --delete

# Download and remove local files not present in bucket
>>> hf buckets sync hf://buckets/username/my-bucket ./data --delete

O a través de Python:

>>> sync_bucket("./data", "hf://buckets/username/my-bucket", delete=True)
>>> sync_bucket("hf://buckets/username/my-bucket", "./data", delete=True)

Filtrado

Puede controlar qué archivos se sincronizan mediante patrones de inclusión/exclusión:

# Only sync .txt files
>>> hf buckets sync ./data hf://buckets/username/my-bucket --include "*.txt"

# Exclude log files
>>> hf buckets sync ./data hf://buckets/username/my-bucket --exclude "*.log"

# Combine include and exclude
>>> hf buckets sync ./data hf://buckets/username/my-bucket --include "*.safetensors" --exclude "*.tmp"

O a través de Python:

# Only sync .txt files
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", include=["*.txt"])

# Exclude log files
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", exclude=["*.log"])

# Combine include and exclude
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", include=["*.safetensors"], exclude=["*.tmp"])

Para un filtrado más complejo, use un archivo de filtro con --filter-from (o filter_from en Python):

>>> hf buckets sync ./data hf://buckets/username/my-bucket --filter-from filters.txt

El archivo de filtros usa los prefijos + (incluir) y - (excluir). Las líneas que comienzan con # son comentarios. Las reglas se evalúan en orden (gana la primera regla que coincida):

# filters.txt
- *.log
- *.tmp
+ *.safetensors
+ *.json

Modos de comparación

Por defecto, sync compara los archivos utilizando tanto el tamaño como la hora de modificación. Puedes personalizar este comportamiento:

# Only compare sizes (ignore modification times)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --ignore-times

# Only compare modification times (ignore sizes)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --ignore-sizes

# Only update files that already exist on the receiver (skip new files)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --existing

# Only create new files (skip files that already exist on the receiver)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --ignore-existing

O a través de Python:

>>> sync_bucket("./data", "hf://buckets/username/my-bucket", ignore_times=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", ignore_sizes=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", existing=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", ignore_existing=True)

Planificar y aplicar

Para operaciones críticas, puedes revisar el plan de sincronización antes de ejecutarlo:

# Step 1: Generate a plan file (nothing is transferred)
>>> hf buckets sync ./data hf://buckets/username/my-bucket --plan sync-plan.jsonl
Sync plan: ./data -> hf://buckets/username/my-bucket
  Uploads: 3
  Downloads: 0
  Deletes: 0
  Skips: 1
Plan saved to: sync-plan.jsonl

# Step 2: Review the plan file (JSONL format)
>>> cat sync-plan.jsonl

# Step 3: Apply the plan
>>> hf buckets sync --apply sync-plan.jsonl

O a través de Python:

# Step 1: Generate a plan file (nothing is transferred)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")

# Step 2: Review the plan file (JSONL format), then apply
>>> sync_bucket(apply="sync-plan.jsonl")

El archivo de plan es un archivo JSONL con una línea de encabezado seguida de una línea por operación. Cada operación incluye la acción (upload, download, delete o skip), la ruta del archivo y el motivo de la acción. Puede editar este archivo manualmente antes de aplicarlo, pero tenga cuidado con la sintaxis.

Prueba en seco

Use --dry-run (o dry_run=True en Python) para obtener el plan de sincronización sin ejecutar nada:

# Preview what would be synced
>>> hf buckets sync ./data hf://buckets/username/my-bucket --dry-run | jq '.action'

O a través de Python:

>>> plan = sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
>>> plan.summary()
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}

--dry-run genera el mismo formato JSONL que --plan, pero lo imprime en stdout en lugar de guardarlo en un archivo. Solo se imprime el contenido JSONL, lo que permite usarlo de forma segura con tuberías.

Modos detallado y silencioso

# Show per-file operations
>>> hf buckets sync ./data hf://buckets/username/my-bucket --verbose

# Suppress all output
>>> hf buckets sync ./data hf://buckets/username/my-bucket --quiet

O a través de Python:

>>> sync_bucket("./data", "hf://buckets/username/my-bucket", verbose=True)
>>> sync_bucket("./data", "hf://buckets/username/my-bucket", quiet=True)

Avanzado

Para casos de uso de nivel inferior, también están disponibles los siguientes métodos:

  • get_bucket_paths_info(): Obtiene información sobre rutas específicas en un bucket en una sola solicitud por lotes. Útil cuando sabes exactamente de qué archivos necesitas los metadatos.
>>> from huggingface_hub import get_bucket_paths_info
>>> for info in get_bucket_paths_info("username/my-bucket", ["file.txt", "models/model.safetensors"]):
...     print(info.path, info.size, info.xet_hash)
>>> from huggingface_hub import get_bucket_file_metadata
>>> metadata = get_bucket_file_metadata("username/my-bucket", "models/model.safetensors")
>>> metadata.size
42000
Update on GitHub