Ik ben bezig met een opleiding rond AI. In het tweede deel van de opleiding gaat het over Deep Learning. En hiervoor gaan we met Tensorflow 2 werken.
Ik heb een MacBook Pro 16″, 2019. Met een i7 2.6 GHz CPU, 16GB RAM en een AMD Radeon Pro 5300M 4GB. Dus helaas geen optimaal toestel. Want geen M1, M2, M3 CPU of geen NVIDIA GPU.
Ik wou dus vergelijken wat de beste manier is. Daarom heb ik het op verschillende manieren geprobeerd met hetzelfde script:
import tensorflow as tf
import time
devices = tf.config.list_physical_devices() print("\nDevices: ", devices)
gpus = tf.config.list_physical_devices('GPU')
if gpus:
details = tf.config.experimental.get_device_details(gpus[0])
print("GPU details: ", details) start_time = time.time()
cifar = tf.keras.datasets.cifar100
(x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50(
include_top=True,
weights=None,
input_shape=(32, 32, 3),
classes=100,
)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"])
model.fit(x_train, y_train, epochs=1, batch_size=64) end_time = time.time()
print(f'Duration: {end_time - start_time} seconds')
Ik heb steeds python 3.10 gebruikt.
Tensorflow
pip3.10 install tensorflow
Het resultaat:
> This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
> To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
Devices: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]
782/782 [==============================] - 1297s 2s/step - loss: 4.4852 - accuracy: 0.0869
Duration: 1299.4248449802399 seconds
Dus een dikke 00:21:39.
Tensorflow-metal
Zie ook https://developer.apple.com/metal/tensorflow-plugin/.
pip3.10 install tensorflow==2.12
pip3.10 install tensorflow-metal==0.8.0
pip3.10 install tensorflow-macos
Ik kreeg wel een error:
> Non-OK-status: stream_executor::MultiPlatformManager::RegisterPlatform( std::move(cplatform)) status: Internal: platform is already registered with name: "METAL"
Die heb ik opgelost door /usr/local/lib/python3.10/site-packages/tensorflow/__init__.py te openen. En onderstaande (rond lijn 419) te vervangen:
_site_packages_dirs = list(set(_site_packages_dirs))
Door:
from pathlib import Path
_site_packages_dirs = {Path(p).resolve() for p in _site_packages_dirs}
_site_packages_dirs = [str(p) for p in _site_packages_dirs]
Bron: https://stackoverflow.com/a/76560686
Het resultaat:
> This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
> To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
Devices: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'), PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
GPU details: {'device_name': 'METAL'}
> Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
> Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
Metal device set to: AMD Radeon Pro 5300M
systemMemory: 16.00 GB
maxCacheSize: 1.99 GB
> Plugin optimizer for device_type GPU is enabled.
782/782 [==============================] - 1214s 1s/step - loss: 4.5082 - accuracy: 0.0889
Duration: 1216.873417854309 seconds
Dus een dikke 00:20:16.
Geen extreme verbetering dus. Maar er werd wel gebruik gemaakt van de GPU.
Google Cloud
Een iets complexere setup. Maar wel snel:
> This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
> To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
Devices: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'), PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
> Created device /job:localhost/replica:0/task:0/device:GPU:0 with 13775 MB memory: -> device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5
782/782 [==============================] - 72s 47ms/step - loss: 4.6311 - accuracy: 0.0829
Duration: 102.1021716594696 seconds
Dus 00:01:42.
Een extreem verschil!
Dit heeft natuurlijk wel wat meer voeten in de aarde.
VM instance
Ik heb een machine aangemaakt door de stappen te volgen op Create a TensorFlow Deep Learning VM instance. Ik koos voor 1 NVIDIA T4 GPU.
Als je die 7/7 laat aan staan dan is dat een stevige kost. Maar voor mij is het voldoende om die enkel aan te zetten als ik met mijn opdrachten bezig ben. Dus op zich valt de kost mee.
Nadien heb ik op mijn computer via gcloud compute config-ssh de ssh config aangepast zodat ik vlot kan SSH’en naar de instance.
Let op: als je de server stop/start krijg je soms een ander IP adres. Dus kan zijn dat je deze stap soms opnieuw moet doen.
PyCharm
Ik werk zelf in PyCharm. En ik wil natuurlijk niet elke keer via SFTP files zitten uploaden. Daarnaast zijn de opdrachten ook steeds gedaan in Jupyter Notebooks. Dus ik wil dat ook vlot kunnen gebruiken. Om dat werkend te krijgen heb ik de volgende stappen gedaan:
SSH Configuration toevoegen
- Open de Settings van PyCharm
- Ga naar Tools → SSH Configurations
- Voeg een configuratie toe:
- Host: de host uit je SSH config
- Port: 22
- Username: jouw username
- Authentication type: OpenSSH config en authentication agent
Dit hoef je maar eenmalig te doen.
Python Interpreter toevoegen
- Open de Project Settings
- Ga naar Python Interpreter
- Voeg een Interpreter toe. Kies voor “On SSH”
- SSH Connection: Existing
- SSH Server: Jouw SSH Configuration
- Virtualenv Environment:
- Environment: New
- Location: /home/XXX/.virtualenvs/deep_learning
- Base interpreter: /opt/conda/bin/python3
- Inherit global site-packages: aanvinken
- Sync folders: <project root> → /home/XXX/deep_learning
- System Interpreter:
- Interpreter: /opt/conda/bin/python3
- Sync folders: <project root> → /home/XXX/deep_learning
In het project selecteer je dan deze interpreter (onderaan rechts). Dit zal even duren. Want PyCharm gaat dan de interpreter indexeren.
Dit hoef je maar eenmalig te doen.
CSV files uploaden
De opdrachten maken gebruik van CSV files, die worden standaard niet geüpload.
- Open de Settings van PyCharm
- Ga naar Build, Execution, Deployment → Deployment → Options
- Bij Exclude items by name haal je
;*.csvweg
Dit hoef je maar eenmalig te doen.
Jupyter Notebook Server
De demo’s en opdrachten van de opleiding zijn opgesteld in Jupyter Notebooks. Om die dus te kunnen draaien in PyCharm heb je een Jupyter Notebook Server nodig:
cd deep_learning
pip3.10 install jupyter
Deze stap hoef je maar 1 keer te doen.
Jupyter Notebook in PyCharm
Om de Jupyter Notebook Server beschikbaar te maken op mijn computer heb ik een SSH tunnel opgezet:
gcloud compute ssh --zone "europe-west1-b" "NAME-OF-THE-SERVER" --project "YYY" --ssh-flag="-L 8888:localhost:8888
Nadien inloggen op de server via SSH en de Jupyter Notebook Server starten:
cd ~/deep_learning; JUPYTER_TOKEN=SUPER-SECRET-TOKEN jupyter notebook
Nadien kan je hiermee verbinden als je in PyCharm een Jupyter Notebook opent en een code-cell uitvoert. Je moet dan de token ingeven.
Nuttige links
Links die ik gebruikt heb om alles werkend te krijgen.
- https://gidutz.medium.com/remote-development-with-pycharm-and-google-cloud-1a8bdab3433f
- https://theiconic.tech/set-up-a-cloud-gpu-enabled-virtual-machine-for-the-tensorflow-certificate-exam-760284deefa4
- https://stackoverflow.com/questions/48963665/how-to-use-pycharm-with-google-compute-engine
- https://www.jetbrains.com/help/pycharm/configuring-remote-interpreters-via-ssh.html