serve_openai_api.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 'model' in args.load_from:
  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)
  37. load_lora(model, f'../{args.save_dir}/lora/{args.lora_weight}_{args.hidden_size}.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. full_text = ""
  113. emitted = 0
  114. thinking_ended = not bool(open_thinking)
  115. while True:
  116. text = queue.get()
  117. if text is None:
  118. break
  119. if isinstance(text, dict):
  120. yield json.dumps(text, ensure_ascii=False)
  121. continue
  122. full_text += text
  123. if not thinking_ended:
  124. pos = full_text.find('</think>')
  125. if pos >= 0:
  126. thinking_ended = True
  127. new_r = full_text[emitted:pos]
  128. if new_r:
  129. yield json.dumps({"choices": [{"delta": {"reasoning_content": new_r}}]}, ensure_ascii=False)
  130. emitted = pos + len('</think>')
  131. after = full_text[emitted:].lstrip('\n')
  132. emitted = len(full_text) - len(after)
  133. if after:
  134. yield json.dumps({"choices": [{"delta": {"content": after}}]}, ensure_ascii=False)
  135. emitted = len(full_text)
  136. else:
  137. new_r = full_text[emitted:]
  138. if new_r:
  139. yield json.dumps({"choices": [{"delta": {"reasoning_content": new_r}}]}, ensure_ascii=False)
  140. emitted = len(full_text)
  141. else:
  142. new_c = full_text[emitted:]
  143. if new_c:
  144. yield json.dumps({"choices": [{"delta": {"content": new_c}}]}, ensure_ascii=False)
  145. emitted = len(full_text)
  146. _, _, tool_calls = parse_response(full_text)
  147. if tool_calls:
  148. yield json.dumps({"choices": [{"delta": {"tool_calls": tool_calls}}]}, ensure_ascii=False)
  149. yield json.dumps({"choices": [{"delta": {}, "finish_reason": "tool_calls" if tool_calls else "stop"}]}, ensure_ascii=False)
  150. except Exception as e:
  151. yield json.dumps({"error": str(e)})
  152. @app.post("/v1/chat/completions")
  153. async def chat_completions(request: ChatRequest):
  154. try:
  155. if request.stream:
  156. return StreamingResponse(
  157. (f"data: {chunk}\n\n" for chunk in generate_stream_response(
  158. messages=request.messages,
  159. temperature=request.temperature,
  160. top_p=request.top_p,
  161. max_tokens=request.max_tokens,
  162. tools=request.tools,
  163. open_thinking=request.get_open_thinking()
  164. )),
  165. media_type="text/event-stream"
  166. )
  167. else:
  168. new_prompt = tokenizer.apply_chat_template(
  169. request.messages,
  170. tokenize=False,
  171. add_generation_prompt=True,
  172. tools=request.tools or None,
  173. open_thinking=request.get_open_thinking()
  174. )
  175. inputs = tokenizer(new_prompt, return_tensors="pt", truncation=True).to(device)
  176. with torch.no_grad():
  177. generated_ids = model.generate(
  178. inputs["input_ids"],
  179. max_new_tokens=request.max_tokens,
  180. do_sample=True,
  181. attention_mask=inputs["attention_mask"],
  182. pad_token_id=tokenizer.pad_token_id,
  183. eos_token_id=tokenizer.eos_token_id,
  184. top_p=request.top_p,
  185. temperature=request.temperature
  186. )
  187. answer = tokenizer.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
  188. content, reasoning_content, tool_calls = parse_response(answer)
  189. message = {"role": "assistant", "content": content}
  190. if reasoning_content:
  191. message["reasoning_content"] = reasoning_content
  192. if tool_calls:
  193. message["tool_calls"] = tool_calls
  194. return {
  195. "id": f"chatcmpl-{int(time.time())}",
  196. "object": "chat.completion",
  197. "created": int(time.time()),
  198. "model": "minimind",
  199. "choices": [
  200. {
  201. "index": 0,
  202. "message": message,
  203. "finish_reason": "tool_calls" if tool_calls else "stop"
  204. }
  205. ]
  206. }
  207. except Exception as e:
  208. raise HTTPException(status_code=500, detail=str(e))
  209. if __name__ == "__main__":
  210. parser = argparse.ArgumentParser(description="Server for MiniMind")
  211. parser.add_argument('--load_from', default='../model', type=str, help="模型加载路径(model=原生torch权重,其他路径=transformers格式)")
  212. parser.add_argument('--save_dir', default='out', type=str, help="模型权重目录")
  213. parser.add_argument('--weight', default='full_sft', type=str, help="权重名称前缀(pretrain, full_sft, dpo, reason, ppo_actor, grpo, spo)")
  214. parser.add_argument('--lora_weight', default='None', type=str, help="LoRA权重名称(None表示不使用,可选:lora_identity, lora_medical)")
  215. parser.add_argument('--hidden_size', default=768, type=int, help="隐藏层维度")
  216. parser.add_argument('--num_hidden_layers', default=8, type=int, help="隐藏层数量")
  217. parser.add_argument('--max_seq_len', default=8192, type=int, help="最大序列长度")
  218. parser.add_argument('--use_moe', default=0, type=int, choices=[0, 1], help="是否使用MoE架构(0=否,1=是)")
  219. parser.add_argument('--inference_rope_scaling', default=False, action='store_true', help="启用RoPE位置编码外推(4倍,仅解决位置编码问题)")
  220. parser.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu', type=str, help="运行设备")
  221. args = parser.parse_args()
  222. device = args.device
  223. model, tokenizer = init_model(args)
  224. uvicorn.run(app, host="0.0.0.0", port=8998)