Set Up a Fine-Tuning Environment with PyTorch and Hugging Face

JS
Jai Singh
28 Nov, 2026 4 min read 11 views

A reliable fine-tuning environment is a virtual environment with a CUDA-enabled PyTorch build plus the Hugging Face libraries transformers, datasets, peft, trl and accelerate. This guide builds one step by step and ends with a short script that proves your GPU is used.

What you need

  • Python 3.10 or newer is a safe choice for current versions of these libraries.
  • An NVIDIA GPU with a recent driver for the standard path. Apple silicon can use the mps backend for small experiments, and CPUs work only for tiny models.
  • Enough disk space. Model files are large, and the Hub cache can reach tens of gigabytes.

Step 1: create a virtual environment

python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip

Use one environment per project. Fine-tuning libraries move fast, and a pinned environment is what makes your results repeatable later.

Step 2: install PyTorch

Install PyTorch first, using the selector on the official PyTorch website to get the right command for your operating system and CUDA version. Plain pip install torch works on many machines, but the selector avoids mismatches between the build and your driver.

Step 3: install the Hugging Face stack

pip install transformers datasets accelerate peft trl
pip install bitsandbytes   # for 8-bit and 4-bit loading on NVIDIA GPUs
pip install huggingface_hub

bitsandbytes provides the quantization used by QLoRA. It is aimed at CUDA GPUs, and support on other platforms varies, so skip it if you do not need it.

Step 4: log in to the Hub when needed

huggingface-cli login
# or set an environment variable instead of storing a token on disk
export HF_TOKEN="<your token>"

You need a token for gated models and to push your results. Never commit a token to Git.

Step 5: verify everything

import torch, transformers, datasets, peft, trl, accelerate

print("torch", torch.__version__)
print("transformers", transformers.__version__)
print("datasets", datasets.__version__)
print("peft", peft.__version__)
print("trl", trl.__version__)
print("accelerate", accelerate.__version__)

print("cuda available:", torch.cuda.is_available())
if torch.cuda.is_available():
    print("device:", torch.cuda.get_device_name(0))
    print("bf16 supported:", torch.cuda.is_bf16_supported())
    free, total = torch.cuda.mem_get_info()
    print(f"memory: {free / 1e9:.1f} GB free of {total / 1e9:.1f} GB")
elif torch.backends.mps.is_available():
    print("Apple mps backend available")

You should see library versions and your GPU name. If cuda available prints False on a machine with an NVIDIA card, the usual causes are a CPU-only PyTorch build, an outdated driver, or running inside a container started without GPU access.

Step 6: freeze your versions

pip freeze > requirements.lock.txt

Commit that file. When a later upgrade changes behaviour, you can diff the lock files and find the culprit.

Troubleshooting

  • Import errors after upgrading: TRL, PEFT and Transformers are developed together; upgrade them together and read the release notes if an argument was renamed.
  • bitsandbytes cannot find CUDA: check that the driver and PyTorch CUDA build are compatible and that the GPU is visible.
  • Out of disk space: set HF_HOME to a drive with room, since models cache under it by default.
  • Slow downloads: the Hub supports resuming; rerun the command and it continues from the cache.

Where to run

If you lack a local GPU, a hosted notebook or rented cloud GPU works with exactly the same commands. Posts 52 and 53 compare those options. For general PyTorch concepts, see the PyTorch topic on this site.

Pick the right precision for your GPU

Newer NVIDIA data-center and recent consumer cards support bf16, which has the range of fp32 with less memory and rarely overflows. Older cards support fp16 only, and fp16 training usually needs loss scaling, which the Trainer handles when you set fp16=True. The verification script above prints whether bf16 is supported so you can choose the right flag in your training configuration without guessing.

Keep the environment reproducible

Write the exact setup commands in a README or a Makefile, and rebuild the environment from scratch once on a clean machine to prove the instructions work. If you use containers, base your image on a CUDA-enabled PyTorch image and install the libraries from your lock file. Pin the Python version too. A fine-tuning job that worked last month and fails today is almost always caused by an unpinned dependency, and a lock file turns that mystery into a short diff.

Finally, run a one-minute smoke test: load a tiny model, run three training steps on ten examples, and save the output. If that works, your environment is ready for a real run, and you have a quick check to repeat after every upgrade.

Working with notebooks and remote machines

Many people prototype in a notebook and then run long jobs as scripts. Notebooks are fine for exploration, but long training runs belong in a script launched with a terminal multiplexer such as tmux, or as a batch job, so that closing a laptop does not kill them. Log to a file, save checkpoints regularly, and write the command you ran into the log header. When you work on a remote GPU machine, connect through SSH and keep the virtual environment on the machine's fast local disk.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.