serve_openai_api.py 12 KB

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