Posted on

使用GPU跑tensorflow的除錯流程

最簡單的範例

這邊的程式碼是官網教學裡的一個簡單範例:
https://www.tensorflow.org/tutorials/keras/classification?hl=zh-tw

# TensorFlow and tf.keras
import tensorflow as tf

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)
fashion_mnist = tf.keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

train_images_tensor = tf.convert_to_tensor(train_images, dtype=tf.float32)
train_labels_tensor = tf.convert_to_tensor(train_labels, dtype=tf.int64)

# Create a dataset from tensors
train_ds = tf.data.Dataset.from_tensor_slices((train_images_tensor, train_labels_tensor))

AUTOTUNE = tf.data.AUTOTUNE

def configure_for_performance(ds):
    ds = ds.cache()
    ds = ds.shuffle(buffer_size=1000)
    ds = ds.batch(32)
    ds = ds.prefetch(buffer_size=AUTOTUNE)
    return ds


train_ds = configure_for_performance(train_ds)

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
import time
timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
print(timestamp)
model.fit(
    train_ds,
    epochs=5, batch_size=32
)
timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
print(timestamp)
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print('\nTest accuracy:', test_acc)

# 作出預測
probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print(predictions[0], test_labels[0])

使用GPU建模

經過了前三章的教學之後,應該已經設定好了Tensorflow的GPU環境
1. 在python裡面使用GPU 1 – 選擇適合的GPU
2. 在python裡面使用GPU 2 – 安裝正確的套件
3. 在python裡面使用GPU 3 – 開發GPU程式
接著就要嘗試使用GPU來建模,並評估和原本的效能有多大差異,現在就可以將上面的程式碼COPY下來,然後在有GPU的環境嚇跑看看

TensorFlow版本過舊的錯誤

AttributeError: module 'tensorflow.python.util.dispatch' has no attribute 'add_fallback_dispatch_list'

這個錯誤通常是因為您正在使用舊版本的 TensorFlow,而該版本中沒有 dispatch 模塊的 add_fallback_dispatch_list 屬性。

要解決此問題,建議您更新 TensorFlow 到最新版本。您可以使用 pip 升級 TensorFlow:

pip install --upgrade tensorflow

如果正在使用 GPU 版本的 TensorFlow,請使用 tensorflow-gpu 套件升級:

pip install --upgrade tensorflow-gpu

CUDA版本過舊

2023-01-03 14:34:18.036663: W tensorflow/stream_executor/gpu/asm_compiler.cc:111] *** WARNING *** You are using ptxas 11.0.194, which is older than 11.1. ptxas before 11.1 is known to miscompile XLA code, leading to
incorrect results or invalid-address errors.

You may not need to update to CUDA 11.1; cherry-picking the ptxas binary is often sufficient.
這個警告指出正在使用舊版本的 ptxas 編譯器,並表示它可能會導致 XLA 代碼的錯誤編譯,產生不正確的結果或無效地址錯誤。

要解決此問題,建議更新 ptxas 編譯器到最新版本。升級到 CUDA 11.1,或者選擇性地選擇更新 ptxas 編譯器。

可以在 NVIDIA 網站上下載最新版本的 CUDA Toolkit:
https://developer.nvidia.com/cuda-toolkit

zlibwapi.dll找不到

Could not locate zlibwapi.dll. Please make sure it is in your library path!

這個錯誤指出找不到 zlibwapi.dll 文件。這通常是因為您的系統中沒有安裝 zlib 庫。

要解決此問題,建議您安裝 zlib 庫。您可以在此頁面下載 zlib 庫:
https://www.zlib.net/

下載並安裝 zlib 庫後,請將 zlibwapi.dll 文件放在您的系統路徑中。通常,您可以將 zlibwapi.dll 文件放在 C:\Windows\System32 目錄中。

zlibwapi.dll版本錯誤

Could not load library zlibwapi.dll. Error code 193. Please verify that the library is built correctly for your processor architecture (32-bit, 64-bit)

這個錯誤指出無法載入 zlibwapi.dll 文件,並提示錯誤代碼 193。通常是因為您的系統和 zlibwapi.dll 文件的類型不匹配,例如您的系統是 64 位,而 zlibwapi.dll 文件是 32 位。
請參考此文章:https://blog.csdn.net/qq_45071353/article/details/124091856
最後我改下載x64的zlib(下載點)

成功使用GPU跑TF的訊息

2023-01-03 17:05:21.826122: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1616]
Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3971 MB memory:  ->
device: 0, name: NVIDIA GeForce GTX 1660 Ti, pci bus id: 0000:01:00.0, compute capability: 7.5