当前位置:   article > 正文

调用本地魔塔Chatglm3的 api,FastAPI_如何把chatglm3 api生成的信息打印回来

如何把chatglm3 api生成的信息打印回来

1.创建.py文件,jupyter会报错

看自己缺什么包,补什么包

先确保自己模型加载,在当前环境下不报错。

  1. from fastapi import FastAPI
  2. from pydantic import BaseModel
  3. import uvicorn
  4. import torch
  5. import os
  6. from modelscope import AutoTokenizer, AutoModel, snapshot_download
  7. os.environ['CUDA_VISIBLE_DEVICES'] = "1,0"
  8. app = FastAPI()
  9. class Query(BaseModel):
  10. text: str
  11. model_dir = snapshot_download("ZhipuAI/chatglm3-6b-32k", revision = "v1.0.0")
  12. tokenizer = AutoTokenizer.from_pretrained("ZhipuAI/chatglm3-6b-32k", trust_remote_code=True)
  13. model = AutoModel.from_pretrained(model_dir, trust_remote_code=True).half().cuda()
  14. model = torch.nn.DataParallel(model,device_ids=[0,1])
  15. if isinstance(model,torch.nn.DataParallel):
  16. model = model.module
  17. @app.post("/chat/")
  18. async def chat(query: Query):
  19. input_ids = tokenizer([query.text]).input_ids
  20. output_ids = model.generate(
  21. torch.as_tensor(input_ids).cuda(),
  22. do_sample=False,
  23. temperature=0.1,
  24. repetition_penalty=1,
  25. max_new_tokens=1024)
  26. output_ids = output_ids[0][len(input_ids[0]):]
  27. outputs = tokenizer.decode(output_ids, skip_special_tokens=True, spaces_between_special_tokens=False)
  28. return {"result": outputs}
  29. if __name__ == "__main__":
  30. uvicorn.run(app, host="0.0.0.0", port=8060)

运行上门的文件

2.测试api 新建一个py文件

  1. import requests
  2. url = "http://0.0.0.0:8060/chat"
  3. query={'text':"hi"}
  4. response = requests.post(url, json=query)
  5. if response.status_code == 200:
  6. res = response.json()
  7. print("Chatglm3:",res["result"])
  8. else:
  9. print("error")

运行,正常返回,表示api调用成功!

查看防火墙,确保端口 8060是允许的,或者换成自己的允许的端口

查询端口状态:ufw status

坑:

当时设置环境os.environ['CUDA_VISIBLE_DEVICES'] = "1,0" 报错

torch.cuda.DeferredCudaCallError: CUDA call failed lazily at initialization 

bash重置指定显卡解决问题

unset CUDA_VISIBLE_DEVICES

并行报错:

AttributeError: ‘DataParallel’ object has no attribute ‘xxxx’

在并行后加入以下代码:

  1. if isinstance(model,torch.nn.DataParallel):
  2. model = model.module

参考文章:



【FastAPI】利用FastAPI构建大模型接口服务-CSDN博客

torch.cuda.DeferredCudaCallError: CUDA call failed lazily at initialization 报错-CSDN博客

Pytorch —— AttributeError: ‘DataParallel’ object has no attribute ‘xxxx’_attributeerror: 'dataparallel' object has no attri-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/886216
推荐阅读
相关标签
  

闽ICP备14008679号