Apple M2 Ultra环境下R中TensorFlow与Keras无法调用GPU求助
TensorFlow/Keras在R环境中无法调用Apple M2 Ultra GPU及模型构建失败的解决方案
问题描述
在R环境中使用TensorFlow和Keras,已完成官方指南中的CPU和GPU版本安装。执行GPU检测代码:
library(tensorflow) tf$config$list_physical_devices("GPU")
返回空列表list(),说明TensorFlow未识别到GPU。
尝试构建MNIST模型时,日志显示已识别到Apple M2 Ultra,但标注GPU内存为0MB,且模型最终无法构建:
library(tensorflow) library(keras) mnist <- dataset_mnist() train_images <- mnist$train$x train_labels <- mnist$train$y test_images <- mnist$test$x test_labels <- mnist$test$y model <- keras_model_sequential(list( layer_dense(units = 512, activation = "relu"), layer_dense(units = 10, activation = "softmax") ))
日志输出:
2024-04-09 11:48:51.673016: I metal_plugin/src/device/metal_device.cc:1154] Metal device set to: Apple M2 Ultra 2024-04-09 11:48:51.673043: I metal_plugin/src/device/metal_device.cc:296] systemMemory: 192.00 GB 2024-04-09 11:48:51.673051: I metal_plugin/src/device/metal_device.cc:313] maxCacheSize: 72.00 GB 2024-04-09 11:48:51.673095: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:306] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support. 2024-04-09 11:48:51.673134: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:272] 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>)
解决方案
1. 确保TensorFlow版本支持Metal
Apple Silicon设备需要使用TensorFlow 2.15及以上版本,在R中检查当前版本:
tf_version()
若版本过低,重新安装适配版本:
install_tensorflow(version = "2.15", extra_packages = "tensorflow-metal")
2. 配置Metal环境变量
在R会话启动前设置环境变量,启用Metal加速:
Sys.setenv(TENSORFLOW_METAL="1") # 启用GPU内存动态增长 gpu_devices <- tf$config$list_physical_devices("GPU") if(length(gpu_devices) > 0) { tf$config$experimental$set_memory_growth(gpu_devices[[1]], TRUE) }
可将TENSORFLOW_METAL="1"添加到.Renviron文件中,实现永久生效。
3. 修复模型输入预处理问题
模型构建失败的核心原因是MNIST图像为二维数组(28x28),而Dense层需要一维输入,需先展平并归一化数据:
library(tensorflow) library(keras) # 启用Metal加速 Sys.setenv(TENSORFLOW_METAL="1") gpu_devices <- tf$config$list_physical_devices("GPU") if(length(gpu_devices) > 0) { tf$config$experimental$set_memory_growth(gpu_devices[[1]], TRUE) } # 加载并预处理MNIST数据 mnist <- dataset_mnist() train_images <- array_reshape(mnist$train$x, c(60000, 28*28)) / 255 train_labels <- mnist$train$y test_images <- array_reshape(mnist$test$x, c(10000, 28*28)) / 255 test_labels <- mnist$test$y # 构建并编译模型 model <- keras_model_sequential(list( layer_dense(units = 512, activation = "relu", input_shape = c(28*28)), layer_dense(units = 10, activation = "softmax") )) model %>% compile( optimizer = "rmsprop", loss = "sparse_categorical_crossentropy", metrics = c("accuracy") ) # 验证GPU识别 print(tf$config$list_logical_devices("GPU"))
4. 关于0MB内存日志的说明
日志中显示的0 MB memory是TensorFlow Metal插件的已知显示问题,不影响GPU实际内存分配和使用,更新到最新版TensorFlow可改善该显示,但不影响功能。
内容的提问来源于stack exchange,提问作者Lennon Lee
相关产品推荐
相关产品推荐

