← Blog
A cream slide mount with an orange corner holds a plum branching line on a lavender background.
Published on
2026-11-27

Download a pinned Hugging Face model and load it offline

A model that loads on your laptop can still fail on a fresh worker. Your laptop may have a tokenizer or weight file left over from an earlier download. Before taking the worker offline, give it a standalone copy of one model revision and a small test with a known answer.

We tried this with the English sentence encoder sentence-transformers/all-MiniLM-L6-v2. A fresh Python process loaded the copied files on CPU with an empty Hub cache and outbound Python connections blocked. For one fixed sentence, all 384 embedding values matched the reference. Here’s how to repeat that check before starting a larger job.

Choose the revision and runtime together

Open the model’s commit history, choose the revision you have reviewed, and copy its full commit hash. A branch such as main can move between two downloads. We used commit 1110a243fdf4706b3f48f1d95db1a4f5529b4d41. Its card identifies the license as Apache 2.0 and describes how to turn token outputs into a sentence embedding. Read the model card at the tested revision.

Install the following packages in a Python 3.12 environment on both machines while they have network access, or provision an equivalent environment ahead of time. A copy of the weights does not include Python or PyTorch. We ran the example on Windows with the CPU build of PyTorch.

python -m pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cpu
python -m pip install transformers==4.57.1 huggingface-hub==0.36.0 numpy==1.26.4

Download the files into a portable directory

Save the following as prepare.py on the connected machine. Every download uses the same commit. Copying the file contents out of the Hub cache makes the directory portable even if the cache uses symbolic links. The SHA-256 manifest records what should arrive at the worker. Hugging Face’s file download guide.

"""Run on a connected machine. The output must be a new directory."""
import hashlib
import json
import shutil
import sys
from pathlib import Path
from huggingface_hub import hf_hub_download

REPO = "sentence-transformers/all-MiniLM-L6-v2"
REVISION = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41"
FILES = ("config.json", "model.safetensors", "tokenizer.json", "tokenizer_config.json",
         "special_tokens_map.json", "vocab.txt", "README.md")

def digest(path):
    with path.open("rb") as stream:
        return hashlib.file_digest(stream, "sha256").hexdigest()

if __name__ == "__main__":
    out = Path(sys.argv[1])
    out.mkdir(parents=True, exist_ok=False)
    hashes = {}
    for name in FILES:
        cached = hf_hub_download(REPO, name, revision=REVISION, token=False)
        local = out / name
        shutil.copyfile(cached, local)
        hashes[name] = digest(local)
    manifest = {"repo": REPO, "revision": REVISION, "sha256": hashes}
    (out / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    print(f"Prepared {len(hashes)} files at {REVISION}")

These seven files cover the PyTorch and Transformers path used here, including the model card. A different loader can need other files. For sharded weights, include the index and every shard it names. This public model downloads anonymously. For a gated model, first obtain access and use authorized credentials on the download machine. How to use a Hugging Face access token.

Record a reference before transferring the model

Save this as embed.py. It feeds one fixed sentence to the tokenizer, averages the token vectors using the attention mask, and normalizes the result. Saving the token IDs alongside the embedding makes it easier to locate a mismatch. A change in token IDs points to the input or tokenizer before you need to investigate numerical differences.

"""Read a local model and write a reference or recovered embedding as JSON."""
import json
import sys
from pathlib import Path
import torch
from transformers import AutoModel, AutoTokenizer

def embed(folder):
    tokenizer = AutoTokenizer.from_pretrained(folder, local_files_only=True)
    model = AutoModel.from_pretrained(folder, local_files_only=True,
                                      use_safetensors=True).cpu().eval()
    inputs = tokenizer("An offline worker reads local files.", return_tensors="pt",
                       truncation=True, max_length=256)
    with torch.inference_mode():
        hidden = model(**inputs).last_hidden_state
        mask = inputs["attention_mask"].unsqueeze(-1)
        pooled = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1)
        vector = torch.nn.functional.normalize(pooled, dim=1)
    return {"tokens": inputs["input_ids"][0].tolist(), "vector": vector[0].tolist()}

if __name__ == "__main__":
    result = embed(Path(sys.argv[1]).resolve())
    Path(sys.argv[2]).write_text(json.dumps(result), encoding="utf-8")
python prepare.py prepared
python embed.py prepared reference.json

Transfer the contents of prepared/, including the manifest, to a new directory named worker/model/ on the destination. Copy embed.py and reference.json into its working directory. Keep the original reference from the preparation machine. Regenerating it on the destination would turn the comparison into a test against itself.

Check the copied files and run inference offline

Save the following as offline.py beside embed.py. Start it in a fresh interpreter so the Hub reads its offline settings before Transformers imports it. The check uses a new cache directory, rejects outbound connections made through Python sockets and passes only the local model path to the loader. Hugging Face Hub environment variables.

"""Run in a fresh process and refuse outbound Python sockets before importing the model."""
import hashlib
import json
import os
import sys
from pathlib import Path
from tempfile import TemporaryDirectory

def deny_network(event, args):
    if event in {"socket.connect", "socket.getaddrinfo", "socket.sendto"}:
        raise RuntimeError(f"Offline test blocked {event}")

def check(folder, reference):
    manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
    for name, expected in manifest["sha256"].items():
        path = folder / name
        if not path.is_file():
            raise SystemExit(f"Missing model file: {name}")
        with path.open("rb") as stream:
            if hashlib.file_digest(stream, "sha256").hexdigest() != expected:
                raise SystemExit(f"Checksum mismatch: {name}")
    from embed import embed
    actual = embed(folder)
    expected = json.loads(reference.read_text(encoding="utf-8"))
    assert actual["tokens"] == expected["tokens"], "Token IDs differ"
    a, b = actual["vector"], expected["vector"]
    assert len(a) == len(b) == 384, "Unexpected embedding shape"
    delta = max(abs(x-y) for x,y in zip(a,b))
    if not all(abs(x-y) <= 1e-6 for x,y in zip(a,b)):
        raise SystemExit(f"Embedding mismatch: max absolute difference {delta}")
    return {"revision": manifest["revision"], "files": len(manifest["sha256"]),
            "tokens": len(actual["tokens"]), "dimensions": len(a), "max_abs_difference": delta}

if __name__ == "__main__":
    with TemporaryDirectory() as cache:
        for key in ("HF_HUB_CACHE", "HUGGINGFACE_HUB_CACHE", "TRANSFORMERS_CACHE",
                    "PYTORCH_TRANSFORMERS_CACHE", "PYTORCH_PRETRAINED_BERT_CACHE"):
            os.environ.pop(key, None)
        os.environ.update(HF_HOME=cache, HF_HUB_OFFLINE="1", HF_HUB_DISABLE_TELEMETRY="1")
        sys.addaudithook(deny_network)
        print(json.dumps(check(Path(sys.argv[1]).resolve(), Path(sys.argv[2]))))
python offline.py worker/model reference.json

On the tested CPU, the input produced 10 token IDs and one 384-value embedding. The largest absolute difference from the preparation run was 0.0, within our chosen limit of 0.000001 per value. This checks one input on the tested runtime. For a different device or numerical precision, compare representative inputs and choose a tolerance that fits the application.

Find an incomplete transfer before scheduling work

We removed model.safetensors from a disposable copy and repeated the check. It stopped with Missing model file: model.safetensors. Calling Transformers directly on that folder also failed. If this happens on a worker, copy the missing file from the recorded revision, then rerun the check against the original reference. If the hashes match but the token IDs differ, check the input text and tokenizer versions.

For a batch job on Compute with Hivenet, run the check on the instance that will handle the job before passing it the full dataset. The test above ran on a local CPU. Once the worker reproduces the reference, use examples from your own data to check whether the model retrieves the results you need. How to choose an embedding model.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.