PSP - 解决 ESMFold 推理长序列蛋白质结构的显存溢出问题

2023-11-30 13:36

本文主要是介绍PSP - 解决 ESMFold 推理长序列蛋白质结构的显存溢出问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

欢迎关注我的CSDN:https://spike.blog.csdn.net/
本文地址:https://spike.blog.csdn.net/article/details/134709211

IMG

使用 ESMFold 推理长序列 (Seq. Len. > 1500) 时,导致显存不足,需要设置 chunk_size 参数,实现长序列蛋白质的结构预测,避免显存溢出。

ESMFold:https://github.com/facebookresearch/esm

测试 ESM 单条 Case,序列长度 1543 较长,即:

python -u myscripts/esmfold_infer.py \
-f fasta_446/7WY5_R1543.fasta \
-o mydata/test_gpcr/

A100 显存溢出:

Tried to allocate 54.74 GiB (GPU 0; 79.32 GiB total capacity; 73.53 GiB already allocated; 3.94 GiB free; 74.24 GiB reserved in total by PyTorch)

解决显存问题,参考:Out of memory - upper limit on sequence length?

关键参数:chunk-size

Chunks axial attention computation to reduce memory usage from O(L^2) to O(L). Equivalent to running a for loop over chunks of of each dimension. Lower values will result in lower memory usage at the cost of speed. Recommended values: 128, 64, 32. Default: None.将轴向注意力计算分块 (Chunks) ,将内存使用量从 O(L^2) 减少到 O(L)。 相当于在每个维度的块上运行 for 循环。 较低的值将导致内存使用量降低,但代价是速度。 建议值:128、64、32。默认值:无。

关键参数:max-tokens-per-batch,即 max_tokens_per_batch

Maximum number of tokens per gpu forward-pass. This will group shorter sequences together for batched prediction. Lowering this can help with out of memory issues, if these occur on short sequences.每个 GPU 前向传递的最大令牌数。 这会将较短的序列分组在一起以进行批量预测。 如果内存不足问题发生在短序列上,降低此值可以帮助解决这些问题。

chunk-size 设置成 128,问题解决,即:

max_len = 1200
# A100 最多支持 1200 长度的序列
if len(seq) > max_len:chunk_size = 128print(f"[Warning] seq length is too long! {len(seq)} > {max_len}, chunk_size: {chunk_size}")self.model.set_chunk_size(chunk_size)
else:self.model.set_chunk_size(None)with torch.no_grad():output = self.model.infer_pdb(seq)

推理脚本:

#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2022. All rights reserved.
Created by C. L. Wang on 2023/7/5
"""
import argparse
import os
import sys
import time
from pathlib import Pathimport torch
from tqdm import tqdmimport esmp = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if p not in sys.path:sys.path.append(p)from myutils.protein_utils import get_seq_from_fasta
from myutils.project_utils import time_elapsed, mkdir_if_not_exist, traverse_dir_filesclass EsmfoldInfer(object):"""ESMFold的推理类"""def __init__(self):print("[Info] 开始加载 ESMFold 模型!")s_time = time.time()model = esm.pretrained.esmfold_v1()self.model = model.eval().cuda()print(f"[Info] vocab: {self.model.esm_dict.to_dict()}")# 耗时: 00:01:13.264272print(f"[Info] 完成加载 ESMFold 模型! 耗时: {time_elapsed(s_time, time.time())}")def predict_seq(self, seq, out_path, is_log=True):"""预测序列"""print(f"[Info] seq_len: {len(seq)}")max_len = 1200# A100 最多支持 1200 长度的序列if len(seq) > max_len:chunk_size = 128print(f"[Warning] seq length is too long! {len(seq)} > {max_len}, chunk_size: {chunk_size}")self.model.set_chunk_size(chunk_size)else:self.model.set_chunk_size(None)s_time = time.time()with torch.no_grad():output = self.model.infer_pdb(seq)seq_len = len(seq)if is_log:print(f"[Info] 完成推理,链长 {seq_len}, 耗时: {time_elapsed(s_time, time.time())}, "f"平均序列耗时: {(time.time() - s_time) / seq_len}")with open(out_path, "w") as f:f.write(output)if is_log:print(f"[Info] 输出: {output}")def predict_fasta_dir(self, input_path, output_dir):"""预测 FASTA 文件夹"""print(f"[Info] input_path: {input_path}")print(f"[Info] output_dir: {output_dir}")assert os.path.isfile(input_path) or os.path.isdir(input_path)mkdir_if_not_exist(output_dir)if os.path.isdir(input_path):path_list = traverse_dir_files(input_path, ext="fasta")elif os.path.isfile(input_path):path_list = [input_path]else:raise Exception(f"Error input: {input_path}")print(f"[Info] Fasta 数量: {len(path_list)}")s_time = time.time()for path in tqdm(path_list, desc="[Info] fasta"):fasta_name = os.path.basename(path).split(".")[0]output_fasta_dir = os.path.join(output_dir, fasta_name)mkdir_if_not_exist(output_fasta_dir)pdb_name = os.path.basename(path).replace("fasta", "pdb")output_pdb_path = os.path.join(output_fasta_dir, pdb_name)if os.path.exists(output_pdb_path):print(f"[Info] 已预测完成: {output_pdb_path}")continueseqs, _ = get_seq_from_fasta(path)seq = seqs[0]self.predict_seq(seq, output_pdb_path, is_log=False)print(f"[Info] 全部运行完成: {output_dir}, 耗时: {time_elapsed(s_time, time.time())}")def main():parser = argparse.ArgumentParser()parser.add_argument("-f","--fasta-input",type=Path,required=True,)parser.add_argument("-o","--output-dir",type=Path,required=True)args = parser.parse_args()fasta_input = str(args.fasta_input)output_dir = str(args.output_dir)mkdir_if_not_exist(output_dir)ei = EsmfoldInfer()ei.predict_fasta_dir(fasta_input, output_dir)if __name__ == '__main__':main()

这篇关于PSP - 解决 ESMFold 推理长序列蛋白质结构的显存溢出问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/437222

相关文章

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

mybatis和mybatis-plus设置值为null不起作用问题及解决

《mybatis和mybatis-plus设置值为null不起作用问题及解决》Mybatis-Plus的FieldStrategy主要用于控制新增、更新和查询时对空值的处理策略,通过配置不同的策略类型... 目录MyBATis-plusFieldStrategy作用FieldStrategy类型每种策略的作

linux下多个硬盘划分到同一挂载点问题

《linux下多个硬盘划分到同一挂载点问题》在Linux系统中,将多个硬盘划分到同一挂载点需要通过逻辑卷管理(LVM)来实现,首先,需要将物理存储设备(如硬盘分区)创建为物理卷,然后,将这些物理卷组成... 目录linux下多个硬盘划分到同一挂载点需要明确的几个概念硬盘插上默认的是非lvm总结Linux下多

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

pip install jupyterlab失败的原因问题及探索

《pipinstalljupyterlab失败的原因问题及探索》在学习Yolo模型时,尝试安装JupyterLab但遇到错误,错误提示缺少Rust和Cargo编译环境,因为pywinpty包需要它... 目录背景问题解决方案总结背景最近在学习Yolo模型,然后其中要下载jupyter(有点LSVmu像一个

Goland debug失效详细解决步骤(合集)

《Golanddebug失效详细解决步骤(合集)》今天用Goland开发时,打断点,以debug方式运行,发现程序并没有断住,程序跳过了断点,直接运行结束,网上搜寻了大量文章,最后得以解决,特此在这... 目录Bug:Goland debug失效详细解决步骤【合集】情况一:Go或Goland架构不对情况二:

解决jupyterLab打开后出现Config option `template_path`not recognized by `ExporterCollapsibleHeadings`问题

《解决jupyterLab打开后出现Configoption`template_path`notrecognizedby`ExporterCollapsibleHeadings`问题》在Ju... 目录jupyterLab打开后出现“templandroidate_path”相关问题这是 tensorflo

如何解决Pycharm编辑内容时有光标的问题

《如何解决Pycharm编辑内容时有光标的问题》文章介绍了如何在PyCharm中配置VimEmulator插件,包括检查插件是否已安装、下载插件以及安装IdeaVim插件的步骤... 目录Pycharm编辑内容时有光标1.如果Vim Emulator前面有对勾2.www.chinasem.cn如果tools工

Python中顺序结构和循环结构示例代码

《Python中顺序结构和循环结构示例代码》:本文主要介绍Python中的条件语句和循环语句,条件语句用于根据条件执行不同的代码块,循环语句用于重复执行一段代码,文章还详细说明了range函数的使... 目录一、条件语句(1)条件语句的定义(2)条件语句的语法(a)单分支 if(b)双分支 if-else(

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动