1. Introduction

As a cloud infrastructure and SRE engineer, I have spent plenty of time setting up GPU environments for others. Ironically, I had never actually used TensorFlow myself.

When I recently started working through deep learning material that relies on TensorFlow, I wanted to run everything locally on my laptop instead of spinning up cloud instances.
That immediately raised a few questions:

  • Does TensorFlow run on both CPU and GPU out of the box, and can I toggle between them cleanly?
  • Is it even worth using a modest, older 4GB laptop GPU instead of just relying on the CPU?
  • How do I install and configure TensorFlow inside a uv-managed Python project without polluting my operating system with system-wide CUDA packages?
  • Most importantly: how does GPU memory management actually behave under the hood when you are working inside Jupyter notebooks or Python scripts?

This post, like most posts, is my notes documenting the exact setup, commands, gotchas, and mental models I uncovered along the way.

Is a 4GB Laptop GPU Even Worth Using?

Before touching any dependencies, the first question is whether an older, 4GB GPU is worth the setup effort over a modern laptop CPU.

  • For deep learning (neural networks, computer vision, NLP): Yes. Even an older workstation GPU with 768 CUDA cores will train neural networks significantly faster than a laptop CPU, while also keeping your CPU from thermal throttling as hard during long training runs.
  • For classic tabular ML (linear regression, decision trees): The CPU is rarely a bottleneck anyway, so GPU acceleration won’t move the needle much.

The main constraint: With 4GB of VRAM, you will hit OOM errors if you blindly copy-paste large batch sizes or massive pre-trained architectures from places that assume big GPUs (usually in the clouds). Managing that 4GB ceiling cleanly is half the battle. And we will cover exact strategies for doing that.

My Setup

If you try to replicate my steps and run into different behavior, compare your environment against mine:

  • Operating System: Ubuntu 24.04 LTS (Noble Numbat)
  • GPU: NVIDIA Quadro P2000 (Pascal architecture, 4096 MiB VRAM, Compute Capability 6.1)
  • NVIDIA Driver: Version 580.196.07
  • Python Package Manager: uv

You can find the GPU information for your setup via:

nvidia-smi --query-gpu=name,memory.total,compute_cap --format=csv

For me, that outputs:

name, memory.total [MiB], compute_cap
Quadro P2000, 4096 MiB, 6.1

Python Version Pinning

Do not use bleeding-edge Python versions with TensorFlow, especially on older hardware like Pascal (6.1). TensorFlow lags behind new CPython releases for official pre-built wheels, and newer builds frequently drop support for older GPU compute capabilities.

Pinning your project to Python 3.11 or 3.12 before installing anything saves you from immediate dependency and wheel-resolution headaches:

uv python pin 3.11

For more uv tips and tricks see my post Rustification of Python - uv, ruff, ty - Automating Book Availability Checks

2. System CUDA?

Historically, getting TensorFlow to talk to an NVIDIA GPU on Linux meant installing a specific version of the system-wide CUDA Toolkit and cuDNN via apt, managing /usr/local/cuda symlinks. What a nightmare. I had to deal with this dependency version spaghetti for a long time.

Modern TensorFlow (2.14+ from Sep 2023) eliminates that entire headache by bundling the required NVIDIA CUDA and cuDNN runtime libraries directly inside Python wheels via the [and-cuda] extra. Because my NVIDIA driver (580.196.07) was already installed and working at the kernel level, I did not need to install any system-level CUDA Toolkit packages via apt.

You can see this in https://github.com/tensorflow/tensorflow/releases/tag/v2.14.0:

The tensorflow pip package has a new, optional installation method for Linux that installs necessary Nvidia CUDA libraries through pip. As long as the Nvidia driver is already installed on the system, you may now run pip install tensorflow[and-cuda] to install TensorFlow’s Nvidia CUDA library dependencies in the Python environment. Aside from the Nvidia driver, no other pre-existing Nvidia CUDA packages are necessary.

So, inside my project directory (already pinned to Python 3.11), I simply installed TensorFlow alongside ipykernel for Jupyter support:

uv add "tensorflow[and-cuda]" ipykernel

That updated my pyproject.toml to:

[project]
...
requires-python = ">=3.11"
dependencies = [
    "ipykernel>=7.4.0",
    "tensorflow[and-cuda]>=2.22.0",
]

Everything stays cleanly isolated inside the project’s .venv.

A Quick Caveat on Recent TensorFlow Versions and Pascal (6.1) GPUs

Notice that uv resolved tensorflow[and-cuda]>=2.22.0. Newer TensorFlow releases bundle CUDA 12/13 binaries that occasionally drop pre-compiled PTX/SASS kernels for older Pascal GPUs (Compute Capability 6.1).

If you run a real computation on an older GPU and hit a CUDA_ERROR_NO_BINARY_FOR_GPU or JIT compilation failed error, you can pin an earlier release like uv add "tensorflow[and-cuda]==2.17.1".
On my Quadro P2000, 2.22.0 compiled and ran without issue, once I resolved one uv-specific XLA quirk.

The uv / XLA Gotcha (libdevice Not Found)

Because uv installs NVIDIA’s CUDA compiler tools (nvidia-cuda-nvcc) inside your project’s .venv rather than /usr/local/cuda, TensorFlow’s XLA (Accelerated Linear Algebra) compiler sometimes fails to locate libdevice or ptxas at runtime.

To prevent libdevice not found errors during model compilation, you need to explicitly point XLA_FLAGS to the nvidia.cuda_nvcc package directory inside your virtual environment. It’s a “Duh” moment once you figure it out.

How to fix it in a script (.py file)

When running standalone Python scripts from the terminal, resolve the path dynamically in a subshell and pass it via XLA_FLAGS:

XLA_FLAGS=--xla_gpu_cuda_data_dir=$(uv run python -c "import os, nvidia.cuda_nvcc; print(list(nvidia.cuda_nvcc.__path__)[0])") uv run train.py

How to fix it inside a Python script or a Jupyter Notebook

If you set XLA_FLAGS directly inside Python before importing TensorFlow, there is a subtle trap to watch out for. My first instinct was to grab the directory using __file__:

import os
import nvidia.cuda_nvcc

nvcc_dir = os.path.dirname(nvidia.cuda_nvcc.__file__)

That threw a TypeError:

TypeError: expected str, bytes or os.PathLike object, not NoneType

Why? It turns out it’s because nvidia.cuda_nvcc is a PEP 420 namespace package (it has no __init__.py), which means __file__ evaluates to None.

Instead, inspect __path__ and grab the first entry before importing tensorflow:

import os
import nvidia.cuda_nvcc

# Point XLA to uv's bundled CUDA compiler (using __path__ for namespace packages)
nvcc_dir = list(nvidia.cuda_nvcc.__path__)[0]
os.environ["XLA_FLAGS"] = f"--xla_gpu_cuda_data_dir={nvcc_dir}"

import tensorflow as tf

And btw, here’s how to know if a package is a PEP 420 namespace package or not:

uv run --no-project --with nvidia-cuda-nvcc-cu12 python -c "import nvidia.cuda_nvcc as m; print(m.__file__, type(m.__path__))"

It returns:

None <class '_frozen_importlib_external._NamespacePath'>

Meaning that it is a PEP 420 Implicit Namespace Package.

Remember to clean up the cache later via uv cache prune.

What other potential results could we get from that check but with some other package?

  • /path/to/.../__init__.py <class 'list'> –> Standard Package (or legacy pkgutil/pkg_resources namespace)
  • /path/to/module.py + AttributeError: module has no attribute '__path__' –> Single-File Module
  • ModuleNotFoundError: No module named '...' –> Not Installed / Wrong Import Name

3. Running and Toggling CPU vs GPU

One of the first questions I had was how to handle and switch between CPU and GPU when using Tensorflow.

You do not need 2 separate installations.
Once tensorflow[and-cuda] is installed, TensorFlow automatically detects and defaults to your GPU whenever one is available.
If you want to force a script or notebook to ignore the GPU and run strictly on the CPU (for example, to compare execution speeds, debug a CUDA issue, or keep your 4GB VRAM free for another workload), you simply hide the GPU device using the CUDA_VISIBLE_DEVICES=-1 environment variable.

In CLI and Standalone .py Scripts

From the terminal, switching between GPU and CPU requires zero code changes. You just prefix your uv run command:

  • Run on GPU (default):
    uv run train.py
    
  • Force CPU-only execution:
    CUDA_VISIBLE_DEVICES=-1 uv run train.py
    

For a quick one-line sanity check from the terminal to verify that uv, TensorFlow, and your GPU are communicating:

uv run python -c "import tensorflow as tf; print('GPUs:', tf.config.list_physical_devices('GPU'))"

If everything is wired up properly, you will see:

GPUs: [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

In Jupyter and VSCode (with the Jupyter extension)

Working inside Jupyter notebooks introduces a few important differences compared to running .py files from the CLI.

Kernel Registration

  • If you launch JupyterLab or Jupyter Notebook from the terminal: Register your uv virtual environment once so Jupyter lists it as a selectable kernel:
    uv run python -m ipykernel install --user --name=my-uv-env --display-name "Python (uv-env)"
    
  • If you use VS Code’s Jupyter extension: VS Code automatically detects .venv directories created by uv. Just click “Select Kernel” → “Python Environments…” in the top-right corner of the notebook and pick your project’s .venv directly.

Toggling CPU vs. GPU Inside a Notebook

In a notebook, you don’t pass CLI environment flags per cell. Instead, you configure device visibility in the very first code cell before TensorFlow initializes the GPU:

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # Must be set BEFORE importing tensorflow

import tensorflow as tf
print("Active devices:", tf.config.list_physical_devices())

Here’s the ugly part: Kernel Restarts Are Mandatory. TensorFlow locks in hardware device discovery the very first time import tensorflow as tf runs in a Python process. If you already imported TensorFlow in a notebook session, adding or commenting out os.environ["CUDA_VISIBLE_DEVICES"] = "-1" will have zero effect until you click Restart on the Jupyter kernel.

Two Operational Habits for Small VRAM (4GB in my case) in VS Code

  1. Watch out for background notebook tabs: VS Code keeps a separate Python kernel process alive in the background for every open notebook tab. If you have two notebooks open and both initialize TensorFlow without dynamic memory growth enabled, the second notebook will immediately crash with an OOM error. Always Restart or Shutdown idle notebook kernels.
  2. Keep a live GPU dashboard open: Open a split terminal (in VS Code or outside) and run:
    watch -n 1 nvidia-smi
    

    Watching Memory-Usage, GPU-Util, and the bottom Processes table in real time makes it immediately obvious whether a cell is actually executing on the GPU or silently falling back to the CPU.
    Or maybe you already have a Grafana dashboard showing you live metrics for all the GPUs or all your machines.

4. Verification and Benchmarking

Simply running tf.config.list_physical_devices('GPU') only proves that TensorFlow sees your GPU.
It does not prove that TensorFlow can actually compile and execute CUDA kernels on older architectures like my Pascal (6.1).

To verify real execution and measure the speedup on my Quadro P2000, I ran a two-step benchmark multiplying two 5000 x 5000 random normal matrices while monitoring watch -n 1 nvidia-smi in a split terminal.

Baseline nvidia-smi State (Idle)

Before running any notebook cells, my Quadro P2000 had virtually all of its 4096 MiB available (only 4MiB used by Xorg):

+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 580.196.07             Driver Version: 580.196.07     CUDA Version: 13.0     |
+-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  Quadro P2000                   Off |   00000000:01:00.0 Off |                  N/A |
| N/A   45C    P8            N/A  / 5001W |       5MiB /   4096MiB |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+

+-----------------------------------------------------------------------------------------+
| Processes:                                                                              |
|  GPU   GI   CI              PID   Type   Process name                        GPU Memory |
|        ID   ID                                                               Usage      |
|=========================================================================================|
|    0   N/A  N/A            4412      G   /usr/lib/xorg/Xorg                        4MiB |
+-----------------------------------------------------------------------------------------+

Step 1: CPU Benchmark (CUDA_VISIBLE_DEVICES = “-1”)

In a clean Jupyter cell, I hid the GPU and timed the matrix multiplication on the CPU:

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # Hide GPU from TensorFlow

import time
import tensorflow as tf

print("Visible devices:", tf.config.list_physical_devices())

# Run a heavy matrix multiplication to test execution speed
start = time.time()
a = tf.random.normal([5000, 5000])
b = tf.random.normal([5000, 5000])
c = tf.matmul(a, b)
_ = c.numpy()  # Force computation to finish
# This previous line forces Python to wait until TensorFlow's asynchronous 
# background execution finishes computing c before stopping the timer.
# Calling .numpy() converts the tf.Tensor into a host-side NumPy array, 
# which requires the underlying C++ thread (or GPU stream) to block until 
# all pending calculations on c are complete.
# _ is a standard throwaway variable used to explicitly discard the returned 
# NumPy array so you don't keep an extra reference or print anything while 
# still triggering the method call.
print(f"CPU time: {time.time() - start:.3f} seconds")

Output:

...
Visible devices: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]
...
I0000 00:00:1796472294.605340   18927 cuda_diagnostics.cc:163] CUDA_VISIBLE_DEVICES is set to -1 - this hides all GPUs from CUDA
...
CPU time: 0.873 seconds

During this run, nvidia-smi stayed completely untouched at 5MiB.

Step 2: Restart Kernel and Run GPU Benchmark

After clicking Restart on the Jupyter kernel (top center of the notebook window in VSCode) to reset TensorFlow’s device state, I ran the same computation on the Quadro P2000, including a warm-up pass so first-time CUDA kernel compilation wouldn’t skew the timing:

import os
import time
import nvidia.cuda_nvcc

# Point XLA to uv's bundled CUDA compiler (using __path__ for namespace packages)
nvcc_dir = list(nvidia.cuda_nvcc.__path__)[0]
os.environ["XLA_FLAGS"] = f"--xla_gpu_cuda_data_dir={nvcc_dir}"

import tensorflow as tf

# Enable dynamic memory growth so TF doesn't hoard all 4GB
gpus = tf.config.list_physical_devices('GPU')
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu, True)

print("Visible devices:", tf.config.list_physical_devices())

# Warm-up run (compiles CUDA kernels for Pascal 6.1 on first run)
a = tf.random.normal([5000, 5000])
b = tf.random.normal([5000, 5000])
_ = tf.matmul(a, b).numpy()

# Timed GPU run
start = time.time()
c = tf.matmul(a, b)
_ = c.numpy()
print(f"GPU time: {time.time() - start:.3f} seconds")

Output:

Visible devices: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'), PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
I0000 00:00:1796487486.803186  176538 gpu_device.cc:2036] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3481 MB memory:  -> device: 0, name: Quadro P2000, pci bus id: 0000:01:00.0, compute capability: 6.1
GPU time: 0.230 seconds

Result: 0.230 seconds on GPU vs. 0.873 seconds on CPU. Nearly a 4x speedup right out of the gate on an older workstation card.

Meanwhile, nvidia-smi immediately reflected the active .venv/bin/python compute process (Type: C):

+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 580.196.07             Driver Version: 580.196.07     CUDA Version: 13.0     |
+-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  Quadro P2000                   Off |   00000000:01:00.0 Off |                  N/A |
| N/A   42C    P8            N/A  / 5001W |     579MiB /   4096MiB |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+

+-----------------------------------------------------------------------------------------+
| Processes:                                                                              |
|  GPU   GI   CI              PID   Type   Process name                        GPU Memory |
|        ID   ID                                                               Usage      |
|=========================================================================================|
|    0   N/A  N/A            4412      G   /usr/lib/xorg/Xorg                        4MiB |
|    0   N/A  N/A          176538      C   ...eep-Learning/.venv/bin/python        572MiB |
+-----------------------------------------------------------------------------------------+

:warning: Notice one interesting detail in that nvidia-smi output: even after the cell finished executing (GPU-Util: 0%), the Python process continued holding 572MiB of VRAM until I restarted the Jupyter kernel. That observation led into searching and digging to understand how TensorFlow manages VRAM under the hood.
Btw, this reminds me of a fully custom Linux daemon I created for my workplace a few years ago to monitor for machine usage and automatically turn it off if unused to save on cost on those CSP bills. It checks multiple things, and one of them is GPU. For GPU, it tracks GPU-Util (utilization.gpu) across a customizable time rolling window (let’s say 30min), and if it is at zero across all datapoints, then it concludes that GPU is unused. When all (session, cpu, mem, gpu) are unused, then it does a graceful shutdown.
You might say but what if there’s allocated memory and they did not save to disk? Well, first of all they all know that it exists (because I documented it in the part about how they request access, so they have to see it), and it is up to the user to output to disk. Leaving models or data sitting idle in volatile GPU memory overnight wastes money and blocks resources without doing useful work.
If all of this is completely over your head, don’t worry. I explain it down below in this post.

Copy-Pasteable Jupyter Notebook Boilerplate

For day-to-day work, here is the clean setup block I drop into the first cell of every deep learning notebook using Tensorflow:

import os
import nvidia.cuda_nvcc

# Fix XLA libdevice path for uv virtual environments
nvcc_dir = list(nvidia.cuda_nvcc.__path__)[0]
os.environ["XLA_FLAGS"] = f"--xla_gpu_cuda_data_dir={nvcc_dir}"

# Uncomment the line below ONLY if you want to force CPU mode:
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

import tensorflow as tf

# Prevent TensorFlow from grabbing all 4GB VRAM at once
for gpu in tf.config.list_physical_devices('GPU'):
    tf.config.experimental.set_memory_growth(gpu, True)

You can also add os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" above import tensorflow as tf if you want to quiet down the standard C++ informational logs.

5. VRAM

Seeing nvidia-smi stay parked at 572MiB after my benchmark cell finished, and even after running tf.keras.backend.clear_session() and gc.collect(), made me realize I needed a proper mental model for how GPU memory allocation actually works.

GPU memory is not a single bucket. When running TensorFlow on a local card, it helps to picture a three-layer stack (like a landlord, a warehouse manager, and boxes on shelves). Knowing which layer is full immediately tells me why something crashed and which lever fixes it.

Layer 1: The Landlord (The NVIDIA Driver and Physical VRAM)

At the bottom sits the physical 4096 MiB chip on my Quadro P2000, managed by the NVIDIA kernel driver (nvidia-smi).

  • How it works: The driver rents out slices of VRAM to individual OS processes (PIDs).
  • Strict Process Isolation (No Eviction): Once the driver assigns VRAM to Process A (my Jupyter kernel), Process B cannot forcibly evict Process A or steal its already-allocated memory.
  • What happens when a second GPU workload starts:
    • Strict GPU-only processes (e.g., a second TensorFlow notebook, a PyTorch script, or a CUDA renderer): When the new process asks the NVIDIA driver for more VRAM than what remains unallocated on the card, the driver rejects the request (CUDA_ERROR_OUT_OF_MEMORY), and the new process crashes while my original Jupyter kernel stays completely untouched.
    • Hybrid CPU/GPU engines (e.g., Ollama): Ollama queries how much free VRAM remains on the card (~3.4 GB in my case). If the LLM fits in the remaining space, both run side by side. If the model is larger than the remaining space, Ollama doesn’t crash or evict TensorFlow. It simply loads as many layers as fit into the remaining VRAM and offloads the rest onto system CPU/RAM (or falls back to 100% CPU if almost no VRAM is left).
  • Reclaiming memory at Layer 1: The NVIDIA driver only reclaims a process’s VRAM lease when the OS process (PID) exits completely, meaning restarting or shutting down the Jupyter kernel, or killing the PID. Don’t let those PIDs step out of line, or it’s kill -9.

Layer 2: The Tenant’s Private Warehouse (TensorFlow’s BFC Allocator)

Inside the VRAM rented by my Python process, TensorFlow sets up its own internal memory pool managed by its BFC (Best-Fit with Coalescing) Allocator.

  • Why it exists: Asking the NVIDIA driver (Layer 1) to allocate and free memory on every matrix multiplication is far too slow. Instead, TensorFlow acts like a warehouse manager that pre-allocates a pool of VRAM and sub-divides it internally.
  • With vs. Without set_memory_growth(True):
    • Default (False): TensorFlow immediately reserves almost the entire available card (~3.5 GB out of 4 GB) on startup, even if I am only multiplying two tiny tensors.
    • Enabled (True): TensorFlow starts with a small pool (572 MiB in my test, which includes ~200–300 MiB of base CUDA Context overhead) and only requests additional VRAM from the NVIDIA driver when its internal warehouse fills up.
  • It is a One-Way Ratchet: Unlike PyTorch (which exposes torch.cuda.empty_cache()), TensorFlow intentionally does not release empty BFC pool blocks back to the NVIDIA driver while the Python process is alive. nvidia-smi always displays TensorFlow’s high-water mark, even when the warehouse is completely empty inside.

But is there a way to hard release VRAM without restarting the main process?

If I ever run a standalone .py script (or a long-lived notebook) where I need to run a heavy TensorFlow step and immediately hand all 4GB back to the OS without killing my main Python process, I can isolate the TensorFlow work inside a short-lived multiprocessing child process:

import multiprocessing as mp

def train_on_gpu():
    import tensorflow as tf
    # TensorFlow initializes GPU, trains, and saves artifacts to disk.
    # When this function exits, the child PID terminates and nvidia-smi drops back to 5MiB.

p = mp.Process(target=train_on_gpu)
p.start()
p.join()

Once p.join() completes, the child process dies, the NVIDIA driver reclaims the entire VRAM lease, and my main process keeps running with its state intact.

It works because the child process is a separate process with its own unique PID.

Layer 3: The Boxes Inside the Warehouse (Python Variables and Keras Graphs)

At the top layer sit my actual tensors (a, b, c), model weights, and temporary training math, all stored as “boxes” on the shelves inside TensorFlow’s Layer 2 warehouse.

To inspect what is actually sitting inside Layer 2 (rather than looking at the Layer 1 high-water mark in nvidia-smi), I can query TensorFlow’s internal memory counter directly:

import tensorflow as tf

info = tf.config.experimental.get_memory_info('GPU:0')
print(f"Current in-use: {info['current'] / 1024**2:.1f} MiB")
print(f"Peak used:      {info['peak'] / 1024**2:.1f} MiB")

After running my 5000 x 5000 matrix multiplication benchmark, that printed:

Current in-use: 384.0 MiB
Peak used:      512.0 MiB

For the curious: the math behind 384.0 MiB: each 5000 x 5000 float32 tensor takes 5000 × 5000 × 4 bytes = 100,000,000 bytes (~95.4 MiB, padded by the BFC allocator to 128 MiB power-of-two blocks). Three live matrices (a, b, and c) equal 3 × 128 MiB = 384.0 MiB.

Why clear_session() alone didn’t drop 384.0 MiB?

When I ran tf.keras.backend.clear_session() followed by gc.collect() right after the benchmark, Current in-use stayed at 384.0 MiB.

The reason is simple: clear_session() destroys internal Keras models, layers, and computation graphs, but it does not touch standard Python variables (a, b, c) that are still bound in my notebook’s global scope. Until I explicitly delete those variable references, Python keeps them alive on Layer 3’s shelves:

del a, b, c
tf.keras.backend.clear_session()
gc.collect()

:warning: Once I delete the variable references and clear the Keras session, Layer 3 empties completely (0.0 MiB), allowing the next model or experiment in my notebook to reuse Layer 2’s existing 572 MiB pool without forcing Layer 2 to ask the NVIDIA driver for even more VRAM.
This is very important to understand.
If you are constrained by hardware (small VRAM like in my laptop) or care about cost (in a cloud), you need to do some VRAM management if using Tensorflow. :warning:

6. Adapting to my 4GB VRAM GPU

Once we move from simple matrix multiplications to training real deep learning models (such as Convolutional Neural Networks, transfer learning backbones, or NLP models), we will eventually run into ResourceExhaustedError: OOM when allocating tensor.

During training (model.fit()), VRAM isn’t just holding the model’s static weights. It has to hold the intermediate math (activations and gradients) for every single item in a batch simultaneously. On a 4GB Quadro P2000, keeping those transient Layer 3 memory spikes under control comes down to five practical levers.

  1. Lower the batch_size
    • Why it works: Courses and tutorials routinely default to batch_size=32, 64, or 128 because they run on cloud GPUs with 16GB-80GB of VRAM. Cutting batch_size in half (32 → 16 → 8) immediately cuts activation memory per step in half without changing the model architecture.
    • The trade-off: Epochs take slightly longer to finish and gradient updates are slightly noisier, which is a worthwhile trade to keep training on the GPU.
  2. Clear Variables and Sessions Between Experiments
    • Why it works: In a Jupyter notebook, tweaking hyperparameters and re-running model = Sequential(...) multiple times in the same kernel leaves old model weights and computation graphs sitting on Layer 3’s shelves, forcing TensorFlow’s BFC allocator to request more VRAM from the driver until it hits the 4GB ceiling.
    • What to run before defining a new model:
     import gc
     import tensorflow as tf
    
     del model  # Remove the Python reference first
     tf.keras.backend.clear_session()
     gc.collect()
    
  3. Shrink Input Image Resolution (Computer Vision)
    • Why it works: Image memory scales quadratically with height and width. A 224x224 RGB image consumes 4x more VRAM per batch than a 112x112 image.
    • What to do: If lowering batch_size isn’t enough on high-resolution datasets (256x256 or 299x299), resize inputs down to 128x128 or 160x160 in the data loader (target_size=(128, 128) or image_size=(128, 128)).
  4. Pick Lightweight Pre-trained Backbones (Transfer Learning)
    • Why it works: Heavy classic architectures like VGG16 or ResNet152 carry a large parameter and activation footprint.
    • What to do: Swap in edge-friendly architectures like MobileNetV2, MobileNetV3Small, or EfficientNetB0. They train significantly faster on a Quadro P2000, consume a fraction of the VRAM, and deliver comparable accuracy on standard tutorial datasets.
  5. Watch Out for Mixed Precision (mixed_float16) on Pascal (6.1)
    You will often see advice to enable mixed precision (mixed_float16) to cut VRAM usage nearly in half by storing activations in 16-bit floats instead of 32-bit floats.
    • The Hardware Caveat: The Quadro P2000 uses NVIDIA’s Pascal architecture (Compute Capability 6.1), which lacks dedicated Tensor Cores (introduced in Volta/Turing 7.0+).
    • What this means in practice: While mixed_float16 can still reduce memory footprint on a P2000, it will not accelerate training speed, and can occasionally run slower or introduce numerical instability (NaN loss). Stick to standard float32 by default, and treat mixed_float16 as a last resort rather than a free performance boost.

Troubleshooting Cheat Sheet

Whenever something goes wrong with GPU memory during development, map the symptom back to the 3-layer mental model:

Symptom Which Layer Failed Fix
Immediate crash at startup before training starts Layer 1 (NVIDIA Driver): Another process (another notebook tab, Ollama, Xorg) is already holding the VRAM lease. Shutdown/restart other Jupyter kernels or run ollama stop <model>.
OOM crash on model.fit() Step 1 Layer 3 → Layer 2 → Layer 1: A single batch’s activations and gradients exceed the 4GB physical card. Lower batch_size (32 → 16 → 8), reduce image_size, or switch to MobileNetV2 / EfficientNetB0.
Run 1 succeeds, Run 2 crashes in the same notebook Layer 3 (Cluttered Shelves): Previous model objects remained alive in memory, forcing Layer 2 to expand past 4GB. Run del model, tf.keras.backend.clear_session(), and gc.collect() between runs.
Notebook finished, nvidia-smi still shows VRAM reserved Layer 2 (BFC Ratchet): Layer 3 shelves are empty, but TensorFlow is still holding its internal pool lease. Restart/shutdown the Jupyter kernel (or isolate GPU runs in a multiprocessing child process).
Model simply cannot fit in 4GB no matter what Hardware Ceiling: Architecture + minimum batch exceeds 4GB VRAM. Set os.environ["CUDA_VISIBLE_DEVICES"] = "-1", restart the kernel, and run on CPU + system RAM.

And now, you know how to operate your own GPU (locally or in the cloud), when using Tensorflow, without having to rely on some overpriced and mysterious service that abstracts all this stuff away from you.
Behold, the power of knowledge! You’re playing with the big [AI Infra] boys now. :wink: