# Environment setup {#sec-environment}
## Python environment and Quarto
This lab uses `uv` for Python environment setup. Run `uv sync` from the project root to create the
virtual environment in `.venv`.
In VS Code, the repository's `.vscode/settings.json` selects `.venv` as the Python interpreter, and
the [Quarto extension](https://marketplace.visualstudio.com/items?itemName=quarto.quarto) passes it
to Quarto (our document generator). If a render fails with `No module named 'yaml'` or
"Jupyter is not available", start a new terminal (or reload the window) so that it picks up the
project interpreter.
## How to render this Quarto book
Run these from the project root:
```bash
quarto preview docs/ --no-execute-daemon # live preview while you write; re-renders a chapter when you save it
quarto render docs/ # render the whole book (the recommended way to build it)
```
**What is re-executed.** Every chapter uses Quarto's `freeze: auto`. A chapter is re-executed, in full,
only when its own `.qmd` file changes, and otherwise its saved results in `docs/_freeze/` are reused.
Quarto does not notice changes to the Python package in `src/convfinqa/`, to `docs/_environment`, or to
the data. To force a re-run of one chapter, delete its folder `docs/_freeze/<chapter>/`, or run
`quarto render docs/<chapter>.qmd --no-execute-daemon`.
**Heavy cells.** Some computations, such as training and full evaluation, take minutes to hours.
Results are stored as named *[artifacts](901_glossary.qmd#gloss-artifact)* in `artifacts/`, each with a `node.json` that records its
configuration and the artifacts it was built from. On later renders a chapter loads the saved result
instead of recomputing, so editing a chapter's text stays cheap. If an upstream artifact changes,
everything built from it counts as stale.
Cells marked `#HEAVY` will not recompute a stale or missing artifact on their own: they raise an
error that names the build command. The error is deliberate, because a preview or an ordinary render
can never start a long run by accident. Setting `ALLOW_STALE=1` relaxes this for artifacts that exist
but are out of date: the cell loads the old result and shows a red warning box above it. A missing
artifact always raises.
**Declaring an artifact.** The recipe sits in the chapter, in the cell that uses the result: a function
decorated with `@artifact(...)`, followed by the call that loads it. Artifact names use letters, digits
and underscores, and a name template such as `sft_{variant}_{seed}` covers a family
(`get("sft_dsl_0")` is one member). The function is only a few lines of glue that call the real logic
in `src/convfinqa/`, and it may use only its own parameters, builtins and imports made inside it, so that
a build in a separate process finds everything it needs. The function must be a plain `def` at the top
level of its cell (not inside an `if` or a function), and a cell marked `#| eval: false` is ignored, so
use a plain `python` fence to show an example. Quarto never has to run a chapter for the build script
to know its artifacts: the registry reads the `.qmd` files and finds the recipes and the `get("name")`
calls by parsing them (a `get` may appear anywhere in a cell, inside flow control too).
**What makes an artifact stale.** An artifact is rebuilt when any of these changed: its parameters or
declared input files; the source of its builder function, or of any `convfinqa` module the function
imports (whitespace, comments and docstrings don't count, and neither do other cells or the chapter's
prose); its builder's manual `version`; or
any artifact it was built from, which in turn must itself be fresh. A rebuild that produces identical
output leaves everything downstream fresh. Every build seeds Python, NumPy and torch from the artifact's
seed first, so its random draws do not depend on what ran before it. GPU training is still not
bit-reproducible, so retraining normally yields new weights and the evaluations built on them are
rebuilt too.
**Building everything.** Before each render, a hook (`pre-render` in `docs/_quarto.yml`) marks the
chapters that used a changed artifact for re-execution, so nothing stale is left in the book. A heavy
build can take hours, so it has to survive a lost terminal. The way to build the book is the script
`build.sh` in the project root:
```bash
./build.sh
```
It does four things:
1. Inside a `screen` session named `render`, builds every missing or stale artifact in dependency
order (`python -m convfinqa.artifacts build --all`), each heavy one in its own process that logs to
`artifacts/<name>/build.log`; then runs `quarto render docs/ --no-execute-daemon --log artifacts/render.log` without
`RUN_HEAVY`, so anything still stale fails loudly instead of starting a hidden run. The session
keeps running if your terminal or connection drops. Detach with `Ctrl-a d` and reattach later with
`screen -r render`.
2. Waits for the session to finish, whether or not you stay attached. It writes its exit status to
`artifacts/render.status`, and the script polls for it.
3. Starts `quarto preview docs/` only if that succeeded, with `ALLOW_STALE=1`, so editing prose keeps
working after a code change made an artifact stale (the warning box marks the old result). The
preview never starts a build. A failure prints its exit code instead, and a killed session is
reported rather than waited on forever.
4. Refuses to start if a `render` session already exists ("Render already in progress"), so two
builds cannot run at once through the script.
That last guard covers **only builds started through `build.sh`.** It looks for the `screen` session by
name. A build started some other way, such as `uv run python -m convfinqa.artifacts build --all` typed
directly, or a `tmux` session, is invisible to it. A per-artifact lock stops two processes building the
same artifact, but two renders writing to `docs/_book/` at once can corrupt each other, so start every
full build through `build.sh`. (`RUN_HEAVY=1 quarto render docs/` also still works, building stale
heavy artifacts as the chapters reach them, in chapter order rather than dependency order.)
**Why `--no-execute-daemon`.** By default Quarto keeps a chapter's Jupyter kernel alive for five minutes
after rendering it, and the next render of that chapter reuses it. A reused kernel keeps the environment
variables it started with, so a later `RUN_HEAVY=1` or `ALLOW_STALE=1` would be silently ignored, and it
keeps whatever code it already loaded. The flag gives every render a fresh kernel. (Setting
`execute: daemon: false` in `_quarto.yml` looked like the same thing but had no effect in Quarto
1.10.19, which we checked.) The artifact registry also re-reads the chapter files when they change, so an
edited builder is never served stale even inside a long-lived kernel.
Quarto's `--log` option is used instead of piping through `tee`, because Quarto writes terminal colour
codes to a pipe and the log file stays free of them. Each render overwrites `artifacts/render.log`,
so copy it if you want to keep one. The per-artifact build logs in `artifacts/<name>/build.log` are
separate (a failed build leaves its log in `artifacts/<name>.tmp/`). If a build fails, nothing renders;
fix the problem and run `./build.sh` again, and the artifacts that were already built are reused.
To see what a full render would build, or to build one artifact without Quarto:
```bash
uv run python -m convfinqa.artifacts status # what is fresh, stale or missing, and why
uv run python -m convfinqa.artifacts build sft_dsl_0 # build one artifact and anything stale it needs
uv run python -m convfinqa.artifacts refresh # re-execute chapters that used outdated artifacts (the pre-render hook does this)
```
## The hardware and the CUDA stack
Three different tools report a "CUDA version", and they mean different things.
- `nvidia-smi` reports the newest CUDA runtime the **driver** supports.
- `torch.version.cuda` is the CUDA runtime **bundled in the PyTorch wheel**.
- `nvcc --version` is the **compiler** installed on the system, used only if we compile CUDA extensions.
Drivers are compatible across minor versions, so these need not match. Here they agree, as the output below shows.
```{python}
import subprocess
import torch
smi = subprocess.run(
["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"],
capture_output=True,
text=True
).stdout.strip()
nvcc = subprocess.run(
["nvcc", "--version"],
capture_output=True,
text=True
).stdout.strip().splitlines()[-2]
smi_cuda = [
l for l in subprocess.run(
["nvidia-smi"], capture_output=True, text=True
).stdout.splitlines()
if "CUDA Version" in l
][0].split("CUDA Version:")[1].split()[0]
print("GPU / driver :", smi)
print("nvidia-smi : CUDA", smi_cuda)
print("torch.cuda :", torch.version.cuda)
print("nvcc :", nvcc.strip())
import re
nvcc_cuda = re.search(r"release (\d+\.\d+)", " ".join(
subprocess.run(["nvcc", "--version"], capture_output=True, text=True)
.stdout.splitlines()
)).group(1)
assert smi_cuda == torch.version.cuda == nvcc_cuda # the sentence below
```
All three say CUDA `{python} nvcc_cuda`.
## Does bf16 work?
This lab uses bf16 for the model computations on the GB10 GPU. This uses 8 exponent bits as in
standard 32-bit floating point (fp32), but only 7 mantissa bits, reducing precision. In return,
bf16 allows for faster computation and reduced memory usage on compatible hardware.
| Format | Bits | Exponent bits | Mantissa bits | Range | Precision |
|--------|------|---------------|---------------|-------|-----------|
| fp32 | 32 | 8 | 23 | about 1e-38 to 3e38 | about 7 digits |
| fp16 | 16 | 5 | 10 | about 6e-5 to 65,504 | about 3 digits |
| bf16 | 16 | 8 | 7 | same as fp32 | about 2 digits |
Computational expressions generated by the model for generating the final outputs will use **exact**
arithmetic; only the model's own computation runs in reduced precision.
```{python}
assert torch.cuda.is_available()
print(torch.cuda.get_device_name(0), torch.cuda.get_device_capability(0))
a = torch.randn(1024, 1024, device="cuda", dtype=torch.bfloat16)
b = torch.randn(1024, 1024, device="cuda", dtype=torch.bfloat16)
c = a @ b
assert c.dtype == torch.bfloat16 and torch.isfinite(c.float()).all()
print("bf16 matmul OK, supported:", torch.cuda.is_bf16_supported())
```
## Library versions
```{python}
from importlib.metadata import version
import sys
print("python", sys.version.split()[0])
for pkg in [
"torch", "transformers", "datasets", "accelerate", "peft",
"trl", "xgrammar", "sympy", "tensorboard"
]:
print(f"{pkg:13s}", version(pkg))
```