linux服务器配置GroundingDINO 详细过程(py310, cuda118, pytorch2.1) (离线下载bert-base-uncased运行)(2024年6月)

1. 参考帖子

已经跑通了,该踩的坑也都踩过来了,大家按照我配置的流程来配,大概率不会出错。(现在是2024/5/31日)
Grounding DINO使用攻略一
Github- IDEA-Research / GroundingDINO Public
【AI】Windows环境安装GroundingDINO
Ground DINO 自用/部署方法(notebook代码)
大家主要参考相关的Github网站

2. 配置流程:

环境配置:py310, cuda118, pytorch2.1

2.1 设置相关的环境变量:

# 首先: 设置相关的CUDA_HOME
echo $CUDA_HOME
# 寻找一下我们这台电脑的nvcc
which nvcc
# 显示/usr/local/cuda/bin/nvcc
# 设置相关的环境变量
export CUDA_HOME=/usr/local/cuda
# 再次输入:
echo $CUDA_HOME
显示:/usr/local/cuda
# 如果想永久的设置好cuda home(建议永久设置),可以这样设置:
echo 'export CUDA_HOME=/usr/local/cuda' >> ~/.bashrc
source ~/.bashrc
echo $CUDA_HOME

2.2 配置conda

下载anaconda

首先进入清华大学开源镜像站
点击里面的archive页面,下载Anaconda3-2024.02-1-Linux-x86_64.sh 安装包。 (但是夜里好像打不开清华大学开源镜像站,可能白天才能打开,可以换一个网址来下载。)

# 我使用的是autodl云服务器来跑的,这个服务器基本都把文件放到autodl-tmp文件夹下,大家进入自己的文件夹里就好
cd autodl-tmp
# 为Anaconda3-2024.02-1-Linux-x86_64.sh赋予运行权限
chmod +x Anaconda3-2024.02-1-Linux-x86_64.sh
# 开始安装
./Anaconda3-2024.02-1-Linux-x86_64.sh

# 之后在系统root根目录下运行
ls -a
# 之后可以看到相关的目录下有.bashrc文件,运行命令:
vim .bashrc
# 之后我们添加上一句: (因为我的conda装完以后默认就在/root/anaconda3下)
export PATH=/root/anaconda3/bin:$PATH
# 之后保存文件,然后
source ~/.bashrc
# 这样的话,我们默认运行的anaconda就是咱们自己安装的anaconda了。(系统里有两个conda,我制定了我自己安装的这个版本的conda,便于后续迁移到其他环境里)
# 我们运行命令:
conda info
# 只要我们包上传的过程不出错,安装的过程也不出错,同时全程正确的安装好了之后,这时显示的就是正确的conda信息、

配置相对应的环境

1. 先使用anadonda创建python3.10的DINO环境:

# 配置相对应的conda环境
source activate base
conda create -n dino python=3.10
conda init bash && source /root/.bashrc
conda activate dino

为了避免cuda版本错误,我在这里又额外利用conda安装了一下cuda: (服务器里已经有cuda11.8和cudnn的大家就不用再安装了)

conda search cudatoolkit
conda search cudnn
# 也可使用conda search cudatoolkit --info命令,下载后conda install ./cudatoolkit-11.3.1-h2bc3f7f_2.conda 本地安装
# 如果不怕慢,也可以换源搜索:
# conda search cudatoolkit -c conda-forge
# conda search cudnn -c conda-forge
conda install cudatoolkit==11.8.0
conda install cudnn==8.9.7.29
# 我这里本地下载安装了
# conda search cudatoolkit --info -c conda-forge
# conda install ./cudnn-8.9.7.29-hcdd5f01_2.conda
# 接下来可以检查一下conda安装的cuda和cudnn
conda list | grep cudatoolkit
conda list | grep cudnn

现在安装一下对应cuda11.8版本的pytorch2.1

conda install pytorch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 pytorch-cuda=11.8 -c pytorch -c nvidia

然后进入安装GroundingDINO:

# 首先获取相关的DINO的安装包
git clone https://github.com/IDEA-Research/GroundingDINO.git
cd GroundingDINO/
# 其次安装相关的DINO
pip install -e .

# 这回我们使用pip install -e . 没有报错了,因为提前安装了pytorch ,对应上了电脑用的conda

# 所以我们还是参考那个网址吧: https://zhuanlan.zhihu.com/p/635346878
# 创建weights文件夹
mkdir weights
cd weights
wget -q https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
cd ..

然后我们下载bert-base-uncased文件到本地文件夹中。把bert-base-uncased.tar移动到autodl-tmp/GroundingDINO文件夹内。然后解压
(
PS,我已经提前下好了bert-base-uncased.tar了,大家也可以直接用我的网盘来下载
链接:https://pan.baidu.com/s/18XNPQweebr6J4gBdb_zf-w
提取码:8x8d
–来自百度网盘超级会员V8的分享

cd GroundingDINO
tar -xvf bert-base-uncased.tar

运行dino

首先更改get_tokenlizer.py的相关代码:

GroundingDINO/groundingdino/util/get_tokenlizer.py文件原来的代码如下:

from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
import os

def get_tokenlizer(text_encoder_type):
    if not isinstance(text_encoder_type, str):
        # print("text_encoder_type is not a str")
        if hasattr(text_encoder_type, "text_encoder_type"):
            text_encoder_type = text_encoder_type.text_encoder_type
        elif text_encoder_type.get("text_encoder_type", False):
            text_encoder_type = text_encoder_type.get("text_encoder_type")
        elif os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type):
            pass
        else:
            raise ValueError(
                "Unknown type of text_encoder_type: {}".format(type(text_encoder_type))
            )
    print("final text_encoder_type: {}".format(text_encoder_type))

    tokenizer = AutoTokenizer.from_pretrained(text_encoder_type)
    return tokenizer


def get_pretrained_language_model(text_encoder_type):
    if text_encoder_type == "bert-base-uncased" or (os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type)):
        return BertModel.from_pretrained(text_encoder_type)
    if text_encoder_type == "roberta-base":
        return RobertaModel.from_pretrained(text_encoder_type)

    raise ValueError("Unknown text_encoder_type {}".format(text_encoder_type))

将这个文件的代码修改成: (这样可以载入本地的bert-base-uncased文件)
(我在修改过程中参考了如下帖子:
请问,离线运行,配置文件需要修改哪些地方?需要下载哪些文件?
Huggingface-Download files from the Hub
Unable to download online,已参考#75
google-bert/bert-base-uncased
但是之前的作者代码修改有问题,我又参考了如下帖子进行修改:
下载BERT模型到本地,并且加载使用
pytorch-pretrained-bert的模型下载慢的问题
(这些帖子还给了使用镜像下载bert的方法,不用怎么修改函数)
最终发现作者报错是因为没使用绝对路径:
from_pretrained()方法加载本地模型时报错:huggingface_hub.utils._validators.HFValidationError
上面的错误我都修改好了,大家直接运行我下面的代码即可(记得把bert-base-uncased放到对的位置上)
我最近再新开一个帖子,跟大家说怎么去本地下载bert-base-uncased模型

from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
import os

def get_tokenlizer(text_encoder_type):
    # import ipdb;ipdb.set_trace();
    if not isinstance(text_encoder_type, str):
        # print("text_encoder_type is not a str")
        if hasattr(text_encoder_type, "text_encoder_type"):
            text_encoder_type = text_encoder_type.text_encoder_type
        elif text_encoder_type.get("text_encoder_type", False):
            text_encoder_type = text_encoder_type.get("text_encoder_type")
        elif os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type):
            pass
        else:
            raise ValueError(
                "Unknown type of text_encoder_type: {}".format(type(text_encoder_type))
            )
    print("final text_encoder_type: {}".format(text_encoder_type))
    
    # 新添加代码片段
    tokenizer_path = "/root/autodl-tmp/GroundingDINO/bert-base-uncased"    # 这个需要使用绝对路径才可以。他这里使用了相对路径,有可能报错。
    tokenizer = BertTokenizer.from_pretrained(tokenizer_path, use_fast=False)
    return tokenizer

    '''
    tokenizer = AutoTokenizer.from_pretrained(text_encoder_type)
    return tokenizer
    '''
    

def get_pretrained_language_model(text_encoder_type):
    # import ipdb;ipdb.set_trace();
    if text_encoder_type == "bert-base-uncased" or (os.path.isdir(text_encoder_type) and os.path.exists(text_encoder_type)):
        # 新添加代码片段
        model_path = "/root/autodl-tmp/GroundingDINO/bert-base-uncased"
        return BertModel.from_pretrained(model_path)
        # return BertModel.from_pretrained(text_encoder_type)
    if text_encoder_type == "roberta-base":
        return RobertaModel.from_pretrained(text_encoder_type)

    raise ValueError("Unknown text_encoder_type {}".format(text_encoder_type))

运行程序

创建一个test.py文件:
在grounding dino文件夹下,新建一个test.py文件,其代码参考这个帖子:
https://zhuanlan.zhihu.com/p/670262724
但是因为这个作者的风格是ipynb风格的代码,我将其改成.py文件能运行的代码如下:

import os
import torch
import requests
from groundingdino.util.inference import load_model, load_image, predict, annotate
import supervision as sv

# settings
DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

HOME = os.getcwd()
CONFIG_PATH = os.path.join(HOME, "groundingdino/config/GroundingDINO_SwinT_OGC.py")
WEIGHTS_NAME = "groundingdino_swint_ogc.pth"
WEIGHTS_PATH = os.path.join(HOME, "weights", WEIGHTS_NAME)

model = load_model(CONFIG_PATH, WEIGHTS_PATH)

# 下载示例图片
data_dir = os.path.join(HOME, 'data')
os.makedirs(data_dir, exist_ok=True)
os.chdir(data_dir)

image_urls = [
    "https://media.roboflow.com/notebooks/examples/dog.jpeg",
    "https://media.roboflow.com/notebooks/examples/dog-2.jpeg",
    "https://media.roboflow.com/notebooks/examples/dog-3.jpeg",
    "https://media.roboflow.com/notebooks/examples/dog-4.jpeg",
]

for url in image_urls:
    image_name = url.split('/')[-1]
    response = requests.get(url)
    with open(image_name, 'wb') as f:
        f.write(response.content)

IMAGE_NAME = "dog-2.jpeg"
IMAGE_PATH = os.path.join(HOME, "data", IMAGE_NAME)

TEXT_PROMPT = "straw" # 可以换成"dog",则只给出dog
BOX_TRESHOLD = 0.35
TEXT_TRESHOLD = 0.25

image_source, image = load_image(IMAGE_PATH)

boxes, logits, phrases = predict(
    model=model,  
    image=image,  
    caption=TEXT_PROMPT,  
    box_threshold=BOX_TRESHOLD,  
    text_threshold=TEXT_TRESHOLD
)

annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)

# 为了在Python脚本中展示图片,你可能需要使用其他库,如OpenCV或PIL等
# 这里只是保存图片,你可能需要根据你的需求进行修改
sv.plot_image(annotated_frame, (16, 16))

之后python test.py运行就可以了。

也可以运行如下程序2:
创建一个test2.py

from groundingdino.util.inference import load_model, load_image, predict, annotate
import cv2

model = load_model("groundingdino/config/GroundingDINO_SwinT_OGC.py", "weights/groundingdino_swint_ogc.pth")
IMAGE_PATH = "weights/dog-3.jpeg"
TEXT_PROMPT = "chair . person . dog ."
BOX_TRESHOLD = 0.35
TEXT_TRESHOLD = 0.25

image_source, image = load_image(IMAGE_PATH)

boxes, logits, phrases = predict(
    model=model,
    image=image,
    caption=TEXT_PROMPT,
    box_threshold=BOX_TRESHOLD,
    text_threshold=TEXT_TRESHOLD
)

annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
cv2.imwrite("annotated_image.jpg", annotated_frame)

python test2.py

之后就根据自己的需求对代码做进一步的修改即可。

我自己对代码做的修改:

检测dog-3.jpeg图片中的chair,person,dog三个物体

from groundingdino.util.inference import load_model, load_image, predict, annotate
import cv2

model = load_model("groundingdino/config/GroundingDINO_SwinT_OGC.py", "weights/groundingdino_swint_ogc.pth")
IMAGE_PATH = "weights/dog-3.jpeg"
TEXT_PROMPT = "chair . person . dog ."
BOX_TRESHOLD = 0.35
TEXT_TRESHOLD = 0.25

image_source, image = load_image(IMAGE_PATH)

boxes, logits, phrases = predict(
    model=model,
    image=image,
    caption=TEXT_PROMPT,
    box_threshold=BOX_TRESHOLD,
    text_threshold=TEXT_TRESHOLD
)
import ipdb;ipdb.set_trace()
annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)    #这个文件里的phrases直接就可以拿来用,而且也可以和boxes一起拿来用。
cv2.imwrite("annotated_image.jpg", annotated_frame)
<think>我们正在处理一个关于在PyCharm中配置和使用BERT-BiLSTM-CRF模型的问题。用户需要知道安装配置步骤,包括需要下载的模型文件和通过PyCharm安装的依赖。 根据引用[3]:我们有一个基于BERT+LSTM+CRF的医疗知识图谱问答系统,这暗示了BERT-BiLSTM-CRF模型的应用。同时,引用[1]提到了在服务器上训练BERT-BiLSTM-CRF模型,但用户现在是在本地PyCharm环境中配置。 步骤概述: 1. 环境准备:Python环境(建议Python 3.6或更高版本,引用[4]提到Python3.6环境) 2. 创建PyCharm项目并设置解释器 3. 安装必要的依赖包(通过PyCharm的终端或安装界面) 4. 下载预训练的BERT模型(例如来自Hugging Face的Transformers库提供的模型) 5. 构建或获取BERT-BiLSTM-CRF模型的代码(可能需要自己编写或从开源项目获取) 6. 准备数据并运行模型 详细步骤: 1. 创建PyCharm项目: - 打开PyCharm,创建新项目,选择好项目路径和解释器(如果没有,可以新建一个虚拟环境)。 2. 设置Python解释器: -PyCharm中,通过File -> Settings -> Project -> Python Interpreter 来管理包。 3. 安装依赖: - 通过PyCharm的终端(Terminal)或使用解释器设置界面中的“+”按钮安装以下包: transformers(提供BERT模型和相关的功能) tensorflow 或 pytorch(作为深度学习框架,根据模型代码选择) keras(如果使用TensorFlow,并且代码基于Keras) tqdm(用于显示进度条) numpy, pandas(数据处理) sklearn(用于评估等) seqeval(用于序列标注任务的评估) crf++ 或 sklearn-crfsuite(如果模型需要CRF层,但通常我们使用Keras或PyTorch实现的CRF层,如keras-contrib中的CRF层,但注意keras-contrib已不再维护,现在常用tensorflow_addons或pytorch-crf) 注意:由于BERT-BiLSTM-CRF模型可能使用不同的框架实现,我们需要根据具体代码选择安装。例如,如果使用PyTorch,则安装torch。 通过终端安装示例: ```bash pip install transformers tensorflow==2.10.0 numpy pandas sklearn seqeval tqdm ``` 或者(如果使用PyTorch): ```bash pip install transformers torch numpy pandas sklearn seqeval tqdm ``` 对于CRF层,如果使用TensorFlow,可以安装tensorflow_addons(包含CRF层): ```bash pip install tensorflow-addons ``` 如果使用PyTorch,可以安装: ```bash pip install pytorch-crf ``` 4. 下载预训练BERT模型: - 我们可以使用Hugging Face提供的预训练模型。在代码中,我们可以通过模型名称直接下载,例如'bert-base-uncased'。但为了离线使用,也可以提前下载到本地。 - 下载方式:在Hugging Face模型库(https://huggingface.co/models)中找到需要的模型,如`bert-base-uncased`,然后使用`transformers`提供的`from_pretrained`方法时会自动下载(第一次运行代码时)。如果希望手动下载,可以点击页面的“List all files in model”然后逐个下载,并放到一个文件夹中,然后在代码中指定该文件夹路径。 5. 获取模型代码: - BERT-BiLSTM-CRF模型的结构通常为:BERT作为嵌入层,然后接BiLSTM,最后接CRF层。 - 我们可以自己编写模型,或者参考开源项目。例如,在PyTorch中,我们可以这样构建: ```python from transformers import BertModel import torch import torch.nn as nn from torchcrf import CRF class BertBiLSTMCRF(nn.Module): def __init__(self, bert_model_name, num_tags, lstm_hidden_size, lstm_layers=1, dropout=0.1): super().__init__() self.bert = BertModel.from_pretrained(bert_model_name) self.lstm = nn.LSTM(self.bert.config.hidden_size, lstm_hidden_size // 2, num_layers=lstm_layers, bidirectional=True, batch_first=True) self.dropout = nn.Dropout(dropout) self.classifier = nn.Linear(lstm_hidden_size, num_tags) self.crf = CRF(num_tags, batch_first=True) def forward(self, input_ids, attention_mask, labels=None): outputs = self.bert(input_ids, attention_mask=attention_mask) sequence_output = outputs.last_hidden_state lstm_output, _ = self.lstm(sequence_output) lstm_output = self.dropout(lstm_output) emissions = self.classifier(lstm_output) if labels is not None: loss = -self.crf(emissions, labels, mask=attention_mask.byte()) return loss else: return self.crf.decode(emissions, mask=attention_mask.byte()) ``` 在TensorFlow中,可以使用类似的结构,但需要从`tensorflow_addons`中导入CRF层。 6. 准备数据: - 需要将数据整理成模型可接受的格式,通常包括tokenization(使用BERT的tokenizer),然后构建输入(input_ids, attention_mask)和标签(tags)的数组。 7. 训练和评估: - 编写训练循环,包括数据加载、前向传播、损失计算、反向传播等。 注意事项: - 由于BERT模型较大,训练需要较大的内存和显存。如果本地资源不足,可以考虑使用云服务器(如引用[1]中提到的矩池云)。 -PyCharm中运行代码时,可能需要设置运行配置,特别是当使用GPU时,确保环境变量正确。 引用说明: - 关于BERT-BiLSTM-CRF模型的应用,可以参考引用[3]中提到的医疗知识图谱问答系统,该系统采用了类似的模型结构。 - 引用[1]提到了在服务器上训练该模型,但步骤中的环境配置和代码编写在本地PyCharm中同样适用。 因此,在PyCharm中配置和使用BERT-BiLSTM-CRF模型的主要步骤包括:环境设置、依赖安装、模型下载、代码编写(或获取)、数据准备和模型训练。 生成相关问题: 1. BERT-BiLSTM-CRF模型在序列标注任务中如何工作? 2. 如何为BERT-BiLSTM-CRF模型准备训练数据? 3. 在本地训练大型模型(如BERT)时资源不足怎么办?</think>### 在PyCharm中配置BERT-BiLSTM-CRF模型的完整指南 #### 一、环境配置步骤 1. **创建PyCharm项目** - 新建Python项目(建议Python 3.8+) - 创建虚拟环境:`File > New Project > 勾选"New environment"` 2. **安装核心依赖** 在PyCharm终端执行: ```bash pip install transformers==4.28.1 # BERT模型支持 pip install tensorflow==2.10.0 # 或PyTorch pip install keras==2.10.0 # BiLSTM层实现 pip install keras-bert==0.89.0 # BERT集成 pip install keras-crf==0.0.8 # CRF层支持 pip install seqeval # 序列标注评估 ``` 3. **模型文件下载** | 文件类型 | 下载来源 | 保存位置 | |---------|----------|----------| | BERT预训练模型 | [Hugging Face Model Hub](https://huggingface.co/models) | `项目目录/bert_model/` | | 词表文件 | 同上(如`bert-base-uncased`) | 与模型同目录 | | 示例数据集 | CoNLL-2003等公开NER数据集 | `项目目录/data/` | #### 二、项目结构配置 ``` your_project/ ├── bert_model/ # BERT模型文件 │ ├── config.json # 模型配置文件 │ ├── pytorch_model.bin # PyTorch权重 │ └── vocab.txt # 词表 ├── data/ # 训练数据 ├── utils/ # 工具函数 ├── model.py # 模型架构代码 └── train.py # 训练脚本 ``` #### 三、模型实现示例 ```python # model.py from transformers import TFBertModel from tensorflow.keras.layers import Bidirectional, LSTM, Dense from keras_crf import CRFModel def build_bert_bilstm_crf(num_tags): # BERTbert = TFBertModel.from_pretrained('bert_model/') # BiLSTM层 bilstm = Bidirectional(LSTM(128, return_sequences=True)) # 输出层 dense = Dense(num_tags, activation='relu') # 构建CRF模型 model = CRFModel( inputs=bert.input, outputs=dense(bilstm(bert.output)), num_tags=num_tags ) return model ``` #### 四、训练流程 1. **数据预处理** ```python from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained('bert_model/vocab.txt') # 文本转BERT输入 inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="tf") ``` 2. **模型训练** ```python model = build_bert_bilstm_crf(num_tags=len(tag_list)) model.compile(optimizer='adam') model.fit( x=[inputs["input_ids"], inputs["attention_mask"]], y=labels, epochs=10, batch_size=32 ) ``` #### 五、常见问题解决 1. **CUDA内存不足**: - 降低`batch_size` - 使用`tf.config.experimental.set_memory_growth()` 2. **依赖冲突**: - 固定库版本:`pip install tensorflow==2.10.0 transformers==4.28.1` 3. **CRF层报错**: - 确保使用`keras-crf`而非`sklearn-crfsuite` - 检查标签格式是否为整数序列 > **关键提示**:医疗文本处理需使用领域适配的BERT变体(如BioBERT)[^3],可通过[Hugging Face](https://huggingface.co/dmis-lab/biobert-base-cased-v1.1)获取专业预训练模型。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值