Installing Transformers gives you software that can run many model types. It does not give you the learned settings or text vocabulary of a particular model. Here you will obtain one exact set of model files, check what arrived and load it again without requesting a download. You will generate text in a later lesson.
Finish CPU environment setup
first. You need its owned ~/genai-llm-practice folder, .venv/, ordinary
model/, inputs/ and outputs/ directories, and passing environment checks.
The reference path is Linux x86_64/Bash, CPython 3.13.15, torch 2.14.1+cpu and
Transformers 5.19.0. Initial download needs internet and about 271.2 MB for the
six selected files, before temporary space and the existing packages. The
previous RAM/disk allowances remain planning budgets, not tested minima.
No external account, key, GPU or paid API is involved.
Keep three identities separate
The model ID, HuggingFaceTB/SmolLM2-135M-Instruct, names a repository.
A revision identifies a particular repository snapshot. We use the full
commit identifier 12fd25f77366fa6b3b4b768ec3050bf629380bac, rather than a
moving branch such as main. The package version, such as Transformers
5.19.0, identifies the software interpreting those files. Changing a package
version is different from changing the model revision.
The model's weights are learned numerical settings, also called parameters. The tokenizer defines how text maps to numerical token IDs and back. The next lesson inspects that mapping. We need the matching tokenizer, model configuration and weights from the same chosen snapshot. A similarly named tokenizer is not a substitute.
config.jsondescribes the model type and dimensions so the installed library can construct it.model.safetensorsstores the learned parameter arrays in safetensors format.generation_config.jsonsupplies generation defaults; later exercises set important controls explicitly.tokenizer.jsonstores the tokenizer's text-processing rules and vocabulary.tokenizer_config.jsonsupplies tokenizer behaviour, including conversation formatting used later.special_tokens_map.jsonnames special token markers; later lessons distinguish them from ordinary text.
The configuration records the serialization-era Transformers version 4.42.3
and a preferred weight dtype of bfloat16. These are not instructions to
replace your course environment. We use the tested 5.19.0 loader and explicitly
request CPU float32, a 32-bit floating-point representation. The configuration
file remains unchanged. File size on disk does not measure the RAM needed to
load the model and run a program.
Read the model card at the fixed revision (S03). It declares Apache-2.0 and describes the small checkpoint's limitations and English focus. Keep that source/revision with your practice notes. A matching checksum does not grant usage rights or establish that generated content is correct; licence terms and task results are separate questions. This exercise obtains the files from their public host and does not redistribute weights.
What a file check establishes
A file is a sequence of bytes, units of stored data. A size check compares its byte count with the expected count. A truncated download usually fails that check, but replacing a character without changing the length can pass. A SHA-256 checksum is a digest calculated from all the file's bytes. In this example it is written as 64 hexadecimal characters. A different digest reveals that the bytes differ even when their count is unchanged.
The FILES dictionary in the script below is the course's manifest:
filename to expected byte count and SHA-256. The weight digest matches the
publisher's revision metadata (S05).
The other five digests were observed from the fixed downloaded files. They
check agreement with this course snapshot; they are not independent publisher
signatures. A checksum only helps when the expected value comes from a source
you have reason to trust. Do not replace an expected digest merely to make an
unexpected download pass.
Our transfer uses an owned .part file. Only after size and hash verification
does that file become the final filename. A later run checks existing final
files instead of silently replacing them. This separates an interrupted
transfer from a completed, verified input.
Save the complete downloader and verifier
In the practice root, save this complete file as prepare_model.py. Its
maintained course example is examples/model-files/prepare_model.py; everything
needed from that file is reproduced here. No separate source pack is assumed.
The .json names denote structured text consumed by the library. This exercise
checks file bytes; it does not require you to write a JSON parser.
"""Save in the practice root. Download only on explicit --download."""
import argparse
import hashlib
import os
from pathlib import Path
import urllib.request
MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
REVISION = "12fd25f77366fa6b3b4b768ec3050bf629380bac"
ROOT = Path(__file__).resolve().parent
FILES = {
"config.json": (861, "8eb740e8bbe4cff95ea7b4588d17a2432deb16e8075bc5828ff7ba9be94d982a"),
"generation_config.json": (132, "87b916edaaab66b3899b9d0dd0752727dff6666686da0504d89ae0a6e055a013"),
"model.safetensors": (269060552, "5af571cbf074e6d21a03528d2330792e532ca608f24ac70a143f6b369968ab8c"),
"special_tokens_map.json": (655, "2b7379f3ae813529281a5c602bc5a11c1d4e0a99107aaa597fe936c1e813ca52"),
"tokenizer.json": (2104556, "9ca9acddb6525a194ec8ac7a87f24fbba7232a9a15ffa1af0c1224fcd888e47c"),
"tokenizer_config.json": (3764, "4ec77d44f62efeb38d7e044a1db318f6a939438425312dfa333b8382dbad98df"),
}
def verify_file(path, expected_size, expected_hash):
if path.is_symlink() or not path.is_file():
raise ValueError(f"Need an ordinary local file: {path.name}")
if path.stat().st_size != expected_size:
raise ValueError(f"Byte-count mismatch: {path.name}")
digest = hashlib.sha256()
with path.open("rb") as stream:
while True:
block = stream.read(1024 * 1024)
if not block:
break
digest.update(block)
if digest.hexdigest() != expected_hash:
raise ValueError(f"SHA-256 mismatch: {path.name}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--download", action="store_true")
mode.add_argument("--check-config-copy", type=Path)
args = parser.parse_args()
if args.check_config_copy is not None:
verify_file(args.check_config_copy, *FILES["config.json"])
print("config copy matches the expected bytes")
return
model_dir = ROOT / "model"
if model_dir.is_symlink():
raise ValueError("Use an owned ordinary model folder")
model_dir.mkdir(exist_ok=True)
for name, (size, digest) in FILES.items():
target = model_dir / name
if target.is_symlink():
raise ValueError(f"Refusing symlink: {name}")
if not target.exists():
if not args.download:
raise FileNotFoundError(f"Missing local file: {name}; no download requested")
partial = model_dir / (name + ".part")
url = f"https://huggingface.co/{MODEL_ID}/resolve/{REVISION}/{name}?download=true"
print("downloading:", name, flush=True)
# Exclusive creation refuses an existing partial file or symlink.
with partial.open("xb") as destination:
with urllib.request.urlopen(url, timeout=120) as response:
received = 0
while True:
block = response.read(1024 * 1024)
if not block:
break
received += len(block)
if received > size:
raise ValueError(f"Download exceeds expected size: {name}")
destination.write(block)
verify_file(partial, size, digest)
partial.replace(target)
verify_file(target, size, digest)
print("verified:", name, size)
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
torch.set_num_threads(4)
tokenizer = AutoTokenizer.from_pretrained(
model_dir, local_files_only=True, trust_remote_code=False
)
model = AutoModelForCausalLM.from_pretrained(
model_dir, local_files_only=True, trust_remote_code=False,
use_safetensors=True, dtype=torch.float32,
).to("cpu").eval()
print("model/revision:", MODEL_ID, REVISION)
print("verified files/bytes:", len(FILES), sum(size for size, _ in FILES.values()))
print("parameters:", model.num_parameters())
print("tokenizer entries:", len(tokenizer))
print("device/dtype:", next(model.parameters()).device, next(model.parameters()).dtype)
print("ready: local files loaded; no text generated")
if __name__ == "__main__":
main()
The manifest stores a two-item pair for each filename: byte count first, digest
second. for name, (size, digest) in FILES.items() unpacks that pair into
meaningful names. ROOT is the saved script's own folder, so its model/
location does not depend on a hidden cache or an arbitrary current directory.
verify_file() first rejects a symlink (a pointer to another location) or a
missing/non-file input. stat().st_size gives bytes, not character count.
open("rb") reads raw bytes. The loop feeds at most 1,048,576 bytes (one MiB)
at a time into the digest, stopping at the empty byte string. It checks the
large weight file without reading the whole file into one Python byte string.
This streaming check does not constrain the memory needed by the later loader.
argparse turns command-line flags into named choices. --download permits
network transfers of missing files; without it, missing local files cause an
error. --check-config-copy PATH checks a supplied disposable file against the
configuration manifest entry and returns before model loading. The * before
FILES["config.json"] passes the pair's two values as separate function
arguments. The two modes are mutually exclusive.
The download loop builds a public URL from the fixed model/revision/filename.
open("xb") creates a new .part file exclusively: it refuses an existing
file or symlink instead of overwriting it. The response is read in chunks with
a 120-second socket timeout, and the byte counter rejects data exceeding the
expected size. After verification, replace() renames the owned partial file
to its final name. Run only one copy of this script at a time. If a network or
verification step fails, the partial file stays available for inspection.
After all six files pass, the script enables offline Hub use and disables Hub
telemetry before importing Transformers. These variables affect the Hub
library; they do not disable Python's downloader or the computer's network.
The loaders also use local_files_only=True, so they must use these local
files. trust_remote_code=False declines repository-supplied custom Python,
and use_safetensors=True selects the verified weight format. These choices
are not a blanket guarantee about arbitrary downloaded content.
Four CPU threads bound this example's parallel setting. .to("cpu") chooses
the CPU, dtype=torch.float32 chooses the loaded numerical type, and eval()
selects evaluation behaviour. No model forward pass or training occurs here.
num_parameters() counts learned numerical values; len(tokenizer) counts
its token entries. The final next(model.parameters()) reads one parameter's
device/type for inspection. The sum over manifest sizes adds the first number
from every pair; it is a file-byte total, not a memory measurement.
Download once, then verify locally
In Bash, return to the practice root, confirm the earlier environment and run the explicit download mode. These commands create/read only the named local inputs and contact the public file host for missing files:
cd ~/genai-llm-practice
.venv/bin/python check_environment.py
.venv/bin/python prepare_model.py --download
The download prints each filename, not a model answer. It can take several minutes depending on connectivity; wait for it to finish before rerunning. A missing dependency belongs to environment setup, not a different model checkpoint. On success, run the default local-only mode:
.venv/bin/python prepare_model.py
Illustrative local-only output for the selected files is below. Compare file counts/sizes, identity and runtime fields, rather than interpreting a clean exit as proof of future answers.
verified: config.json 861
verified: generation_config.json 132
verified: model.safetensors 269060552
verified: special_tokens_map.json 655
verified: tokenizer.json 2104556
verified: tokenizer_config.json 3764
model/revision: HuggingFaceTB/SmolLM2-135M-Instruct 12fd25f77366fa6b3b4b768ec3050bf629380bac
verified files/bytes: 6 271170520
parameters: 134515008
tokenizer entries: 49152
device/dtype: cpu torch.float32
ready: local files loaded; no text generated
The largest input is the 269,060,552-byte weight file. The six files total 271,170,520 bytes, about 271.2 decimal MB. The parameter count concerns learned settings; it is not a count of known facts. The successful load establishes that the tested local files and installed implementation can be read together. It does not establish generation, factual accuracy or performance of larger models.
To test reuse, temporarily disable your network with the computer's normal
network controls and rerun the default command. Restore connectivity afterwards
if needed. Do not add --download to an offline check. An existing final file
is checked in either mode; a missing file in default mode is an explicit
failure, not an invitation to fetch a replacement.
Break a copy, not the source input
Predict whether size alone detects a one-character substitution. Then make a
small copy in the already-owned outputs/ folder:
cp model/config.json outputs/config-copy.json
.venv/bin/python prepare_model.py --check-config-copy outputs/config-copy.json
cp copies this one file. The check should first report that the copy matches.
Open only outputs/config-copy.json in your editor and replace one existing
digit with a different digit, without inserting/deleting characters. Do not
edit model/config.json or load the changed copy as a model configuration.
Rerun the same copy-check command. Explain which condition failed and what it
means. If the editor also changes line endings, use the reported byte-count
failure to distinguish that from a same-length substitution.
Hint
The size check runs before the digest check. A file's meaning and its exact bytes are different concerns. The loader never runs in copy-check mode.
Answer and reasoning
If the byte count is unchanged, the copy fails with SHA-256 mismatch: config-copy.json. Matching size did not establish matching bytes. If line
endings or other content length changed, Byte-count mismatch is detected
first. Neither error says what the correct answer to a library question is.
The manifest is not repaired by substituting the corrupted copy's digest.
Run the default verifier again to confirm that all six originals still pass. The model/revision choice, package versions and original hashes remain the same. This is why a disposable small copy is useful for diagnosis.
Recover and keep the verified inputs
After interruption, close the previous run and inspect the printed filename
and model/ contents. A final file is verified on the next run. If a transfer
left a .part file, inspect its exact path, confirm it is this course's partial
file, and remove only that owned partial file in your file manager before
retrying --download. This simple downloader restarts that file from byte
zero; it does not implement byte-range resume. Verified final files are kept.
If a final file fails size/hash verification, stop and compare the exact revision, manifest and source. This script deliberately does not overwrite the mismatch. Move only the suspect owned file aside for inspection when its source is established, then obtain the missing file again from the fixed revision. Do not change the expected digest or delete a shared cache to hide the error. A permission/ordinary-folder error needs a path check, not broader permissions.
On a new terminal, return to ~/genai-llm-practice and use .venv/bin/python
explicitly; saved model files survive the closed terminal. Keep model/, the
script and environment for the token and generation lessons. The edited
outputs/config-copy.json is disposable; inspect and remove only that copy
when finished. No generated answer or cloud resource needs cleanup.
Sources
- Pinned model card (S03) and pinned configuration (S04) describe the chosen snapshot.
- Revision metadata API (S05) exposes the weight size and published SHA-256.
- Hub download guidance (S10) explains fixed revisions and local files; the lesson uses its own explicit six-file downloader.
- Transformers model loading (S11) provides API context; the actual command uses the course's tested 5.19.0 release.