动手学深度学习d2l包M4芯片 gpu加速

conda创建环境

bash 复制代码
CONDA_SUBDIR=osx-arm64 conda create -n ml python=3.9 -c conda-forge
conda env config vars set CONDA_SUBDIR=osx-arm64
conda activate ml

pip安装包

bash 复制代码
pip install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu
pip install transformers datasets
pip install matplotlib

下载del源文件

del链接

放到本地项目内

修改del下的torch.py的两个函数内容

python 复制代码
# 修改try gpu函数
def try_gpu(i=0):
    """Return gpu(i) if exists, otherwise return cpu().

    Defined in :numref:`sec_use_gpu`"""
    if torch.cuda.device_count() >= i + 1:
        return torch.device(f'cuda:{i}')
    try:
        return torch.device('mps')
    except:
        return torch.device('cpu')

# 修改try gpu函数
def try_all_gpus():
    """Return all available GPUs, or [cpu(),] if no GPU exists.

    Defined in :numref:`sec_use_gpu`"""
    devices = [torch.device(f'cuda:{i}')
               for i in range(torch.cuda.device_count())]
    try:
        device_macos = torch.device('mps')
    except:
        device_macos = torch.device('cpu')
    return devices if devices else [device_macos]

测试

运行lenet.ipynb测试效果

速度还可以。

还不懂的可以看M1版本的教程

相关推荐
Terrence Shen40 分钟前
Agent面试八股文(系列之二)
人工智能·大模型·agent·rag
爱睡懒觉的焦糖玛奇朵5 小时前
【从视频到数据集:焦糖玛奇朵的魔法工具使用说明】
人工智能·python·深度学习·学习·算法·yolo·音视频
oy_mail5 小时前
2026教程:用Gemini解决PCB设计与EMC/EMI问题,工程师效率跃升指南(国内直访)
人工智能
Runawayliquor5 小时前
opbase:CANN 所有算子的公共地基
大数据·数据库·人工智能·算法
英辰朗迪AI获客5 小时前
AI动态简报之算力基建篇(2026.05.22)
人工智能
徐安安ye5 小时前
FlashAttention 为什么对序列长度这么“敏感”?
人工智能·算法
天行健,君子而铎5 小时前
2026国内政务数据安全平台排名评析:基于AI降噪、全链路、动态性
人工智能·政务
智塑未来5 小时前
app应用怎么接入广告?标准流程与落地实操方案全解析
大数据·网络·人工智能
甲维斯5 小时前
Claude Code的六种种授权模式!安全和效率控制
人工智能·ai编程