上一篇文章:【2025深度學習環境搭建-1】在Win11上用WSL2和Docker解鎖GPU加速
- 先啟動Docker!
- 對文件內容有疑問,就去問AI
一、用Docker拉取pytorch鏡像,啟動容器,測試GPU
docker pull pytorch/pytorch:2.5.0-cuda12.4-cudnn9-devel
docker run -it --rm --gpus all pytorch/pytorch:2.5.0-cuda12.4-cudnn9-devel nvidia-smi
別忘了用
--gpus all
啟用GPU
能出現顯卡信息,說明基于該鏡像的容器,是可以用gpu的。之后要把這個鏡像應用到到我們的開發環境之中(使用VS Code插件Dev Container)
二、安裝VS Code插件
三、創建項目文件(測試pytorch和GPU的python程序)
創建文件夾pytorch-test,并在其目錄下創建如下文件夾和文件(主要創建app.py和.devcontainer就行,其他的隨意):
需要創建的文件,內容如下:
requirements.txt
這個文件內容為空
app.py
import torch
a=[1,23,4,5,.4]
def print_gpu_info():# 檢查CUDA是否可用cuda_available = torch.cuda.is_available()print(f"CUDA 是否可用: {cuda_available}")if not cuda_available:return# 獲取GPU數量device_count = torch.cuda.device_count()print(f"\n可用的GPU數量: {device_count}")# 打印每個GPU的詳細信息for i in range(device_count):print(f"\n=== GPU {i} ===")print(f"名稱: {torch.cuda.get_device_name(i)}")prop = torch.cuda.get_device_properties(i)print(f"總內存: {prop.total_memory / 1024**3:.2f} GB")print(f"多處理器數量: {prop.multi_processor_count}")print(f"計算能力: {prop.major}.{prop.minor}")def test_gpu_operation():# 嘗試在GPU上執行操作if torch.cuda.is_available():try:# 創建測試張量x = torch.randn(3, 3).cuda()y = torch.randn(3, 3).cuda()z = x + y # 執行GPU計算# 驗證設備類型print("\n=== GPU 操作測試 ===")print(f"張量所在設備: {x.device}")print("GPU 計算成功!")return Trueexcept Exception as e:print(f"\nGPU 操作失敗: {str(e)}")return Falseelse:print("沒有可用的GPU進行測試")return Falseif __name__ == "__main__":print("===== PyTorch GPU 信息 =====")print_gpu_info()print("\n===== GPU 功能測試 =====")test_result = test_gpu_operation()print("\n===== 最終狀態 =====")print(f"GPU 是否可用: {torch.cuda.is_available()}")print(f"GPU 是否可用: {test_result}")print(f"PyTorch 版本: {torch.__version__}")
.devcontainer/devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-dockerfile
{"name": "GPU Development,torch2.5+cu124+cudnn9,Py3.11.10","runArgs": ["--gpus=all" // 添加 GPU 支持],"build": {// Sets the run context to one level up instead of the .devcontainer folder."context": "..",// Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename."dockerfile": "Dockerfile"},"customizations": {"vscode": {"extensions": ["ms-python.python","ms-toolsai.jupyter","ms-python.autopep8","ms-python.vscode-pylance","mechatroner.rainbow-csv","ms-azuretools.vscode-docker","ms-toolsai.datawrangler"]}}// Features to add to the dev container. More info: https://containers.dev/features.// "features": {},// Use 'forwardPorts' to make a list of ports inside the container available locally.// "forwardPorts": [],// Uncomment the next line to run commands after the container is created.// "postCreateCommand": "cat /etc/os-release",// Configure tool-specific properties.// "customizations": {},// Uncomment to connect as an existing user other than the container default. More info: https://aka.ms/dev-containers-non-root.// "remoteUser": "devcontainer"
}
.devcontainer/Dockerfile
# 使用 PyTorch 官方鏡像作為基礎鏡像
FROM pytorch/pytorch:2.5.0-cuda12.4-cudnn9-devel# 設置工作目錄(容器中的)
WORKDIR /workspace# 將本地代碼復制到容器中
COPY . /workspace# 安裝額外的依賴(如果有)
RUN pip install --no-cache-dir -r requirements.txt# 暴露端口(如果有需要)
# EXPOSE 8000# 定義容器啟動時運行的命令
# CMD ["python", "app.py"]
README.md
## pip環境導入導出
從requirements.txt導入環境:
`pip install --no-cache-dir -r requirements.txt`
導出環境到文件requirements.txt:
`pip freeze | grep -v '@ file://' > requirements.txt`
四、打開項目文件,并使用容器環境
在VS Code中打開項目文件
按下【F1】在上方選擇【Dev Containers:Reopen in Container】
此時查看vscode左下角,藍底白字,顯示Dev Container: GPU Development,torch2.5+..
,就說明我們現在的項目torch-test已經在使用剛才拉取的pytorch容器了!
在左邊找到app.py,運行他,若顯示可用gpu大于0,表示項目torch-test中的python程序可以使用gpu。之后我們需要運行深度學習程序時,使用這里的步驟即可,不需要安裝額外的python環境了,若需要安裝其他包,那就修改requirements.txt文件即可。
五、需要安裝其他python包怎么辦?
若我們需要其他python包,那就在終端直接安裝,測試能用之后,用pip freeze | grep -v '@ file://' > requirements.txt
將當前python環境中的包導出到文件requirements.txt
中。
之后再啟動項目時,Dev Container
會自動幫我們根據文件requirements.txt
安裝環境。
清空文件
requirements.txt
中的內容,之后重新構建容器,即可得到一個原始鏡像中的python環境
補充:如何重新構建容器
按【F1】,搜索【Dev Containers:Rebuild Container】
補充:在鏡像中添加VS Code插件
可以在鏡像中添加VS Code插件,之后每次構建,鏡像都會自動安裝插件,不用自己手動安裝了
方法:右鍵單擊插件,點擊【Add to devcontainer.json】
參考
教程:使用 Visual Studio Code 創建 Docker 應用
借助 Visual Studio Code 將 Docker 容器用作開發環境