NPU流式输出-torch_npu和transformers框架-多线程Streamer-昇腾910B-EE1001

前情提要

torch_npu框架不支持多线程自动set_device

报错详情

直接使用transformers的TextIteratorStreamer进行流式推理,会报错

Exception in thread Thread-6:
Traceback (most recent call last):
  File "/root/anaconda3/envs/AI/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/root/anaconda3/envs/AI/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "/root/anaconda3/envs/AI/lib/python3.9/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
    return func(*args, **kwargs)
  File "/root/anaconda3/envs/AI/lib/python3.9/site-packages/transformers/generation/utils.py", line 1403, in generate
    and torch.sum(inputs_tensor[:, -1] == generation_config.pad_token_id) > 0
RuntimeError: getDevice:torch_npu/csrc/aten/common/CopyKernel.cpp:41 NPU error, error code is 107002
[Error]: The context is empty.
        Check whether acl.rt.set_context or acl.rt.set_device is called.
EE1001: The argument is invalid.Reason: rtGetDevMsg execute failed, reason=[context pointer null]
        Solution: 1.Check the input parameter range of the function. 2.Check the function invocation relationship.
        TraceBack (most recent call last):
        ctx is NULL![FUNC:GetDevErrMsg][FILE:api_impl.cc][LINE:4686]
        The argument is invalid.Reason: rtGetDevMsg execute failed, reason=[context pointer null]

设置好generation_config后,报错变为

Exception in thread Thread-6:
Traceback (most recent call last):
  File "/root/anaconda3/envs/sakura/lib/python3.9/threading.py", line 954, in _bootstrap_inner
    self.run()
  File "/root/anaconda3/envs/sakura/lib/python3.9/threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "/root/anaconda3/envs/sakura/lib/python3.9/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
    return func(*args, **kwargs)
  File "/root/anaconda3/envs/sakura/lib/python3.9/site-packages/transformers/generation/utils.py", line 1411, in generate
    streamer.put(input_ids.cpu())
RuntimeError: getDevice:torch_npu/csrc/aten/common/CopyKernel.cpp:41 NPU error, error code is 107002
[Error]: The context is empty.
        Check whether acl.rt.set_context or acl.rt.set_device is called.
EE1001: The argument is invalid.Reason: rtGetDevMsg execute failed, reason=[context pointer null]
        Solution: 1.Check the input parameter range of the function. 2.Check the function invocation relationship.
        TraceBack (most recent call last):
        ctx is NULL![FUNC:GetDevErrMsg][FILE:api_impl.cc][LINE:4686]
        The argument is invalid.Reason: rtGetDevMsg execute failed, reason=[context pointer null]

为此咨询了transformers官方人员,issues-23042,但是他们无法处理
在这里插入图片描述

后来经过不断debug发现在threading.py的Thread函数中,执行run函数后self._kwargs中的参数均未传递成功
在这里插入图片描述
询问了torch_npu的官方人员
在这里插入图片描述

解决方案

在Thread函数中的target传入set_device
完整代码如下,以chatglm3-6b为例

import torch
import torch_npu
from torch_npu.contrib import transfer_to_npu
torch_device = "npu:3"
torch.npu.set_device(torch.device(torch_device))
torch.npu.set_compile_mode(jit_compile=False)
option = {}
option["NPU_FUZZY_COMPILE_BLACKLIST"] = "Tril"
torch.npu.set_option(option)
import os
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer, AutoModel
from transformers import TextIteratorStreamer
from threading import Thread
 
model_path = "/root/.cache/modelscope/hub/ZhipuAI/chatglm3-6b" 
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModel.from_pretrained(model_path, trust_remote_code=True, device_map=torch_device)
model = model.eval()
 

def generate_with_npu_device(**generation_kwargs):
    torch.npu.set_device(torch.device(torch_device))
    model.generate(**generation_kwargs)


if __name__ == "__main__":
     # TextIteratorStreamer实现
    streamer = TextIteratorStreamer(tokenizer)
    turn_count = 0
    while True:
        query = input("\n用户:")
        if query.strip() == "stop":
            break
        inputs = tokenizer([query], return_tensors="pt")
        input_ids = inputs["input_ids"].to(torch_device)
        attention_mask = inputs["attention_mask"].to(torch_device)
        generation_kwargs = dict(input_ids=input_ids,
            						attention_mask=attention_mask, 
            						streamer=streamer, 
            						max_new_tokens=512)
        thread = Thread(target=generate_with_npu_device, kwargs=generation_kwargs)
        thread.start()
        generated_text = ""
        position = 0
        # 流式输出
        for new_text in streamer:
            generated_text += new_text
            print(generated_text[position:], end='', flush=True)
            position = len(generated_text)

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Linux shell 脚本基础与部署SpringCloud实战

博主介绍:✌全网粉丝5W,全栈开发工程师,从事多年软件开发,在大厂呆过。持有软件中级、六级等证书。可提供微服务项目搭建与毕业项目实战,博主也曾写过优秀论文,查重率极低,在这方面有丰富的经验…

L2正则化——解释为什么可以减少模型的复杂度

L2正则化是一种用于机器学习模型的技术,旨在减少模型的复杂度,从而提高其泛化能力。在L2正则化中,通过添加一个惩罚项,模型的权重被迫保持较小的值,这有助于防止过拟合,即模型在训练数据上表现良好但在未见…

python学习笔记B-07:序列结构之列表--列表的常用函数和方法

以xx_函数名(列表名)的形式出现的是函数;以xx_列表名.xx_方法名的形式出现的是方法。 列表常用函数如下: len():计算列表元素数量 max():获取列表元素最大值 min():获取列表元素最小值 sum():计算列表中各元素之和 列表常用方法如…

【Java EE】文件操作

目录 1.认识文件 2.树型结构组织和目录 3.文件路径(Path) 4.其他知识 5.Java中操作文件 5.1File概述 5.1.1属性 5.1.2构造方法 5.1.3方法 5.2代码示例 1.认识文件 我们先来认识狭义的文件(file)。针对1硬盘这种持久化存…

HTML重要标签梳理学习

1、HTML文件的框架 使用VS Code编码时&#xff0c;输入!选中第一个&#xff01;就可以快速生成一个HTML文件框架。 2、标签 <hr> <!--下划线--> <br> <!--换行--> <strong>加粗</strong> &…

MySQL行级锁——技术深度+1

引言 本文是对MySQL行级锁的学习&#xff0c;MySQL一直停留在会用的阶段&#xff0c;需要弄清楚锁和事务的原理并DEBUG查看。 PS:本文涉及到的表结构均可从https://github.com/WeiXiao-Hyy/blog中获取&#xff0c;欢迎Star&#xff01; MySQL行级锁 行级锁&#xff08;Row-…

案例研究 | JumpServer助力天虹股份构建可靠的运维安全审计平台

天虹数科商业股份有限公司&#xff08;以下简称为“天虹股份”&#xff09;成立于1984年&#xff0c;是国有控股的上市公司。通过人本、科学的管理&#xff0c;以及专业、高效的运营&#xff0c;天虹股份连续多年入围中国连锁百强企业&#xff0c;拥有全国领先的零售技术研发和…

vue3 项目启动时vite版本问题报错

背景&#xff1a; 我是在项目迁移过程中遇到的这个问题&#xff0c;前提可以看下面这篇 http://t.csdnimg.cn/g70Eq 问题描述 迁移项目时&#xff0c;将项目整体升级到了vue3版本&#xff0c;启动项目时出现下列报错&#xff1a; npm ERR! Found: vite5.1.4 npm ERR! node_…

2024-2.基础操作-Python

Jupiter基本使用 cell有两种模式&#xff1a; codemarkdown 快捷键 新建cell&#xff1a;a,b删除cell&#xff1a;dd&#xff0c;x运行cell&#xff1a;shiftenter切换cell模式&#xff1a; m&#xff1a;将code模式的cell切换到mdy:将md模式的cell切换到code 智能补全&#x…

QT Webengine开发过程报错qml: Render process exited with code 159 (killed)

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、解决方法二、补充说明总结 前言 提示&#xff1a;这里可以添加本文要记录的大概内容&#xff1a; 基于QT的Webengine开发过程中&#xff0c;QT的官方示例…

【算法】反转链表

本题来源---《反转链表》 题目描述&#xff1a; 给你单链表的头节点 head &#xff0c;请你反转链表&#xff0c;并返回反转后的链表。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5] 输出&#xff1a;[5,4,3,2,1]示例 2&#xff1a; 输入&#xff1a;head [1,2] 输…

22长安杯电子取证复现(检材一,二)

检材一 先用VC容器挂载&#xff0c;拿到完整的检材 从检材一入手&#xff0c;火眼创建案件&#xff0c;打开检材一 1.检材1的SHA256值为 计算SHA256值&#xff0c;直接用火眼计算哈希计算 9E48BB2CAE5C1D93BAF572E3646D2ECD26080B70413DC7DC4131F88289F49E34 2.分析检材1&am…

50.HarmonyOS鸿蒙系统 App(ArkUI)web组件实现简易浏览器

50.HarmonyOS鸿蒙系统 App(ArkUI)web组件实现简易浏览器 配置网络访问权限&#xff1a; 跳转任务&#xff1a; Button(转到).onClick(() > {try {// 点击按钮时&#xff0c;通过loadUrl&#xff0c;跳转到www.example1.comthis.webviewController.loadUrl(this.get_url);} …

Root mapping definition has unsupported parameters: [all : {analyzer=ik_max_wor

你们好&#xff0c;我是金金金。 场景 我正在使用Springboot整合elasticsearch&#xff0c;在创建索引(分词器) 运行报错&#xff0c;如下 排查 排查之前我先贴一下代码 import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; // 注意这个包SpringBootTe…

Linux中如何安装ImageMagick及其常规使用命令

在Linux中安装ImageMagick可以通过包管理工具进行安装。具体步骤如下&#xff1a; 打开终端&#xff08;Terminal&#xff09;。 使用以下命令更新系统软件包列表&#xff1a; sudo apt update使用以下命令安装ImageMagick&#xff1a; sudo apt install imagemagick安装完…

物理机安装centos7并配置基本环境,网络配置,docker配置

1.首先下载镜像Download 2.下载UltraISO 安装docker 第1步&#xff1a;卸载当前版本docker yum erase docker \docker-client \docker-client-latest \docker-common \docker-latest \docker-latest-logrotate \docker-logrotate \docker-selinux \docker-engine-selinux \do…

[生活][杂项] 如何正确打开编织袋

编织袋打开的正确姿势 面对单线分离右边的线头&#xff0c;然后依次拉开即可

YAML教程-1-基础入门

领取资料&#xff0c;咨询答疑&#xff0c;请➕wei: June__Go YAML简介 YAML&#xff08;YAML Aint Markup Language&#xff09;是一种用于数据序列化的人类可读格式。它广泛用于配置文件、数据交换、持续集成/持续部署&#xff08;CI/CD&#xff09;等领域。YAML的设计目标…

注意,把Python库安装在一个环境里,可能会“非常危险”!

如果说谁写Python不用第三方库&#xff0c;我敬他是条汉子。如今到处是轮子的时代&#xff0c;Python第三方库管理成了开发者们头疼的问题。 可能在看这篇文章的很多人&#xff0c;都没用过Python虚拟环境&#xff0c;不知道安装Python库需要考虑版本兼容问题。 那么把所有要…

基于SpringBoot的健身房管理系统

一.前言 本系统用了 Sping Data JPA 这一不常用的数据库框架&#xff0c;是一个值得学习研究的点。 本项目用户名&#xff1a;admin 密码: admin123 方可进入。项目源码在文章开头&#xff0c;下载到本地导入IDEA&#xff0c;修改配置文件中数据库连接信息后&#xff0c;导入项…