CLIP代码运行
整体步骤
1.上传代码至服务器
2.创建conda环境clip_dev
3.安装依赖pytorch、torchvision依赖
4.安装其他依赖
5.在项目路径下
6.运行项目
具体实现
-
上传代码至服务器
-
创建
conda
环境clip_dev
conda create clip_dev python=3.8 # 如果镜像源出现问题导致无法创建上述环境,先用下行代码换回默认源再创建 conda config --remove-key channels
-
安装依赖
pytorch、torchvision
依赖(conda
不行用pip
)# 先检查一下nvidia的最高版本 nvidia-smi # 复制pytorch安装代码(https://pytorch.org/get-started/previous-versions/) pip install torch==2.2.1 torchvision==0.17.1 torchaudio==2.2.1 --index-url https://download.pytorch.org/whl/cu118
-
安装其他依赖
# 根据官网提示/requirements.txt文件安装其他依赖 pip install ftfy regex tqdm #清华源 -i https://pypi.tuna.tsinghua.edu.cn/simple
-
安装
setup.py
(setup.py
文件会遍历requirements.txt
,并自动安装其中包含的依赖,因此实际上5包含了4,按理说只要执行5就够了,但是由于pip
安装常常需要镜像源,一般还是先用4安装,再用5作为双层保险)setup.py
的作用有两个:- 自动安装
requirements.txt
的依赖 - 将整个项目构建成一个包,让它可以在其他项目中作为一个依赖进行导入
# 先进入项目路径下 cd CLIP_MAIN # 安装setup.py pip install -e . 或pip install .
- 自动安装
-
运行项目
#根据官网提示,在项目路径下创建文件myEntry.py,复制官网提供的代码 import torch import clip from PIL import Image device = "cuda" if torch.cuda.is_available() else "cpu" model, preprocess = clip.load("ViT-B/32", device=device) image = preprocess(Image.open("CLIP.png")).unsqueeze(0).to(device) text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device) with torch.no_grad(): image_features = model.encode_image(image) text_features = model.encode_text(text) logits_per_image, logits_per_text = model(image, text) probs = logits_per_image.softmax(dim=-1).cpu().numpy() print("Label probs:", probs) # prints: [[0.9927937 0.00421068 0.00299572]] #执行myEntry.py python myEntry.py
-
调试项目(Debug-参考利用Docker容器部署GLIP项目最后的Debug部分)
-
创建
launch.json
文件。点击vscode左侧的run and debug
窗口=>create a launch.json
=>选择Python debugger
=>Python file
,然后就创建了一个launch.json
文件 -
点击右下角的
Python Interpreter
,选择服务器端的Python解释器(我选择的是之前安装conda创建的clip_dev这一虚拟环境的Python解释器) -
修改
launch.json
文件内容参考原本开启训练的代码
python myEntry.py
修改launch.json
# 修改项目路径为开启训练时的python文件myEntry.py的绝对路径 # 修改最后一项"python"对应的值,表示python解释器的地址。如果是conda环境,可以直接在环境中输入which python,即可获得该地址(这一步应该和步骤2是重复的) { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Clip Debug", "type": "debugpy", "request": "launch", "program": "${file}", # 将值修改为/data/xxx/CLIP_main/myEntry.py "console": "integratedTerminal", "python": "/home/xjingyu/anaconda3/envs/clip_dev/bin/python" } ] }
-
回到文件目录,打断点调试
-