Reproducible environments: uv, dependencies and the CUDA stack
Build an isolated Python environment declared in pyproject.toml and locked with uv, so it can be reproduced on another machine or a year later. Examine the GPU software stack, including the driver, CUDA runtime bundled with PyTorch wheels, and RTX 4060 architecture, to diagnose broken installations on Windows. Finish by creating the course project skeleton.
After this lesson you can
- Create a uv project that declares dependencies in pyproject.toml and locks them in uv.lock.
- Explain the difference between declared constraints and resolved versions, and why a lockfile makes an environment reproducible.
- Install PyTorch with CUDA support on Windows using the correct wheel index and verify the GPU from Python.
- Diagnose incompatibilities among the NVIDIA driver, the wheel's CUDA variant, and GPU architecture.
- Install the project's own package in editable mode for use in notebooks and scripts.
Motivation: the experiment that worked last month
You train a model, record the result, and move on. A month later you want to repeat it for a comparison, but the script does not even start: an ImportError appears in a library you have not touched. Or it starts, but its final loss does not match your notebook. You have not changed a line of your code. Everything around it has changed.
One prominent example was NumPy 2.0, released in June 2024. It changed the binary interface against which C extensions are compiled. Extensions compiled for NumPy 1.x could be incompatible with NumPy 2 and fail on import with a message beginning “A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.0 as it may crash”. Reinstalling with numpy and no version bound could combine NumPy 2 with incompatible binary extensions; pinning the versions and artifacts of a compatible environment prevented that particular change. An environment changing beneath unchanged code is called dependency drift.
Machine learning adds another layer. Beneath Python is a native software stack (the GPU driver, CUDA runtime, cuBLAS, and cuDNN) with its own compatibility rules. An installation can appear to work without using the GPU at all: torch.cuda.is_available() returns False, nothing crashes, and training runs on the CPU without warning.
This lesson builds the course working environment from the ground up, explaining each part:
- What a virtual environment is and exactly what it isolates.
- How to declare a project in
pyproject.tomland turn that declaration into concrete versions: the NP-complete dependency resolution problem and the lockfile that records its solution. - How the driver, CUDA runtime, PyTorch wheel, and GPU architecture fit together, so that you can diagnose a broken installation.
- What every lockfile leaves out and how to record it.
By the end you will have created the course project skeleton with uv, PyTorch with CUDA running on the RTX 4060, and a diagnostic script to accompany each experiment.
Interpreter, site-packages, and virtual environments
When you write import numpy, Python searches the directories in sys.path in order and loads the first numpy it finds. The interpreter builds that list at startup from the location of its own executable. A virtual environment works by changing that starting point.
The process has three stages:
- Which executable is launched. When you type
pythonin the terminal, the shell searches the directories inPATHand runs the firstpython.exeit finds. Activating an environment simply prepends its executables directory toPATH. - Where its prefix is. At startup, the interpreter looks for a
pyvenv.cfgfile next to its executable or in the parent directory. If it finds one, it setssys.prefixto the environment directory and takes the standard library from the base interpreter specified by thehomekey. Otherwise,sys.prefixis its own installation directory. - Which directories
importsearches.sys.pathcontains, in order, the script directory (or the current directory withpython -cor an interactive interpreter), the base interpreter’s standard library, andsite-packagesundersys.prefix, plus any paths added by.pthfiles inside it.
Two consequences deserve attention. First, a venv reuses Python rather than copying it. Creating one is therefore almost instant (milliseconds with uv; python -m venv takes a little longer because it installs pip), and deleting or upgrading the base interpreter breaks the environment. Second, a venv is disposable. You do not edit it by hand, copy it between machines, or commit it to the repository. You regenerate it from a description, which is where reproducibility comes from.
The figure also shows three real pitfalls. With system Python, the user’s site-packages (where pip install --user writes) comes before the global one, so an old version installed years ago can shadow the new one. A file you name numpy.py in the current directory shadows the whole library, because that directory comes first. Finally, your own package can only be imported from anywhere if it is installed: an editable install leaves a .pth file in site-packages containing the path to your src directory, which Python adds to sys.path at startup.
What a virtual environment does not isolate is equally important:
- The GPU driver and system libraries. They belong to the operating system and are shared by all environments.
- Environment variables.
PYTHONPATHstill adds paths tosys.pathinside any environment, andCUDA_VISIBLE_DEVICESdetermines which GPU PyTorch sees in all of them. - Tools on PATH. A compiler,
nvcc, orgitcomes from the system. - The state of an already running Jupyter kernel. A notebook uses the interpreter with which its kernel was launched, regardless of the environment active in the terminal. You will explore this in the hidden state of notebooks.
Pyodide, the interpreter that runs this page’s cells, is also a Python installation with its own prefix. You can ask it the same questions as any other:
import sys, os, tempfile, importlib.util
print("sys.prefix: ", sys.prefix)
print("sys.base_prefix: ", sys.base_prefix, " ¿entorno virtual?", sys.prefix != sys.base_prefix)
print("sys.path:")
for p in sys.path:
print(" ", repr(p))
print("numpy se cargaría desde:", importlib.util.find_spec("numpy").origin)
# Un módulo con el nombre de uno de la biblioteca estándar, en una carpeta que va primero en sys.path
carpeta = tempfile.mkdtemp()
with open(os.path.join(carpeta, "statistics.py"), "w") as f:
f.write("def mean(x):\n return 'soy un impostor'\n")
sys.path.insert(0, carpeta)
sys.modules.pop("statistics", None)
import statistics
print("\nstatistics.mean([1, 2, 3]) =", statistics.mean([1, 2, 3]), " <-", statistics.__file__)
# deshacer: quitar la carpeta y olvidar el módulo cargado
sys.path.remove(carpeta)
sys.modules.pop("statistics")
import statistics
print("statistics.mean([1, 2, 3]) =", statistics.mean([1, 2, 3]), " <-", statistics.__file__)Look at the final step: removing the directory from sys.path is not enough, because the loaded module remains in the sys.modules cache and import returns it without searching. For the same reason, after reinstalling a package, a notebook continues to use the old version until you restart the kernel.
pyproject.toml: the project description
The description used to regenerate the environment lives in pyproject.toml, the standard configuration file for a Python project. This is what uv init creates:
uv init --package atlas-lab --python 3.12
atlas-lab/
├── .git/ # uv init también crea el repositorio
├── .gitignore # ya ignora .venv, __pycache__, dist...
├── .python-version # 3.12
├── README.md
├── pyproject.toml
└── src/
└── atlas_lab/
└── __init__.py
For the course the file looks like this (we will add PyTorch below):
[project]
name = "atlas-lab"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"numpy>=2.0",
"pandas>=2.2",
"matplotlib>=3.9",
]
[project.optional-dependencies]
rl = ["gymnasium>=1.0"] # uv sync --extra rl
[dependency-groups]
dev = ["pytest>=8", "jupyterlab>=4", "ipykernel>=6"] # uv sync los instala por defecto
[build-system]
requires = ["uv_build>=0.10.11,<0.11.0"] # uv init escribe aquí su propia versión
build-backend = "uv_build"
Why use a package instead of a directory of scripts? A src/ layout and an editable install address the import problem at its source. Without them, from atlas_lab.data import cargar works when you run from the project root and fails from notebooks/ or scripts/, leaving you to write sys.path.append("..") in every notebook. With them, atlas_lab is an installed package that imports the same way from anywhere. uv sync installs the project in editable mode by default. Check this by finding atlas_lab.pth in site-packages; it contains one line, the absolute path to your src directory.
Notice what the specifiers say. numpy>=2.0 is a set of acceptable versions. The project declares constraints; someone must choose a concrete version of every package that satisfies all of them, including the constraints of indirect dependencies. That is our next topic.
Resolving dependencies
Before resolving anything, we need to compare versions. The first surprise is that they are not strings: "1.10.0" < "1.9.0" is true as a string comparison but false as a version comparison. PEP 440 defines ordering by comparing numeric components one by one, and specifiers as intersections of clauses.
import re
def parse_version(s):
"""'1.26.4' -> (1, 26, 4). Subconjunto de PEP 440: solo números separados por puntos."""
return tuple(int(p) for p in s.split("."))
def _cumple(v, op, w):
# las tuplas se comparan componente a componente; se rellenan con ceros: 2.0 == 2.0.0
n = max(len(v), len(w))
v, w = v + (0,) * (n - len(v)), w + (0,) * (n - len(w))
if op == "==": return v == w
if op == "!=": return v != w
if op == ">=": return v >= w
if op == "<=": return v <= w
if op == ">": return v > w
if op == "<": return v < w
raise ValueError(op)
def satisfies(version, spec):
"""¿Cumple 'version' el especificador 'spec'? Ejemplo: satisfies('1.26.4', '>=1.24,<2')."""
v = parse_version(version)
for clausula in filter(None, (c.strip() for c in spec.split(","))):
op, w = re.fullmatch(r"(~=|==|!=|>=|<=|>|<)\s*([\d.]+)", clausula).groups()
w = parse_version(w)
if op == "~=": # ~=X.Y.Z equivale a >=X.Y.Z, ==X.Y.*
if not (_cumple(v, ">=", w) and v[:len(w) - 1] == w[:-1]):
return False
elif not _cumple(v, op, w):
return False
return True
versiones = ["1.9.0", "1.10.0", "1.26.4", "1.27.0", "2.0.2", "2.1.3", "1.24.4"]
print("orden de cadenas: ", sorted(versiones))
print("orden de versiones:", sorted(versiones, key=parse_version))
for spec in [">=1.24,<2", "~=1.26", "~=1.26.0", "!=2.0.2,>=2"]:
print(f"{spec:12s} ->", [v for v in versiones if satisfies(v, spec)])The ~= operator (“compatible version”) deserves attention: ~=1.26 means “at least 1.26 and within 1.”, while ~=1.26.0 means “at least 1.26.0 and within 1.26.”. One extra component changes “any later 1.x” to “only 1.26 patches”: in the output, 1.27.0 satisfies the first but not the second.
The problem
A package index (PyPI or the PyTorch index) is a set of (package, version) pairs, each publishing its own dependencies as specifiers. Your project adds the root constraints.
Among valid installations, resolvers usually prefer newer versions. This is where drift appears: the index changes over time, so the “best” solution changes too. The specifiers in pyproject.toml say what you accept; the lockfile records what you chose. The former helps people reason about compatibility, while the latter lets machines reproduce an environment.
The most direct way to find an installation is depth-first search with backtracking: decide packages in the order they appear, try each version from newest to oldest, discard those that conflict with previous choices, and if a package runs out of candidates, undo the last decision and try the next one.
Three lessons emerge from the figure. First, a narrow constraint on an indirect dependency can hold back the entire environment. Your project does not mention numpy<2.0, but vizlib imposes it and affects numpy, which affects modelkit. Second, without a lockfile, the same pyproject.toml produces different environments on different dates, and not just for the package that changed: the arrival of modelkit 3.0 causes vizlib to move down from 1.6 to 1.4. Third, the resolver backtracks to old versions without an upper bound. vizlib 1.4 says nothing about numpy 2 because it was published before numpy 2 existed; the resolver treats them as compatible and the error appears at runtime. This is exactly what happened with many packages when NumPy 2.0 was released.
Here is the figure’s resolver in Python, with a candidate counter and a list of constraints that ruled candidates out:
def resolver(raiz, indice, traza=False):
"""
Resolvedor por retroceso. raiz: {paquete: especificador}; indice: {paquete: {versión: {dep: especificador}}}.
Devuelve (asignación o None, estadísticas). Decide los paquetes en el orden en que se descubren y prueba
sus versiones de la más nueva a la más antigua.
"""
restricciones = [(p, s, "raíz") for p, s in raiz.items()] # (paquete, especificador, quién la impone)
elegido, orden = {}, list(raiz)
stats = {"probados": 0, "retrocesos": 0, "culpables": set()}
def buscar(nivel):
pendiente = next((p for p in orden if p not in elegido), None)
if pendiente is None:
return True # todos decididos: solución
for v in sorted(indice.get(pendiente, {}), key=parse_version, reverse=True):
stats["probados"] += 1
viola = [(s, quien) for p, s, quien in restricciones if p == pendiente and not satisfies(v, s)]
if viola:
stats["culpables"].add(f"{viola[0][1]} exige {pendiente}{viola[0][0]}")
continue
deps = indice[pendiente][v]
choque = [(d, s) for d, s in deps.items() if d in elegido and not satisfies(elegido[d], s)]
if choque:
stats["culpables"].add(f"{pendiente} {v} exige {choque[0][0]}{choque[0][1]}")
continue
if traza:
print(" " * nivel + f"{pendiente} {v}")
elegido[pendiente] = v
restricciones.extend((d, s, f"{pendiente} {v}") for d, s in deps.items())
n_orden = len(orden)
orden.extend(d for d in deps if d not in orden)
if buscar(nivel + 1):
return True
# deshacer la decisión y probar la siguiente versión
del elegido[pendiente]
del restricciones[len(restricciones) - len(deps):]
del orden[n_orden:]
stats["retrocesos"] += 1
return False
ok = buscar(0)
return (dict(elegido) if ok else None), stats
# el índice de juguete del interactivo, tal como está en junio
indice = {
"modelkit": {"3.0": {"numpy": ">=2.0", "tensorcore": ">=2.1"},
"2.4": {"numpy": ">=1.24", "tensorcore": ">=2.0"},
"2.3": {"numpy": ">=1.24", "tensorcore": ">=1.9"}},
"vizlib": {"1.6": {"numpy": ">=1.24,<2.0"}, "1.5": {"numpy": ">=1.24,<2.0"}, "1.4": {"numpy": ">=1.20"}},
"numpy": {v: {} for v in ["2.2", "2.1", "2.0", "1.26", "1.24"]},
"tensorcore": {"2.1": {"numpy": ">=1.26"}, "2.0": {"numpy": ">=1.24"}, "1.9": {"numpy": ">=1.24"}},
}
nuevas = {("modelkit", "3.0"), ("numpy", "2.2")} # publicadas en junio
enero = {p: {v: d for v, d in vs.items() if (p, v) not in nuevas} for p, vs in indice.items()}
raiz = {"modelkit": "", "vizlib": "", "numpy": ""}
for nombre, idx, r in [("enero", enero, raiz), ("junio", indice, raiz),
("junio, vizlib>=1.5", indice, {**raiz, "vizlib": ">=1.5"}),
("junio, vizlib>=1.5 y numpy>=2.0", indice, {**raiz, "vizlib": ">=1.5", "numpy": ">=2.0"})]:
sol, st = resolver(r, idx)
print(f"{nombre:32s} probados={st['probados']:2d} retrocesos={st['retrocesos']} ->", sol)
if sol is None:
print(" restricciones implicadas:", sorted(st["culpables"]))
print("\ntraza de junio (cada nivel de sangría es una decisión):")
resolver(raiz, indice, traza=True);The trace shows June’s two backtracks: once modelkit 3.0 is chosen, vizlib 1.6 and 1.5 leave numpy without candidates and are undone, while vizlib 1.4 leaves room. The constraints implicated in the impossible case are a miniature version of what pip or uv print on failure: a chain of constraints that cannot all be satisfied together.
Why resolution is hard
The search finishes immediately for the toy index. Is that always true? No. The problem is intrinsically hard.
The proof is a polynomial reduction from 3-SAT, the problem of deciding whether a Boolean formula in conjunctive normal form with three literals per clause is satisfiable (the SAT problem). The construction, as presented by Russ Cox (2016), works as follows. Given a formula with variables and clauses :
- For each variable , create a package
x_iwith two versions:1.0means false and2.0means true. - For each clause , create a package
c_jwith three versions. Version requires the version of the variable in that makes true:==2.0if and==1.0if . - The root requires all
c_j, at any version.
Choosing a version of c_j chooses which literal in the clause is committed to being true, and assumption (a) forces all commitments to be consistent. You will prove that the equivalence works in both directions in the guided exercise at the end. The index has versions, so the reduction is polynomial.
Assumption (a) matters in practice: Python cannot load two versions of the same package in a process, so pip, uv, and conda satisfy it. npm allows different copies of a library for each package using it, which makes its resolution problem easier, except for peerDependencies, which again require a single copy.
import time
def indice_desde_cnf(clausulas, n):
"""Reducción de 3-SAT: x{i} con 1.0 (falso) y 2.0 (verdadero); c{j} con una versión por literal."""
indice = {f"x{i}": {"1.0": {}, "2.0": {}} for i in range(1, n + 1)}
for j, clausula in enumerate(clausulas, 1):
indice[f"c{j}"] = {f"{k}.0": {f"x{abs(lit)}": "==2.0" if lit > 0 else "==1.0"}
for k, lit in enumerate(clausula, 1)}
raiz = {f"c{j}": "" for j in range(1, len(clausulas) + 1)}
return raiz, indice
# (x1 ∨ ¬x2 ∨ x3) ∧ (¬x1 ∨ x2) ∧ (¬x3 ∨ ¬x2) ∧ (x2 ∨ x3)
cnf = [[1, -2, 3], [-1, 2], [-3, -2], [2, 3]]
sol, st = resolver(*indice_desde_cnf(cnf, 3))
asignacion = {k: v == "2.0" for k, v in sorted(sol.items()) if k.startswith("x")}
print("instalación:", sol)
print("asignación: ", asignacion)
print("¿satisface la fórmula?", all(any(asignacion[f"x{abs(l)}"] == (l > 0) for l in c) for c in cnf))
# insatisfacible: (x1) ∧ (¬x1 ∨ x2) ∧ (¬x2)
sol, st = resolver(*indice_desde_cnf([[1], [-1, 2], [-2]], 2))
print("\ninsatisfacible ->", sol, " restricciones implicadas:", sorted(st["culpables"]))
# El peor caso del retroceso cronológico: k paquetes libres de 2 versiones y, al final, un conflicto
# (a exige b>=2.0 y no existe) que no depende de ellos. El resolvedor prueba las 2^k combinaciones.
def trampa(k):
indice = {f"p{i}": {"2.0": {}, "1.0": {}} for i in range(k)}
indice["a"] = {"1.0": {"b": ">=2.0"}}
indice["b"] = {"1.0": {}}
return {**{f"p{i}": "" for i in range(k)}, "a": ""}, indice
print("\n k probados retrocesos segundos")
for k in [4, 8, 10, 12]:
t0 = time.perf_counter()
sol, st = resolver(*trampa(k))
print(f"{k:2d} {st['probados']:10d} {st['retrocesos']:12d} {time.perf_counter() - t0:10.3f}")The final table shows the weakness of chronological backtracking, which always undoes the last decision whether or not it caused the conflict. The conflict between a and b has nothing to do with packages p0, p1, …, yet the resolver rediscovers it for each of the combinations of those packages. It tries exactly candidates: the in the binary tree of p packages, plus two for each of its leaves. NP-completeness says that, if P ≠ NP, no algorithm solves every index in polynomial time. This particular index is hard because of our algorithm.
Real resolvers tackle the latter issue. uv uses PubGrub, an algorithm that derives and remembers an incompatibility (“a 1.0 cannot be installed”) when it finds a conflict, so it does not explore another branch containing it. This is the idea behind conflict-driven clause learning (CDCL) in modern SAT solvers. When a lockfile already exists, uv also prefers locked versions, so very little search may be needed. You will implement that preference in the code exercise.
uv in practice
uv is a Python project manager written in Rust that combines tasks previously handled by several tools. It installs Python interpreters, creates environments, resolves, locks, synchronizes, and runs. Its uv.lock file is universal: a single resolution covers Linux, Windows, and macOS, with markers such as sys_platform == 'win32' where dependencies differ. For example, pytest depends on colorama only on Windows, and the lockfile records that as follows:
[[package]]
name = "pytest"
version = "9.1.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "colorama", marker = "sys_platform == 'win32'" },
{ name = "iniconfig" },
{ name = "packaging" },
{ name = "pluggy" },
{ name = "pygments" },
]
sdist = { url = "https://files.pythonhosted.org/.../pytest-9.1.1.tar.gz", hash = "sha256:1088fbde...", size = 1636369 }
wheels = [
{ url = "https://files.pythonhosted.org/.../pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45...", size = 386536 },
]
Each artifact carries its sha256. If the index served a different file with the same version number tomorrow, installation would fail instead of continuing silently. A package with native extensions such as numpy appears with dozens of wheels, one for each combination of operating system, architecture, and Python version.
Commands you will use daily:
| Command | What it does |
|---|---|
uv init --package nombre | creates the project with src/, pyproject.toml, and .python-version |
uv python install 3.12, uv python pin 3.12 | installs a uv-managed interpreter and pins it in .python-version |
uv add "numpy>=2" | adds the constraint to pyproject.toml, resolves again, updates uv.lock, and synchronizes |
uv add --dev pytest, uv add --optional rl gymnasium | does the same in a development group or an extra |
uv lock | resolves and writes uv.lock without installing anything |
uv lock --upgrade-package numpy | resolves again, allowing only numpy and any necessary dependencies to change |
uv sync | makes .venv match uv.lock exactly, installing missing packages and removing extras |
uv sync --locked | works like uv sync but fails if uv.lock is out of date with pyproject.toml (for continuous integration) |
uv run script.py | checks the lockfile, synchronizes if necessary, and runs using the environment’s interpreter |
uv tree | shows the resolved dependency graph |
The workflow is consistent: declare in pyproject.toml (by hand or with uv add), resolve with uv lock, and materialize with uv sync. uv run chains the last two steps before execution, so always using uv run keeps the environment aligned with the lockfile. Installing packages is inexpensive: uv downloads them once to a global cache and links them into each environment.
The GPU stack
Installing PyTorch with GPU support is a common source of failures, usually because it is unclear which components depend on which. When you write x.to("cuda"), the request passes through several software layers, each with its own version.
For an operation to reach the GPU, three conditions between layers must hold:
None of the three conditions mentions the system CUDA Toolkit. A widespread installation mistake is to install the Toolkit after a failure; it takes several gigabytes and changes nothing because PyTorch uses the runtime in its own wheel. Minimum driver versions come from the NVIDIA table, and architectures for each wheel variant come from the PyTorch 2.11 support matrix.
The V100 case deserves an explanation. The cu128 wheel contains sm_75, with the same major version as the V100 (7.0) but a higher minor version, so that code cannot run on 7.0. Yet torch.cuda.is_available() returns True: it checks only that the driver sees a GPU, not that code exists for it. On CUDA initialization, PyTorch 2.11 applies the exact rule and emits a UserWarning beginning “Found GPU0 … which is of compute capability (CC) 7.0”. A warning does not stop execution and can be missed in a script with many warnings. The error appears at the first kernel: “no kernel image is available for execution on the device”. Thus is_available() alone is insufficient as a smoke test; run an operation on the GPU, as the diagnostic below does.
The course laptop corresponds to the “course laptop” case. The cu128 wheel does not include sm_89, but does include sm_86, which the 4060 executes through compatibility within major version 8. This applies to PyTorch’s own kernels. NVIDIA libraries shipped with the wheel, such as cuBLAS and cuDNN, have their own code for each supported architecture.
Installing PyTorch with CUDA on Windows
If you simply add torch, uv looks for it on PyPI. According to the uv documentation, PyPI publishes CUDA wheels for Linux (CUDA 13.0 from PyTorch 2.11 onward) but CPU-only wheels for Windows and macOS. On the course laptop, uv add torch installs a wheel without error that does not use the GPU. CUDA variants are in a dedicated PyTorch index, with one URL per CUDA version (https://download.pytorch.org/whl/cu128, .../cu130…). Tell uv to take torch from there, and only torch:
[project]
dependencies = [
"numpy>=2.0",
"pandas>=2.2",
"matplotlib>=3.9",
"torch>=2.11",
]
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true # este índice solo se usa para los paquetes que lo piden en [tool.uv.sources]
[tool.uv.sources]
torch = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux' or sys_platform == 'win32'" }]
explicit = true prevents uv from looking in that index for any other package. The PyTorch index also hosts copies of numpy and others, which we do not want to obtain there. The marker keeps torch coming from PyPI on macOS, where CUDA is unavailable. Why cu128 instead of cu130? Both work on the 4060 with the current driver; cu128 is installed and verified in the lab. Never choose a variant newer than your driver supports (check with nvidia-smi). Also consider size: the lab’s torch/lib directory occupies about 4 GB, mostly CUDA libraries, so place uv’s cache on a drive with enough space.
After uv sync, verify from Python using the environment’s interpreter. Here is the local lab diagnostic:
import os, platform, shutil, subprocess, sys
import torch
print("python ", platform.python_version(), " en", sys.prefix)
print("¿venv? ", sys.prefix != sys.base_prefix)
print("torch ", torch.__version__, " CUDA de la wheel:", torch.version.cuda, " cuDNN:", torch.backends.cudnn.version())
# las librerías de CUDA viajan dentro de la wheel (en Linux, como paquetes de NVIDIA aparte)
lib = os.path.join(os.path.dirname(torch.__file__), "lib")
if os.path.isdir(lib):
print("DLL de CUDA en torch/lib:", sorted(f for f in os.listdir(lib) if f.startswith(("cudart", "cudnn64", "cublas64"))))
# el driver, visto por nvidia-smi
smi = shutil.which("nvidia-smi")
if smi:
q = subprocess.run([smi, "--query-gpu=name,driver_version,compute_cap,memory.total", "--format=csv,noheader"],
capture_output=True, text=True, timeout=30)
print("nvidia-smi ", q.stdout.strip())
if torch.cuda.is_available():
cap = torch.cuda.get_device_capability(0)
sms = [int(a[3:]) for a in torch.cuda.get_arch_list() if a.startswith("sm_")]
usable = [s for s in sms if s // 10 == cap[0] and s % 10 <= cap[1]]
print("GPU ", torch.cuda.get_device_name(0), f" compute capability {cap[0]}.{cap[1]}")
print("arch list ", torch.cuda.get_arch_list(), " código que se ejecutará:",
f"sm_{max(usable)}" if usable else "ninguno (el primer kernel fallará)")
torch.manual_seed(0)
a = torch.randn(1024, 1024, device="cuda")
print("matmul GPU frente a CPU, diferencia máxima:", (a @ a).cpu().sub(a.cpu() @ a.cpu()).abs().max().item())
else:
print("CUDA no disponible: revisa la variante de la wheel (torch.version.cuda) y el driver")
# toolchain nativa (solo hace falta para compilar extensiones propias)
for tool in ["cl", "cmake", "ninja", "nvcc", "gcc"]:
print(f"{tool:6s}", shutil.which(tool) or "no está en el PATH")npm run lab and open the connection link.On the course laptop it prints torch 2.11.0+cu128, driver 596.49, compute capability 8.9, and the list sm_75 through sm_120 without sm_89. The code executed is sm_86, as rule 2 predicts. The last GPU line previews the final section: the same matrix product on GPU and CPU differs on the order of with the same environment and seed.
Native toolchain: compiler and CMake
You rarely need to compile anything to use PyTorch, but the course will do so at times: C++ extensions to speed up a loop, custom CUDA kernels in the scaling module, or packages without a wheel for your platform, which pip and uv compile from source. This requires a native toolchain, often the trickiest part on Windows.
On Windows, cl.exe is not on PATH by default. The vcvars64.bat script adds it when you open “x64 Native Tools Command Prompt” or “Developer PowerShell for VS”. That is why the diagnostic above says it is not on PATH even when Visual Studio is installed. Verify in two steps from that terminal:
winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"
winget install Kitware.CMake
# 1. un programa mínimo
"int main() { return 0; }" | Out-File -Encoding ascii hola.cpp
cl /nologo /EHsc hola.cpp; .\hola.exe; echo "código de salida: $LASTEXITCODE"
# 2. una extensión mínima de PyTorch (compila con cl y ninja la primera vez)
uv add --dev ninja
uv run python -c "from torch.utils.cpp_extension import load_inline; m = load_inline(name='suma', cpp_sources='int suma(int a, int b) { return a + b; }', functions=['suma']); print(m.suma(2, 3))"
If the second step prints 5, the whole chain works: compiler, Python and PyTorch headers, and loading the resulting DLL. If it fails, the message usually identifies which link is missing.
What the lockfile does not capture
With pyproject.toml, uv.lock, and .python-version in the repository, uv sync reproduces the Python environment on any machine. Is that enough to reproduce an experiment? Work through the layers from bottom to top and see what is missing.
What Python tools cannot pin, including the driver, operating system, and GPU, can still be recorded. If a result changes in six months, the first question will be what changed, and you can answer only if you recorded it. Each course experiment will therefore save an environment report alongside its metrics: versions of Python and key libraries, the wheel’s CUDA variant, driver, GPU, and compute capability. You will write it in the code exercise; the lesson on experiment provenance integrates it into every run record.
Even with everything recorded, two runs may not produce the same bits. The difference between GPU and CPU in the previous cell is not an error: each sums products in a different order, and floating-point addition is not associative, as formalized in floating-point representation. Distinguishing reproducibility of the environment, statistical results, and bits is the subject of reproducibility levels; GPU-specific sources of variation are covered in GPU nondeterminism.
Setting up the course environment
With all of that in place, here is the complete procedure from a machine with the NVIDIA driver installed and nothing else. Python is not required beforehand: uv downloads the interpreter.
# 0. uv (una sola vez por máquina)
winget install astral-sh.uv
# 1. el proyecto
uv init --package atlas-lab --python 3.12
cd atlas-lab
uv add "numpy>=2.0" "pandas>=2.2" "matplotlib>=3.9"
uv add --dev pytest jupyterlab ipykernel
# 2. PyTorch desde el índice CUDA: añade [[tool.uv.index]] y [tool.uv.sources] a pyproject.toml
# (bloque de la sección anterior) y después
uv add "torch>=2.11"
uv run python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available())"
# 3. al repositorio (uv init ya creó uno con git): el código y la descripción del entorno, nunca .venv
git add pyproject.toml uv.lock .python-version .gitignore README.md src
git commit -m "Esqueleto del proyecto"
The definitive reproducibility test is to regenerate the environment from scratch in another directory and check that it is identical:
git clone atlas-lab atlas-lab-copia
cd atlas-lab-copia
uv sync --locked # falla si uv.lock no corresponde a pyproject.toml
uv pip freeze --exclude-editable > ..\copia.txt
cd ..\atlas-lab
uv pip freeze --exclude-editable > ..\original.txt
Compare-Object (Get-Content ..\original.txt) (Get-Content ..\copia.txt) # sin salida: idénticos
Empty output means that both directories contain exactly the same packages and versions. The project itself is excluded because its editable-install path differs in each copy. The skeleton is now ready; its internal structure (data directories, configuration, and scripts) is completed in the anatomy of a research project.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. Why is the problem in NP?
resolve(root, index, locked=None). root is a dictionary {paquete: especificador}, index is {paquete: {versión: {dependencia: especificador}}}, and locked is a previous lockfile {paquete: versión} or None. Return {paquete: versión} containing exactly the packages reachable from the root, or None if there is no solution. Search depth-first with backtracking, deciding packages in discovery order. For each package, try its locked version first if it exists in the index, followed by the others from newest to oldest. This preserves a compatible lockfile and changes only what is necessary if it becomes incompatible. parse_version and satisfies are already implemented.def parse_version(s):
return tuple(int(p) for p in s.split("."))
def satisfies(version, spec):
"""Especificadores separados por comas con ==, !=, >=, <=, >, <. La cadena vacía no restringe."""
v = parse_version(version)
ops = {"==": lambda a, b: a == b, "!=": lambda a, b: a != b, ">=": lambda a, b: a >= b,
"<=": lambda a, b: a <= b, ">": lambda a, b: a > b, "<": lambda a, b: a < b}
for c in filter(None, (c.strip() for c in spec.split(","))):
op = next(o for o in ("==", "!=", ">=", "<=", ">", "<") if c.startswith(o))
w = parse_version(c[len(op):])
n = max(len(v), len(w))
if not ops[op](v + (0,) * (n - len(v)), w + (0,) * (n - len(w))):
return False
return True
def resolve(root, index, locked=None):
"""Devuelve {paquete: versión} o None. Prueba primero la versión de locked y luego de la más nueva a la más antigua."""
# tu código: búsqueda en profundidad con retroceso
return {}
env_report() returning a dictionary with keys python (platform.python_version()), numpy and torch (their __version__, or None), cuda (torch.version.cuda, or None), gpu (torch.cuda.is_available(), False when torch is absent), gpu_name and capability (for example '8.9', or None), memory_gib (device 0's total memory in GiB rounded to one decimal, or None), and error (None or text describing what failed). It must never raise an exception: it must work without torch, with the CPU-only wheel, and when importing torch raises OSError because a DLL cannot load. It must not query the device when is_available() is False. Tests replace torch with fake modules to simulate each case.import platform
def env_report():
"""Diccionario con versiones, CUDA y GPU; nunca lanza una excepción."""
rep = {"python": platform.python_version()}
# tu código
return rep
Summary
- A virtual environment is a directory with
pyvenv.cfgand its ownsite-packages.importsearchessys.pathin order and the first match wins. It does not isolate the driver, system libraries, or environment variables. pyproject.tomldeclares the project (dependencies, extras, development groups, and build system). Withsrc/and an editable install, your package imports consistently from anywhere.- Dependency resolution searches for one version per package satisfying every constraint. With one version per package it is NP-complete (by reduction from 3-SAT). Chronological backtracking can be exponential, and real resolvers such as uv’s PubGrub learn incompatibilities.
- Without a lockfile, the same
pyproject.tomlproduces different environments at different times, sometimes backtracking to old versions without upper bounds.uv.lockis universal and stores each artifact’s hash;uv syncmakes the environment match it. - The CUDA stack has three rules: a driver supporting the wheel runtime, machine code with the same major version and a minor version no higher than the GPU’s (the 4060, 8.9, runs
sm_86), and a CUDA wheel. On Windows, PyPI has CPU wheels only, so configure the PyTorch index. The CUDA Toolkit is needed only for compilation. - The native toolchain (MSVC or GCC, CMake, Ninja) is needed only for compiling extensions. Check it by compiling a minimal program and extension.