Python 3.6导入TensorFlow时出现Illegal instruction:4错误求助
Hey there, let's tackle this Illegal instruction: 4 error you're hitting when importing TensorFlow 1.6.0 in your macOS virtualenv. I've run into this exact issue before, and it's almost always linked to CPU instruction set compatibility.
Why This Happens
Starting with TensorFlow 1.6, the official precompiled packages default to using AVX/AVX2 instruction sets—these are advanced CPU features that speed up tensor operations. If your Mac's CPU doesn't support these (common in older models like Core 2 Duo, early Core i-series, or low-end Intel chips), Python will crash with that "Illegal instruction" error when it tries to load code that uses unsupported instructions.
Solutions to Try
1. Roll Back to a TensorFlow Version Without AVX Requirements
The easiest fix is to install an older TensorFlow version that doesn't enforce AVX support. TensorFlow 1.5.0 and earlier are compiled to work on most older Mac CPUs. Here's how:
- First, uninstall your current TensorFlow and the
sixdependency (to avoid version conflicts):pip3 uninstall -y tensorflow six - Install TensorFlow 1.5.0:
pip3 install tensorflow==1.5.0 - Activate your virtualenv and test it:
python3 -c "import tensorflow as tf; print('Success! TensorFlow version:', tf.__version__)"
2. Compile TensorFlow 1.6.0 From Source (For Advanced Users)
If you specifically need TensorFlow 1.6.0, you can compile it from source and disable AVX instructions. Here's a simplified breakdown:
- Install prerequisites: Xcode (with command-line tools), Bazel 0.10.0 (the compatible version for TensorFlow 1.6—newer Bazel versions won't work).
- Clone the TensorFlow repo and check out the 1.6.0 tag:
git clone https://github.com/tensorflow/tensorflow.git cd tensorflow git checkout v1.6.0 - Run the configure script:
When asked about CPU instruction sets, answer "no" to enabling AVX, AVX2, and any other advanced features your CPU doesn't support../configure - Compile the package with Bazel:
bazel build --config=opt --copt=-mno-avx --copt=-mno-avx2 //tensorflow/tools/pip_package:build_pip_package - Generate the whl file and install it:
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg pip3 install /tmp/tensorflow_pkg/tensorflow-1.6.0*.whl
3. Verify Your CPU's Instruction Set
To confirm if AVX is the issue, run this command in your terminal to check your CPU's supported features:
sysctl -n machdep.cpu.features
If you don't see AVX or AVX2 in the output, that confirms your CPU can't run the precompiled TensorFlow 1.6.0 package.
Give these steps a shot—rolling back to 1.5.0 usually fixes this instantly. If you get stuck with compiling from source, feel free to ask for more details!
内容的提问来源于stack exchange,提问作者Jules

