Skip to content

How a program actually runs

Phase 1 · Working like an engineer · 14 min read

What you'll be able to do

  • Trace what happens when you launch a Python script, from the shell to OS resources and the program's exit.
  • Estimate memory use before a batch or model allocation, and diagnose common Python reference bugs.
  • Explain why output disappears, imports fail, and a CPU-bound Python loop can lag behind a vectorized operation.

From a command to a process

When you run python train.py, the shell asks the operating system (OS) to start a process running the Python interpreter. The OS gives it a process ID, memory, and input/output handles. It schedules CPU time and mediates access to files, devices, and the network.

A system call crosses from your process into the OS. Opening a file, creating a process, and writing to a socket require one. Python's open() makes system calls underneath; the OS can refuse them if a path is missing or access is denied.

Each process has a virtual address space. The OS and hardware map the pages it actually uses to physical memory as needed; some pages are backed by files or swap, and a reserved range need not occupy RAM yet. The same address in two processes need not refer to the same object. Virtual addresses do not add usable memory; allocations can still fail.

Starting a script: the shell asks the OS for a process, the interpreter runs your code, and syscalls reach the OS.

Where a process keeps data

Python tracks active calls in frames, forming a logical call stack: each call adds a frame holding its local names and where to resume, and returning removes it. Do not assume each Python frame is a native stack allocation. Deep recursion piles up frames; Python normally raises RecursionError at its recursion limit first.

A local name usually refers to an object managed by the interpreter. A tensor's Python object and its underlying data are distinct allocations, and the data may live in RAM or GPU memory. Python reclaims unreachable objects. CPython commonly uses reference counting and a collector for cycles; other implementations may differ. del x removes one reference, but another may remain. Even reclaimed memory may stay reserved by an allocator.

Try this in Python:

def hold(value):
    saved = value
    return saved

items = [1, 2]
other = hold(items)
del items
print(other)  # [1, 2]: the list is still reachable

Values, references, and accidental sharing

Assignment binds a name to an object. For an immutable number, rebinding a name leaves another name's value alone. For a mutable list, two names can point at the same object:

a = [[0], [0]]
b = a
b[0].append(7)
print(a)  # [[0, 7], [0]]

a.copy() makes a new outer list but shares inner lists. copy.deepcopy(a) recursively copies the structure, though this can be expensive. Often, build separate objects: [[0] for _ in range(2)], not [[0]] * 2.

Default argument expressions are evaluated when the function is defined, so a mutable default can persist across calls:

def record(item, history=None):
    if history is None:
        history = []
    history.append(item)
    return history

print(record("first"))   # ['first']
print(record("second"))  # ['second']

In data pipelines, decide whether a function mutates its caller's object or copies it, and document that choice.

Memory is a budget

For raw data, calculate element count × bytes per element. A float32 takes 4 bytes, so one billion floats need 1,000,000,000 × 4 = 4,000,000,000 bytes, about 4 GB (3.73 GiB). A 32 × 3 × 224 × 224 float32 batch has 4,816,896 elements and needs 19,267,584 bytes, about 19.3 MB. One billion float32 model weights also need about 4 GB. Training additionally needs gradients, optimizer state, activations, and copies.

RAM is main system memory; VRAM is GPU memory; disk stores data persistently. They are separate budgets, and a tensor may occupy both RAM and VRAM. CPU cache, RAM, GPU memory, and disk differ in latency and bandwidth, and transfers between CPU and GPU also cost time. Cost depends on hardware, access pattern, and caching, so measure the workload rather than assigning one time to "memory access". An out-of-memory error means an allocation cannot fit the available budget; retained objects, other processes, and fragmentation matter.

Estimate before you allocate

Budget for shape, dtype, copies, and peak live intermediates. Copying that 19.3 MB batch needs roughly another 19.3 MB while both copies live.

Files, output, and process lifetime

On Unix-like systems, open files and sockets use file descriptors, small per-process integers. Standard input (stdin), output (stdout), and error (stderr) are streams set up at process start, and may be inherited or redirected. “Everything is a file” means many resources share a read/write interface; their behavior still differs. Windows uses different handle mechanisms.

Output can be buffered. print("saved", flush=True) sends Python's buffered text onward but does not guarantee durable disk storage. Forceful termination can lose unwritten logs. Flush important progress; a missing final line does not prove the code never reached it.

Exit code 0 means success; nonzero usually means failure. Unix kill sends a signal; forceful kill prevents cleanup. On Unix-like systems, a zombie is an exited child whose parent has not collected its status, and an orphan is a running child whose parent exited; it is typically reparented to a system process.

Threads share one process's address space; processes normally have separate spaces. Worker processes may duplicate a dataset, depending on startup and sharing. Threads share data but need coordination for mutation. Concurrency covers the GIL and safe sharing.

Streams and child processes

A generator function uses yield; calling it consumes nothing until you iterate. A file object yields one line at a time, so you can scan a huge file without loading it, and with closes it:

def nonempty(lines):
    for line in lines:
        if line.strip():
            yield line

with open("log.txt", encoding="utf-8") as stream:
    kept = sum(1 for _ in nonempty(stream))

To run another program, subprocess.run takes an argument list, not a shell string:

import subprocess, sys
r = subprocess.run([sys.executable, "-c", "print(1)"],
                   capture_output=True, text=True, check=False)
print(r.returncode, r.stdout, r.stderr)  # 0 '1\n' ''

returncode is the exit code; stdout and stderr are separate captured text. With check=False, nonzero exit does not raise.

How Python finds and runs code

Python executes through an interpreter, while a compiled program has machine code prepared ahead of time. Python also compiles source to bytecode and can call compiled libraries. A Python loop pays interpreter overhead per element; vectorized NumPy moves much of the loop into compiled code. Vectorization may allocate large temporaries, so measure time and memory.

An import searches sys.path, which depends partly on how Python was launched. python project/train.py and python -m project.train can behave differently: -m preserves package context. ModuleNotFoundError can mean a missing package, wrong interpreter, or wrong import path. Inspect sys.executable, sys.path, and the launch command.

# Save as demo.py, then run: python demo.py
import sys

print("module name:", __name__)
print("interpreter:", sys.executable)
if __name__ == "__main__":
    print("run as the entry point")

When imported, __name__ is the module name, so guarded script behavior does not run.

For AI engineers

For AI engineers

For CUDA out of memory, budget weights, batches, activations, gradients, and copies. A list retaining output tensors can also retain their computation graphs. Data-loader workers are commonly processes: check whether they copy the dataset or share storage. Unpickling a model file can execute code; never unpickle an untrusted file.

Common mistakes

  • Using [] or {} as a default argument and leaking state between calls.
  • Using [[0] * columns] * rows and then wondering why editing one row edits every row.
  • Appending ten million outputs to a Python list when each row could be processed and discarded.
  • Assuming del x immediately frees memory, even when references or allocator reservations remain.
  • Expecting threads to speed up a CPU-bound Python loop without measuring; see Concurrency.
  • Running a package file from the wrong directory and treating a relative import failure as a missing dependency.

Check yourself

A float32 batch has shape (64, 3, 256, 256). How much raw memory does it need, and what happens if an operation keeps both input and output?

64 × 3 × 256 × 256 = 12,582,912 elements, or 50,331,648 bytes (50.3 MB). A same-sized output doubles their raw storage to about 100.7 MB.

You make b = a.copy() where a is a list of lists, then append to b[0]. Why does a[0] change?

The outer list was copied, but both lists share the inner list. Build new inner lists or use copy.deepcopy.

A subprocess returns status 1, prints nothing to stdout, and writes an error to stderr. Did your shell command succeed, and where should you look?

It failed. Nonzero means failure; read stderr for the diagnostic.

A script imports successfully with python -m package.worker but fails when run as python package/worker.py. What changed?

The launch form changed package context and import path. Run it as a module from the project root.

Lab

In code/how-programs-run/, calculate tensor bytes and test whether an allocation fits a budget. Fix state leaking through a mutable default and rows shared by aliasing. Count matching lines in a file through a lazy generator, then capture a child process's exit code and two output streams. Read the lab README for the function contracts and complete starter/lab.py. Run: cd code/how-programs-run && PYTHONPATH=starter python -m pytest tests -q Done means all seven tests pass, including the memory-bounded file count and the nonzero subprocess case.

Go deeper