MacBook Pro M1运行tensorflow-metal代码触发NSInvalidArgumentException错误
M1 MacBook 运行TensorFlow报MPSGraph Adam接口错误解决方案
错误根因
该报错是TensorFlow版本、tensorflow-metal插件版本与本地macOS系统的MPS图形框架版本不兼容导致:你当前使用的tensorflow-metal版本调用了adamUpdateWithLearningRateTensor接口,该接口是macOS 12.3及以上版本的MPS框架才新增的API,低版本系统缺少对应实现就会抛出unrecognized selector异常。
解决方法
- 方案1:适配版本(推荐,保留GPU加速+Adam优化器)
二选一即可:- 升级系统到macOS Monterey 12.3或更高版本,同步升级tensorflow-macos到2.9+、tensorflow-metal到0.5.0+
- 若不想升级系统,降级依赖到对应兼容版本:
pip install tensorflow-macos==2.7 tensorflow-metal==0.3.0
- 方案2:更换优化器(临时快速解决)
将代码中model.compile里的优化器参数从optimizer='adam'替换为其他低版本MPS支持的优化器,例如:
调整后即可正常运行,缺点是SGD收敛速度略慢于Adam。optimizer='sgd' - 方案3:强制禁用GPU(应急用,不推荐)
在训练代码前添加以下行,强制TensorFlow使用CPU运行,避开GPU接口冲突:tf.config.set_visible_devices([], 'GPU')
内容的提问来源于stack exchange,提问作者Small_J
相关产品推荐
相关产品推荐

