To compile TensorFlow for CPU-only execution, follow these methods:
1. Install Pre-Built CPU-Optimized Packages
Use pip to install the CPU-only version directly:
pip install tensorflow-cpu # For Python 3.x
pip install tensorflow # For Python 2.x (legacy)
This avoids GPU dependencies entirely[1][5][6].
2. Force CPU Usage via Environment Variables
Even with GPU-enabled TensorFlow installed, set:
export CUDA_VISIBLE_DEVICES="" # Linux/Mac
set CUDA_VISIBLE_DEVICES="" # Windows
Then run your Python script. TensorFlow will ignore GPUs[2][4][7].
3. Build TensorFlow from Source with CPU Optimizations
For maximum performance, compile with CPU-specific flags:
# Clone TensorFlow source
git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow
# Configure build (select CPU-only)
./configure # Answer "N" to GPU questions
# Build with CPU optimizations (e.g., AVX2, FMA)
bazel build --config=mkl -c opt --copt=-march=native //tensorflow/tools/pip_package:build_pip_package
# Install
bazel-bin/tensorflow/tools/pip_package/build_pip_package ./
pip install tensorflow-*.whl
Replace -march=native with flags like -mavx2 -mfma if needed[3][9][13].
4. Verify CPU Usage
Run a test to confirm CPU-only execution:
import tensorflow as tf
print(tf.reduce_sum(tf.random.normal([1000, 1000])))
Look for logs like:
This TensorFlow binary is optimized to use available CPU instructions...
Avoid GPU-related warnings[1][3][7].
Key Considerations
| Method | Pros | Cons |
|---|
| Pre-built CPU package | Simple, no compilation | Limited to pre-optimized binaries |
| Environment variables | No reinstallation needed | Requires GPU TensorFlow installed |
| Source build | Max CPU optimization | Complex setup, requires Bazel |
For most users, installing tensorflow-cpu via pip is the simplest solution[1][5][6]. Advanced users can build from source to leverage specific CPU instructions like AVX2 or AVX512[3][9][13].