调用keras.Sequential.predict时Python无报错崩溃,退出码异常
问题现象
运行基于TensorFlow的GAN代码时,Python无报错直接崩溃,仅输出以下日志:
2022-07-16 09:11:13.307094: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-07-16 09:11:13.832861: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 1342 MB memory: -> device: 0, name: NVIDIA GeForce MX330, pci bus id: 0000:02:00.0, compute capability: 6.1
2022-07-16 09:11:13.911731: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar todataset.cache().take(k).repeat(). You should usedataset.take(k).cache().repeat()instead.
Process finished with exit code -1073740791 (0xC0000409)
代码如下:
# Bringing in tensorflow import tensorflow as tf # Brining in tensorflow datasets for fashion mnist import tensorflow_datasets as tfds # Bringing in matplotlib for viz stuff from matplotlib import pyplot as plt # Do some data transformation import numpy as np # Bring in the sequential api for the generator and discriminator from keras import Sequential # Bring in the layers for the neural network from keras.layers import Conv2D, Dense, Flatten, Reshape, LeakyReLU, Dropout, UpSampling2D # Scale and return images only def scale_images(data): image = data['image'] return image / 255 def build_generator(): model = Sequential() # Takes in random values and reshapes it to 7x7x128 # Beginnings of a generated image model.add(Dense(7 * 7 * 128, input_dim=128)) model.add(LeakyReLU(0.2)) model.add(Reshape((7, 7, 128))) # Upsampling block 1 model.add(UpSampling2D()) model.add(Conv2D(128, 5, padding='same')) model.add(LeakyReLU(0.2)) # Upsampling block 2 model.add(UpSampling2D()) model.add(Conv2D(128, 5, padding='same')) model.add(LeakyReLU(0.2)) # Convolutional block 1 model.add(Conv2D(128, 4, padding='same')) model.add(LeakyReLU(0.2)) # Convolutional block 2 model.add(Conv2D(128, 4, padding='same')) model.add(LeakyReLU(0.2)) # Conv layer to get to one channel model.add(Conv2D(1, 4, padding='same', activation='sigmoid')) return model gpus = tf.config.experimental.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) # Use the tensorflow datasets api to bring in the data source ds = tfds.load('fashion_mnist', split='train') var = ds.as_numpy_iterator().next()['label'] # Setup connection aka iterator data_iterator = ds.as_numpy_iterator() # Getting data out of the pipeline var2 = data_iterator.next()['image'] # Setup the subplot formatting fig, ax = plt.subplots(ncols=4, figsize=(20, 20)) # Loop four times and get images for idx in range(4): # Grab an image and label sample = data_iterator.next() # Plot the image using a specific subplot ax[idx].imshow(np.squeeze(sample['image'])) # Appending the image label as the plot title ax[idx].title.set_text(sample['label']) # plt.show() # Reload the dataset ds = tfds.load('fashion_mnist', split='train') # Running the dataset through the scale_images preprocessing step ds = ds.map(scale_images) # Cache the dataset for that batch ds = ds.cache() # Shuffle it up ds = ds.shuffle(60000) # Batch into 128 images per sample ds = ds.batch(128) # Reduces the likelihood of bottlenecking ds = ds.prefetch(64) generator = build_generator() # Generate new fashion img = generator.predict(np.random.randn(4, 128, 1)) # crash happens here
教程评论区有用户在同一行遇到类似错误:
UnimplementedError: Graph execution error: Node: 'sequential/conv2d/Conv2D' DNN library is not found. [[{{node sequential/conv2d/Conv2D}}]] [Op:__inference_predict_function_140492]
使用NVIDIA GeForce MX330显卡(仅2GB显存),调整生成器参数后问题仍存在;已手动安装CUDA和cudNN,无CUDA相关警告;尝试不同脚本均在调用predict或类似步骤时崩溃。后续从命令行启动程序时发现关键错误:
Could not locate zlibwapi.dll. Please make sure it is in your library path!
解决方法
1. 修复zlibwapi.dll缺失问题
- 从NVIDIA官方CUDA工具包安装路径中提取
zlibwapi.dll(通常位于C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vX.X\bin,X.X为CUDA版本号) - 将该文件复制到以下任意位置:
- 系统目录(如
C:\Windows\System32) - Python环境的
Lib/site-packages/tensorflow目录 - 添加该文件所在路径到系统环境变量
PATH中
- 系统目录(如
2. 优化显存占用(适配低显存显卡)
- 减少模型通道数:将生成器中所有
128通道数改为64或32,例如:def build_generator(): model = Sequential() model.add(Dense(7 * 7 * 64, input_dim=128)) model.add(LeakyReLU(0.2)) model.add(Reshape((7, 7, 64))) model.add(UpSampling2D()) model.add(Conv2D(64, 5, padding='same')) model.add(LeakyReLU(0.2)) # 后续Conv2D层同理修改通道数 - 减小Batch Size:将
ds.batch(128)改为ds.batch(32)或ds.batch(16) - 强制使用CPU运行:若显存仍不足,在代码开头添加:
tf.config.set_visible_devices([], 'GPU')
3. 验证CUDA环境完整性
- 确认TensorFlow版本与CUDA版本匹配(如TensorFlow 2.10+对应CUDA 11.2+)
- 确认cudNN版本与CUDA版本兼容,并已正确放置到CUDA安装目录的
include和lib/x64文件夹中
内容的提问来源于stack exchange,提问作者stefanp99

