动手学深度学习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版本的教程

相关推荐
一点一木2 小时前
🚀 2026 年 8 月 GitHub 十大热门项目排行榜 🔥
人工智能·github
ssshooter2 小时前
现在网页都能提供 MCP 了?!
前端·人工智能·程序员
京东云开发者2 小时前
Claude Code vs Codex 记忆体系深度对比
人工智能
不加辣椒3 小时前
第 4 章 什么是 Harness Engineering
人工智能
桃西西呀3 小时前
上下文窗口都卷到 100 万了,大模型为什么还在为"位置"发愁?
人工智能·llm·ai编程
阿拉斯攀登3 小时前
SpringBoot整合MQTT:后端订阅设备数据、解析传感器报文
人工智能
然我3 小时前
模型不是 Agent:从零实现一个最小 Agent Loop
前端·人工智能·agent
黄油面包3 小时前
Codex 额度三天见底后,我重新做了一周预算
前端·人工智能
AI效率君3 小时前
Deer‑Flow 2.0 + Go‑MCP‑Server(add加法工具)保姆级完整教程
人工智能·agent
阿拉斯攀登3 小时前
SpringCloud微服务MQTT架构:设备消息统一接入、业务分发设计
人工智能