centos-LLM-生物信息-BioGPT-使用1

参考
GitHub - microsoft/BioGPT
https://github.com/microsoft/BioGPT

BioGPT:用于生物医学文本生成和挖掘的生成式预训练转换器 |生物信息学简报 |牛津学术 — BioGPT: generative pre-trained transformer for biomedical text generation and mining | Briefings in Bioinformatics | Oxford Academic
https://academic.oup.com/bib/article/23/6/bbac409/6713511

环境
centos 7,anaconda3,CUDA 11.6

安装方法:
centos-LLM-生物信息-BioGPT安装-CSDN博客
https://blog.csdn.net/pxy7896/article/details/146982288


目录

  • 官方测试用例
    • 使用hugging face
      • 文本生成
  • 报错处理
    • ModuleNotFoundError: No module named 'torch.distributed.tensor'
    • A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.1

BioGPT 是一个基于 GPT 架构的生物医学领域预训练语言模型,适用于生成生物医学文本或进行相关 NLP 任务。

官方测试用例

使用hugging face

文本生成

说明:

  • BioGptForCausalLM是GPT类型的因果语言模型,适用于:
    • 文本生成:如问答、摘要
    • 生物医学文本续写:如生成诊断报告
  • BioGptForCausalLM是基于TransformerDecoder-only架构,参数量:1.5B(Large 版本)或 345M(Base 版本)
import os
# 国内加速
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'from transformers import BioGptTokenizer, BioGptForCausalLM
from transformers import pipeline, set_seed
# 加载分词器tokenizer(1.将文本转化为Token IDs供模型理解 2.处理特殊标记)
tokenizer = BioGptTokenizer.from_pretrained("microsoft/biogpt")
# 加载模型(加载时会下载预训练权重)
model = BioGptForCausalLM.from_pretrained("microsoft/biogpt")
'''
text = "Replace me by any text you'd like."
# 返回 PyTorch 张量. tf是返回tensorflow张量, np是返回NumPy数组
# Hugging Face 的 Transformers 库支持 PyTorch、TensorFlow 和 JAX,需明确指定张量格式
encoded_input = tokenizer(text, return_tensors='pt')
output = model(**encoded_input) # 
'''
# 创建文本生成的流水线,能自动处理文本的分词、模型调用和输出解码
generator = pipeline('text-generation', model=model, tokenizer=tokenizer)
# 设置随机种子,确保生成结果可以复现
set_seed(42)
# 要求生成5条不同的文本(需要生成越多越增加显存占用)
# 每条最大长度为20个token,启用随机采样(非确定性生成)
# 模型会基于概率分布随机选择下一个 token(温度参数默认为 1.0),因此每次调用结果可能不同
# 与 do_sample=False(贪心搜索)相比,结果更具多样性
# 如果需要控制随机性可以设置temperature,越小越保守
outputs = generator("COVID-19 is", max_length=20, num_return_sequences=5, do_sample=True)
# 打印结果
for i, output in enumerate(outputs):print(f"Result {i+1}: {output['generated_text']}")
'''
Result 1: COVID-19 is a disease that spreads worldwide and is currently found in a growing proportion of the population
Result 2: COVID-19 is one of the largest viral epidemics in the world.
Result 3: COVID-19 is a common condition affecting an estimated 1.1 million people in the United States alone.
Result 4: COVID-19 is a pandemic, the incidence has been increased in a manner similar to that in other
Result 5: COVID-19 is transmitted via droplets, air-borne, or airborne transmission.
'''

Beam-Search:
Beam-Search(束搜索) 是一种用于序列生成(如文本生成、机器翻译)的搜索算法,比贪心搜索(Greedy Search)更高效且能生成更优结果。其核心思想是:在每一步保留 Top-K(K = num_beams) 个最可能的候选序列,而不是只保留一个最优解(贪心策略)。

参数选择:

  • num_beams:越大结果越好,但是计算量也越。通常5是平衡点
  • early_stopping:当所有候选序列都达到结束标记时提前终止
  • min_lengthmax_length:控制生成的文本的token数量,防止过早结束或者太长
  • length_penalty:长度惩罚( <1 鼓励短文本,>1 鼓励长文本 )
import torch
from transformers import BioGptTokenizer, BioGptForCausalLM, set_seedtokenizer = BioGptTokenizer.from_pretrained("microsoft/biogpt")
model = BioGptForCausalLM.from_pretrained("microsoft/biogpt")sentence = "COVID-19 is"
inputs = tokenizer(sentence, return_tensors="pt")set_seed(42)with torch.no_grad():# 生成一个包含生成的token IDs的张量beam_output = model.generate(**inputs, min_length=100, max_length=1024, num_beams=5, early_stopping=True)
# 解码
tokenizer.decode(beam_output[0], skip_special_tokens=True)
'''
COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK), and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and more than 800,000 deaths.
'''

报错处理

ModuleNotFoundError: No module named ‘torch.distributed.tensor’

完整报错:

>>> from transformers import pipeline, set_seed
Traceback (most recent call last):File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/utils/import_utils.py", line 1967, in _get_modulereturn importlib.import_module("." + module_name, self.__name__)File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/importlib/__init__.py", line 126, in import_modulereturn _bootstrap._gcd_import(name[level:], package, level)File "<frozen importlib._bootstrap>", line 1050, in _gcd_importFile "<frozen importlib._bootstrap>", line 1027, in _find_and_loadFile "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlockedFile "<frozen importlib._bootstrap>", line 688, in _load_unlockedFile "<frozen importlib._bootstrap_external>", line 883, in exec_moduleFile "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removedFile "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/pipelines/__init__.py", line 49, in <module>from .audio_classification import AudioClassificationPipelineFile "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/pipelines/audio_classification.py", line 21, in <module>from .base import Pipeline, build_pipeline_init_argsFile "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/pipelines/base.py", line 69, in <module>from ..modeling_utils import PreTrainedModelFile "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/modeling_utils.py", line 41, in <module>import torch.distributed.tensor
ModuleNotFoundError: No module named 'torch.distributed.tensor'The above exception was the direct cause of the following exception:Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<frozen importlib._bootstrap>", line 1075, in _handle_fromlistFile "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/utils/import_utils.py", line 1955, in __getattr__module = self._get_module(self._class_to_module[name])File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/utils/import_utils.py", line 1969, in _get_moduleraise RuntimeError(
RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback):
No module named 'torch.distributed.tensor'

已知torch.distributed.tensor 模块在 PyTorch 1.10+ 才引入,但我的 PyTorch 版本是1.12.0,考虑是transformers版本冲突,所以降级到4.28.1。

pip install transformers==4.28.1 -i https://pypi.tuna.tsinghua.edu.cn/simple

在这里插入图片描述
验证:

>>> import torch
>>> print(torch.__version__)
1.12.0
>>> print(torch.distributed.is_available()) 
True

A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.1

完整报错:

>>> model = BioGptForCausalLM.from_pretrained("microsoft/biogpt")A module that was compiled using NumPy 1.x cannot be run in
NumPy 2.0.1 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.Traceback (most recent call last):  File "<stdin>", line 1, in <module>File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/modeling_utils.py", line 2560, in from_pretrainedstate_dict = load_state_dict(resolved_archive_file)File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/transformers/modeling_utils.py", line 442, in load_state_dictreturn torch.load(checkpoint_file, map_location="cpu")File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/torch/serialization.py", line 712, in loadreturn _load(opened_zipfile, map_location, pickle_module, **pickle_load_args)File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/torch/serialization.py", line 1049, in _loadresult = unpickler.load()File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/torch/_utils.py", line 138, in _rebuild_tensor_v2tensor = _rebuild_tensor(storage, storage_offset, size, stride)File "/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/torch/_utils.py", line 133, in _rebuild_tensort = torch.tensor([], dtype=storage.dtype, device=storage._untyped().device)
/home/xxx/anaconda3/envs/biogpt/lib/python3.10/site-packages/torch/_utils.py:133: UserWarning: Failed to initialize NumPy: _ARRAY_API not found (Triggered internally at  /opt/conda/conda-bld/pytorch_1656352645774/work/torch/csrc/utils/tensor_numpy.cpp:68.)t = torch.tensor([], dtype=storage.dtype, device=storage._untyped().device)

错误原因

  • 错误日志中的 Failed to initialize NumPy: _ARRAY_API not found 表明 PyTorch 正在尝试调用 NumPy 1.x 的 API,但当前环境是 NumPy 2.0
  • 许多科学计算库(如 PyTorch、HuggingFace Transformers)在发布时是基于 NumPy 1.x 编译的
  • NumPy 2.0 修改了 ABI(应用程序二进制接口),导致旧版编译的扩展模块无法直接运行

解决方案
降级到比较低的版本。

pip install "numpy>=1.21,<2" -i https://pypi.tuna.tsinghua.edu.cn/simple

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/901438.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

高效爬虫:一文掌握 Crawlee 的详细使用(web高效抓取和浏览器自动化库)

更多内容请见: 爬虫和逆向教程-专栏介绍和目录 文章目录 一、Crawlee概述1.1 Crawlee介绍1.2 为什么 Crawlee 是网页抓取和爬取的首选?1.3 为什么使用 Crawlee 而不是 Scrapy1.4 Crawlee的安装二、Crawlee的基本使用2.1 BeautifulSoupCrawler的使用方式2.2 ParselCrawler的使…

架构总览怎么写,才算工业级?

📈系统架构文档是整个项目最重要的起点,但很多人第一章就“写穿了”: 不是写得太细,就是没有重点。想要写出高质量、能协作、能传承的架构文档,这一篇会告诉你应该怎么做—— ✅ 架构总览的终极目标 明确边界、定义角色、画清数据流 别讲执行细节,别深入函数调用。 ✅ 架…

优先级队列(堆二叉树)底层的实现:

我们继续来看我们的优先级队列&#xff1a; 优先级队列我们说过&#xff0c;他也是一个容器适配器&#xff0c;要依赖我们的容器来存储数据&#xff1b; 他的第二个参数就是我们的容器&#xff0c;这个容器的默认的缺省值是vector&#xff0c;然后他的第三个参数&#xff0c;我…

GIC驱动程序分析

今天呢&#xff0c;我们就来具体的讲一下GIC的驱动源码啦&#xff0c;这个才是重点来着&#xff0c;我们来看看&#xff1a; GIC中的重要函数和结构体&#xff1a; 沿着中断的处理流程&#xff0c;GIC涉及这4个重要部分&#xff1a; CPU从异常向量表中调用handle_arch_irq&am…

java操作redis库,开箱即用

application.yml spring:application:name: demo#Redis相关配置redis:data:# 地址host: localhost# 端口&#xff0c;默认为6379port: 6379# 数据库索引database: 0# 密码password:# 连接超时时间timeout: 10slettuce:pool:# 连接池中的最小空闲连接min-idle: 0# 连接池中的最…

Cribl 通过Splunk search collector 来收集数据

今天利用Spliunk search collector 来收集数据啦:还是要先cribl 的官方文档: Splunk Search Collector | Cribl Docs Splunk Search Collector Cribl Stream supports collecting search results from Splunk queries. The queries can be both simple and complex, as well a…

What Was the “Game Genie“ Cheat Device, and How Did It Work?

什么是“Game Genie”作弊装置&#xff0c;它是如何工作的&#xff1f; First released in 1991, the Game Genie let players enter special codes that made video games easier or unlocked other functions. Nintendo didnt like it, but many gamers loved it. Heres wha…

位运算题目:连接连续二进制数字

文章目录 题目标题和出处难度题目描述要求示例数据范围 解法思路和算法代码复杂度分析 题目 标题和出处 标题&#xff1a;连接连续二进制数字 出处&#xff1a;1680. 连接连续二进制数字 难度 5 级 题目描述 要求 给定一个整数 n \texttt{n} n&#xff0c;将 1 \text…

第十六届蓝桥杯Java b组(试题C:电池分组)

问题描述&#xff1a; 输入格式&#xff1a; 输出格式&#xff1a; 样例输入&#xff1a; 2 3 1 2 3 4 1 2 3 4 样例输出: YES NO 说明/提示 评测用例规模与约定 对于 30% 的评测用例&#xff0c;1≤T≤10&#xff0c;2≤N≤100&#xff0c;1≤Ai​≤10^3。对于 100…

63. 评论日记

2025年4月14日18:53:30 雷军这次是真的累了_哔哩哔哩_bilibili

电商中的订单支付(内网穿透)

支付页面 接口文档 Operation(summary"获取订单信息") GetMapping("auth/{orderId}") public Reuslt<OrderInfo> getOrderInfo(Parameter(name"orderId",description"订单id",requiredtrue) PathVaariable Long orderId){OrderI…

MySQL表的使用(4)

首先回顾一下之前所学的增删查改&#xff0c;这些覆盖了平时使用的80% 我们上节课中学习到了MySQL的约束 其中Primary key 是主键约束&#xff0c;我们今天要学习的是外键约束 插入一个表 外键约束 父表 子表 这条记录中classid为5时候&#xff0c;不能插入&#xff1b; 删除…

Kotlin作用域函数

在 Kotlin 中&#xff0c;.apply 是一个 作用域函数&#xff08;Scope Function&#xff09;&#xff0c;它允许你在一个对象的上下文中执行代码块&#xff0c;并返回该对象本身。它的设计目的是为了 对象初始化 或 链式调用 时保持代码的简洁性和可读性。 // 不使用 apply va…

C#集合List<T>与HashSet<T>的区别

在C#中&#xff0c;List和HashSet都是用于存储元素的集合&#xff0c;但它们在内部实现、用途、性能特性以及使用场景上存在一些关键区别。 内部实现 List&#xff1a;基于数组实现的&#xff0c;可以包含重复的元素&#xff0c;并且元素是按照添加的顺序存储的。 HashSet&…

Python 实现的运筹优化系统数学建模详解(最大最小化模型)

一、引言 在数学建模的实际应用里&#xff0c;最大最小化模型是一种极为关键的优化模型。它的核心目标是找出一组决策变量&#xff0c;让多个目标函数值里的最大值尽可能小。该模型在诸多领域&#xff0c;如资源分配、选址规划等&#xff0c;都有广泛的应用。本文将深入剖析最大…

数据库的种类及常见类型

一&#xff0c;数据库的种类 最常见的数据库类型分为两种&#xff0c;关系型数据库和非关系型数据库。 二&#xff0c;关系型数据库介绍 生产环境主流的关系型数据库有 Oracle、SQL Server、MySQL/MariaDB等。 关系型数据库在存储数据时实际就是采用的一张二维表&#xff0…

PE文件(十五)绑定导入表

我们在分析Windows自带的一些程序时&#xff0c;常常发现有的程序&#xff0c;如notepad&#xff0c;他的IAT表在文件加载内存前已经完成绑定&#xff0c;存储了函数的地址。这样做可以使得程序是无需修改IAT表而直接启动&#xff0c;这时程序启动速度变快。但这种方式只适用于…

计算机网络分层模型:架构与原理

前言 计算机网络通过不同的层次结构来实现通信和数据传输&#xff0c;这种分层设计不仅使得网络更加模块化和灵活&#xff0c;也使得不同类型的通信能够顺利进行。在网络协议和通信体系中&#xff0c;最广为人知的分层模型有 OSI模型 和 TCP/IP模型。这两种模型分别定义了计算…

Ollama模型显存管理机制解析与Flask部署方案对比

一、Ollama显存释放机制 Ollama部署模型后&#xff0c;显存占用分为两种情况&#xff1a; 首次调用后短暂闲置&#xff08;约5分钟内&#xff09;&#xff1a; • 释放KV Cache等中间计算数据&#xff08;约回收30%-50%显存&#xff09;。 • 模型权重仍保留在显存中&#xf…

KWDB创作者计划—KWDB技术重构:重新定义数据与知识的神经符号革命

引言&#xff1a;数据洪流中的范式危机 在AI算力突破千卡集群、大模型参数量级迈向万亿的时代&#xff0c;传统数据库系统正面临前所未有的范式危机。当GPT-4展现出跨领域推理能力&#xff0c;AlphaFold3突破蛋白质预测精度时&#xff0c;数据存储系统却仍在沿用基于关系代数的…