在 Google Colab 中安裝 PyTorch 2.2.0

在 Google Colab 中安裝 PyTorch 2.2.0

前言

為了試跑 Dynamo Overview 中的程式碼,筆者首先在 Google Colab 預設的 Python 3.12.13 + PyTorch 2.11.0+cpu 環境裡執行,但在跑到 How to inspect artifacts generated by Dynamo? 章節的這一行時:

python 复制代码
guard, code = cache_entry.check_fn, cache_entry.code

卻會出現如下錯誤:

复制代码
AttributeError: 'torch._C._dynamo.eval_frame._CacheEntry' object has no attribute 'check_fn'

這是因為自 PyTorch 2.3 版本起,_CacheEntry 已經沒有 check_fn 欄位,取而代之的是 guard_manager 欄位,但兩者功能不同:

  • check_fn 代表「這個 cache entry 的 guard 檢查函式」;它會根據目前 frame 的 locals/globals/tensor metadata 判斷這個 compiled code 能不能重用
  • guard_manager 是 guard 管理/描述物件,無法替代 check_fn

為了原汁原味地運行教學裡的程式,不得已只好回退到 PyTorch 2.2 版。

安裝

但在 Colab 裡用 Python 3.12 + PyTorch 2.2 跑到以下這一行時:

python 复制代码
@torchdynamo.optimize(my_compiler)
def toy_example(a, b):
    ...

會出現:

复制代码
RuntimeError: Python 3.12+ not yet supported for torch.compile

這是說在 Python 3.12 下,可以 import torch,但是無法使用 torch.compile

沒辦法只能再回退 Python 版本到 3.11,在 Google Colab 中選取 執行階段

再選 變更執行階段類型

執行階段版本2025.07,參考 Frequently Asked Questions - Past Runtime Versions,這個版本中的 Python 為 3.11.13,PyTorch 則為 2.6.0。

因為 PyTorch 2.6.0 版還是太新了,只能重裝 2.2.0 版。先透過以下指令把之前的 PyTorch 清理乾淨:

shell 复制代码
!pip uninstall -y torch torchvision torchaudio triton
!rm -rf /usr/local/lib/python3.11/dist-packages/torch*
!rm -rf /usr/local/lib/python3.11/dist-packages/~orch*
!rm -rf /usr/local/lib/python3.11/dist-packages/triton*

安裝 PyTorch

shell 复制代码
!pip install torch==2.2.0+cpu torchvision==0.17.0+cpu torchaudio==2.2.0+cpu --index-url https://download.pytorch.org/whl/cpu

安裝完成後嘗試 import torch,會出現如下報錯:

复制代码
A module that was compiled using NumPy 1.x cannot be run in
NumPy 2.1.3 as it may crash. To support both 1.x and 2.x
versions of NumPy, modules must be compiled with NumPy 2.0.
Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.

If you are a user of the module, the easiest solution will be to
downgrade to 'numpy<2' or try to upgrade the affected module.
We expect that some modules will need time to support NumPy 2.

這個因為 PyTorch 2.1/2.2 是用 NumPy 1.x 的介面編譯的,如果搭配 NumPy 2.x 會導致 ABI 不相容的錯誤。

2025.07 裡的 numpy 版本是 2.0.2,得將它降為 1.x 版:

shell 复制代码
!pip install numpy==1.26.4 --force-reinstall

經過如上操作後,教學裡的程式碼終於能正常運行。

相关推荐
深小乐3 分钟前
DeepSeek Harness 强是真的强,普通用户可以再等等
人工智能
counting money20 分钟前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
坚持学习前端日记1 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
蜡台1 小时前
大模型算力下放客户端:浏览器/本地设备全落地方案解析
人工智能·ai
冬奇Lab1 小时前
开源项目第191期:gstack — YC CEO Garry Tan 开源的 AI 虚拟工程团队,23 个专家角色 slash command,从产品构思到上线发布的完整研发流程
人工智能·开源·资讯
北斗落凡尘1 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
冬奇Lab2 小时前
企业知识库系列(03):图增强 RAG 实测——GraphRAG vs HippoRAG
人工智能
MomentYY2 小时前
RAG 索引维护:文档改了,知识库要不要重建?
人工智能·agent·ai编程