serve_openai_api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import argparse
  2. import json
  3. import re
  4. import os
  5. import sys
  6. __package__ = "scripts"
  7. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  8. import time
  9. import torch
  10. import warnings
  11. import uvicorn
  12. from threading import Thread
  13. from queue import Queue
  14. from fastapi import FastAPI, HTTPException
  15. from fastapi.responses import StreamingResponse
  16. from pydantic import BaseModel, Field
  17. from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
  18. from model.model_minimind import MiniMindConfig, MiniMindForCausalLM
  19. from model.model_lora import apply_lora, load_lora
  20. warnings.filterwarnings('ignore')
  21. app = FastAPI()
  22. def init_model(args):
  23. tokenizer = AutoTokenizer.from_pretrained(args.load_from)
  24. if os.path.basename(os.path.normpath(args.load_from)) == 'model':
  25. moe_suffix = '_moe' if args.use_moe else ''
  26. ckp = f'../{args.save_dir}/{args.weight}_{args.hidden_size}{moe_suffix}.pth'
  27. model = MiniMindForCausalLM(MiniMindConfig(
  28. hidden_size=args.hidden_size,
  29. num_hidden_layers=args.num_hidden_layers,
  30. max_seq_len=args.max_seq_len,
  31. use_moe=bool(args.use_moe),
  32. inference_rope_scaling=args.inference_rope_scaling
  33. ))
  34. model.load_state_dict(torch.load(ckp, map_location=device), strict=True)
  35. if args.lora_weight != 'None':
  36. apply_lora(model, rank=args.lora_rank)
  37. load_lora(model, f'../{args.save_dir}/{args.lora_weight}_{args.hidden_size}{moe_suffix}.pth')
  38. else:
  39. model = AutoModelForCausalLM.from_pretrained(args.load_from, trust_remote_code=True)
  40. print(f'MiniMind模型参数量: {sum(p.numel() for p in model.parameters()) / 1e6:.2f} M(illion)')
  41. return model.half().eval().to(device), tokenizer
  42. class ChatRequest(BaseModel):
  43. model: str
  44. messages: list
  45. temperature: float = 0.7
  46. top_p: float = 0.92
  47. max_tokens: int = 8192
  48. stream: bool = True
  49. tools: list = Field(default_factory=list)
  50. open_thinking: bool = False
  51. chat_template_kwargs: dict = None
  52. def get_open_thinking(self) -> bool:
  53. """兼容多种方式开启 thinking"""
  54. if self.open_thinking:
  55. return True
  56. if self.chat_template_kwargs:
  57. return self.chat_template_kwargs.get('open_thinking', False) or \
  58. self.chat_template_kwargs.get('enable_thinking', False)
  59. return False
  60. class CustomStreamer(TextStreamer):
  61. def __init__(self, tokenizer, queue):
  62. super().__init__(tokenizer, skip_prompt=True, skip_special_tokens=True)
  63. self.queue = queue
  64. self.tokenizer = tokenizer
  65. def on_finalized_text(self, text: str, stream_end: bool = False):
  66. self.queue.put(text)
  67. if stream_end:
  68. self.queue.put(None)
  69. def parse_response(text):
  70. reasoning_content = None
  71. think_match = re.search(r'<think>(.*?)</think>', text, re.DOTALL)
  72. if think_match:
  73. reasoning_content = think_match.group(1).strip()
  74. text = re.sub(r'<think>.*?</think>\s*', '', text, flags=re.DOTALL)
  75. elif '</think>' in text:
  76. parts = text.split('</think>', 1)
  77. reasoning_content = parts[0].strip()
  78. text = parts[1].strip() if len(parts) > 1 else ''
  79. tool_calls = []
  80. for i, m in enumerate(re.findall(r'<tool_call>(.*?)</tool_call>', text, re.DOTALL)):
  81. try:
  82. call = json.loads(m.strip())
  83. tool_calls.append({"id": f"call_{int(time.time())}_{i}", "type": "function", "function": {"name": call.get("name", ""), "arguments": json.dumps(call.get("arguments", {}), ensure_ascii=False)}})
  84. except Exception:
  85. pass
  86. if tool_calls:
  87. text = re.sub(r'<tool_call>.*?</tool_call>', '', text, flags=re.DOTALL)
  88. return text.strip(), reasoning_content, tool_calls or None
  89. def generate_stream_response(messages, temperature, top_p, max_tokens, tools=None, open_thinking=False):
  90. try:
  91. new_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, tools=tools or None, open_thinking=open_thinking)
  92. inputs = tokenizer(new_prompt, return_tensors="pt", truncation=True).to(device)
  93. queue = Queue()
  94. streamer = CustomStreamer(tokenizer, queue)
  95. def _generate():
  96. try:
  97. model.generate(
  98. inputs.input_ids,
  99. max_new_tokens=max_tokens,
  100. do_sample=True,
  101. temperature=temperature,
  102. top_p=top_p,
  103. attention_mask=inputs.attention_mask,
  104. pad_token_id=tokenizer.pad_token_id,
  105. eos_token_id=tokenizer.eos_token_id,
  106. streamer=streamer
  107. )
  108. except Exception as e:
  109. queue.put({"error": str(e)})
  110. queue.put(None)
  111. Thread(target=_generate).start()
  112. pending = ""
  113. in_tool_call = False
  114. tool_count = 0
  115. thinking_ended = not bool(open_thinking)
  116. strip_newlines = False
  117. while True:
  118. text = queue.get()
  119. if text is None:
  120. break
  121. if isinstance(text, dict):
  122. yield json.dumps(text, ensure_ascii=False)
  123. continue
  124. pending += text
  125. while pending:
  126. if strip_newlines:
  127. pending = pending.lstrip('\n')
  128. if not pending:
  129. break
  130. strip_newlines = False
  131. if in_tool_call:
  132. end = pending.find('</tool_call>')
  133. if end < 0:
  134. break
  135. end += len('</tool_call>')
  136. block, pending = pending[:end], pending[end:]
  137. _, _, tool_calls = parse_response(block)
  138. if tool_calls:
  139. call = tool_calls[0]
  140. call['index'] = tool_count
  141. call['id'] = f"call_{int(time.time())}_{tool_count}"
  142. tool_count += 1
  143. yield json.dumps({"choices": [{"delta": {"tool_calls": [call]}}]}, ensure_ascii=False)
  144. else:
  145. yield json.dumps({"choices": [{"delta": {"content": block}}]}, ensure_ascii=False)
  146. in_tool_call = False
  147. continue
  148. marker = '<tool_call>' if thinking_ended else '</think>'
  149. field = 'content' if thinking_ended else 'reasoning_content'
  150. pos = pending.find(marker)
  151. if pos < 0:
  152. keep = next((n for n in range(len(marker) - 1, 0, -1)
  153. if pending.endswith(marker[:n])), 0)
  154. end = len(pending) - keep
  155. if end:
  156. yield json.dumps({"choices": [{"delta": {field: pending[:end]}}]}, ensure_ascii=False)
  157. pending = pending[end:]
  158. break
  159. if pos:
  160. yield json.dumps({"choices": [{"delta": {field: pending[:pos]}}]}, ensure_ascii=False)
  161. pending = pending[pos:]
  162. if thinking_ended:
  163. in_tool_call = True
  164. else:
  165. pending = pending[len(marker):]
  166. thinking_ended = True
  167. strip_newlines = True
  168. if pending:
  169. field = 'content' if thinking_ended else 'reasoning_content'
  170. yield json.dumps({"choices": [{"delta": {field: pending}}]}, ensure_ascii=False)
  171. yield json.dumps({"choices": [{"delta": {}, "finish_reason": "tool_calls" if tool_count else "stop"}]}, ensure_ascii=False)
  172. except Exception as e:
  173. yield json.dumps({"error": str(e)})
  174. @app.post("/v1/chat/completions")
  175. async def chat_completions(request: ChatRequest):
  176. try:
  177. if request.stream:
  178. return StreamingResponse(
  179. (f"data: {chunk}\n\n" for chunk in generate_stream_response(
  180. messages=request.messages,
  181. temperature=request.temperature,
  182. top_p=request.top_p,
  183. max_tokens=request.max_tokens,
  184. tools=request.tools,
  185. open_thinking=request.get_open_thinking()
  186. )),
  187. media_type="text/event-stream"
  188. )
  189. else:
  190. new_prompt = tokenizer.apply_chat_template(
  191. request.messages,
  192. tokenize=False,
  193. add_generation_prompt=True,
  194. tools=request.tools or None,
  195. open_thinking=request.get_open_thinking()
  196. )
  197. inputs = tokenizer(new_prompt, return_tensors="pt", truncation=True).to(device)
  198. with torch.no_grad():
  199. generated_ids = model.generate(
  200. inputs["input_ids"],
  201. max_new_tokens=request.max_tokens,
  202. do_sample=True,
  203. attention_mask=inputs["attention_mask"],
  204. pad_token_id=tokenizer.pad_token_id,
  205. eos_token_id=tokenizer.eos_token_id,
  206. top_p=request.top_p,
  207. temperature=request.temperature
  208. )
  209. answer = tokenizer.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
  210. content, reasoning_content, tool_calls = parse_response(answer)
  211. message = {"role": "assistant", "content": content}
  212. if reasoning_content:
  213. message["reasoning_content"] = reasoning_content
  214. if tool_calls:
  215. message["tool_calls"] = tool_calls
  216. return {
  217. "id": f"chatcmpl-{int(time.time())}",
  218. "object": "chat.completion",
  219. "created": int(time.time()),
  220. "model": "minimind",
  221. "choices": [
  222. {
  223. "index": 0,
  224. "message": message,
  225. "finish_reason": "tool_calls" if tool_calls else "stop"
  226. }
  227. ]
  228. }
  229. except Exception as e:
  230. raise HTTPException(status_code=500, detail=str(e))
  231. if __name__ == "__main__":
  232. parser = argparse.ArgumentParser(description="Server for MiniMind")
  233. parser.add_argument('--load_from', default='../model', type=str, help="模型加载路径(model=原生torch权重,其他路径=transformers格式)")
  234. parser.add_argument('--save_dir', default='out', type=str, help="模型权重目录")
  235. parser.add_argument('--weight', default='full_sft', type=str, help="权重名称前缀(pretrain, full_sft, dpo, reason, ppo_actor, grpo, spo)")
  236. parser.add_argument('--lora_weight', default='None', type=str, help="LoRA权重名称(None表示不使用,可选:lora_identity, lora_medical)")
  237. parser.add_argument('--lora_rank', default=16, type=int, help="LoRA rank,需与训练时一致(默认16)")
  238. parser.add_argument('--hidden_size', default=768, type=int, help="隐藏层维度")
  239. parser.add_argument('--num_hidden_layers', default=8, type=int, help="隐藏层数量")
  240. parser.add_argument('--max_seq_len', default=8192, type=int, help="最大序列长度")
  241. parser.add_argument('--use_moe', default=0, type=int, choices=[0, 1], help="是否使用MoE架构(0=否,1=是)")
  242. parser.add_argument('--inference_rope_scaling', default=False, action='store_true', help="启用RoPE位置编码外推(4倍,仅解决位置编码问题)")
  243. parser.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu', type=str, help="运行设备")
  244. args = parser.parse_args()
  245. device = args.device
  246. model, tokenizer = init_model(args)
  247. uvicorn.run(app, host="0.0.0.0", port=8998)