【2025深度学习环境搭建-2】pytorch+Docker+VS Code+DevContainer搭建本地深度学习环境

news/2025/2/25 8:55:37

上一篇文章:【2025深度学习环境搭建-1】在Win11上用WSL2和Docker解锁GPU加速

  • 先启动Docker!
  • 对文件内容有疑问,就去问AI

pytorchGPU_3">一、用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插件

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

pytorchGPUpython_24">三、创建项目文件(测试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 True
        except Exception as e:
            print(f"\nGPU 操作失败: {str(e)}")
            return False
    else:
        print("没有可用的GPU进行测试")
        return False

if __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 容器用作开发环境


http://www.niftyadmin.cn/n/5865279.html

相关文章

python-leetcode-N 皇后

51. N 皇后 - 力扣(LeetCode) class Solution:def solveNQueens(self, n: int) -> List[List[str]]:res []board [[.] * n for _ in range(n)]def is_safe(row, col):for i in range(row):if board[i][col] Q:return Falseif col - (row - i) >…

opencv:距离变换 cv2.distanceTransform

函数 cv2.distanceTransform() 用于计算图像中每一个非零点像素与其最近的零点像素之间的距离(Distance Transform, DT算法),输出的是保存每一个非零点与最近零点的距离信息;图像上越亮的点,代表了离零点的距离越远。 …

halcon三维点云数据处理(二十五)moments_object_model_3d

目录 一、moments_object_model_3d例程二、moments_object_model_3d函数三、效果图一、moments_object_model_3d例程 这个例子说明了如何使用moments_object_model_3d运算符来将3D数据与x、y、z坐标轴对齐。在实际应用中,通过3D传感器获取的物体模型可能具有一个与物体主轴不…

C++中tuple的用法

C中tuple的用法 在C中&#xff0c;std::tuple 是一个模板类&#xff0c;用于存储一组不同类型的值。它类似于 Python 中的元组&#xff0c;但具有更强大的功能&#xff0c;例如支持不同类型的元素和更复杂的操作。std::tuple 是 C11 标准引入的&#xff0c;位于 <tuple>…

java23种设计模式-工厂方法模式

工厂方法模式&#xff08;Factory Method Pattern&#xff09;学习笔记 &#x1f31f; 定义 工厂方法模式属于创建型设计模式&#xff0c;定义一个创建对象的接口&#xff0c;但让子类决定实例化哪一个类。将类的实例化操作延迟到子类&#xff0c;是面向对象设计中"开闭…

OPPO发布新型折叠屏手机 起售价8999

在竞争激烈的智能手机市场&#xff0c;折叠屏手机作为高端科技的代表&#xff0c;一直备受关注。2025年2月20日晚&#xff0c;OPPO推出最新一代折叠屏旗舰手机Find N5&#xff0c;以其极致轻薄的设计、全面升级的性能和创新的功能&#xff0c;再次成为行业焦点。这款起售价8999…

在大数据项目中如何设计和优化数据模型

在大数据项目中&#xff0c;设计和优化数据模型是一个涉及多个步骤和维度的复杂过程。以下是我通常采取的方法&#xff1a; 一、数据模型设计 明确业务需求&#xff1a; 深入了解项目的业务场景和目标&#xff0c;明确数据模型需要解决的具体问题。与业务团队紧密合作&#xf…

Python GUI

Python GUI pip install PyQt5 pip install PySide2 pip install wxPython 这个下载太久了 import tkinter as tk def main(): # 创建主窗口 root tk.Tk() root.title("Hello World") # 创建一个标签&#xff0c;显示文本 label tk.Lab…