diff --git a/.DS_Store b/.DS_Store
new file mode 100644
index 00000000..a54c2cb1
Binary files /dev/null and b/.DS_Store differ
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 00000000..13566b81
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
diff --git a/.idea/Qwen2.iml b/.idea/Qwen2.iml
new file mode 100644
index 00000000..be6d7ebb
--- /dev/null
+++ b/.idea/Qwen2.iml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/deployment.xml b/.idea/deployment.xml
new file mode 100644
index 00000000..33e90575
--- /dev/null
+++ b/.idea/deployment.xml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
new file mode 100644
index 00000000..f4f1b89d
--- /dev/null
+++ b/.idea/inspectionProfiles/Project_Default.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 00000000..105ce2da
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 00000000..15e73d82
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 00000000..5bd76de3
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 00000000..35eb1ddf
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/examples/.DS_Store b/examples/.DS_Store
new file mode 100644
index 00000000..13778cbb
Binary files /dev/null and b/examples/.DS_Store differ
diff --git a/openai_api/openai_api.py b/openai_api/openai_api.py
new file mode 100644
index 00000000..d3ee802b
--- /dev/null
+++ b/openai_api/openai_api.py
@@ -0,0 +1,646 @@
+# Requirement:
+# pip install "openai<1.0"
+# Usage:
+# python openai_api_issue.py
+# Visit http://localhost:8000/docs for documents.
+
+import base64
+import copy
+import json
+import time
+from argparse import ArgumentParser
+from contextlib import asynccontextmanager
+from pprint import pprint
+from typing import Dict, List, Literal, Optional, Union
+
+import torch
+import uvicorn
+from fastapi import FastAPI, HTTPException
+from fastapi.middleware.cors import CORSMiddleware
+from pydantic import BaseModel, Field
+from sse_starlette.sse import EventSourceResponse
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.requests import Request
+from starlette.responses import Response
+from transformers import AutoModelForCausalLM, AutoTokenizer, Qwen2ForCausalLM, Qwen2Tokenizer
+from transformers.generation import GenerationConfig
+from qwen2chat import Qwen2ForChatLM
+
+
+class BasicAuthMiddleware(BaseHTTPMiddleware):
+
+ def __init__(self, app, username: str, password: str):
+ super().__init__(app)
+ self.required_credentials = base64.b64encode(
+ f'{username}:{password}'.encode()).decode()
+
+ async def dispatch(self, request: Request, call_next):
+ authorization: str = request.headers.get('Authorization')
+ if authorization:
+ try:
+ schema, credentials = authorization.split()
+ if credentials == self.required_credentials:
+ return await call_next(request)
+ except ValueError:
+ pass
+
+ headers = {'WWW-Authenticate': 'Basic'}
+ return Response(status_code=401, headers=headers)
+
+
+def _gc(forced: bool = False):
+ global args
+ if args.disable_gc and not forced:
+ return
+
+ import gc
+
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI): # collects GPU memory
+ yield
+ _gc(forced=True)
+
+
+app = FastAPI(lifespan=lifespan)
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=['*'],
+ allow_credentials=True,
+ allow_methods=['*'],
+ allow_headers=['*'],
+)
+
+
+class ModelCard(BaseModel):
+ id: str
+ object: str = 'model'
+ created: int = Field(default_factory=lambda: int(time.time()))
+ owned_by: str = 'owner'
+ root: Optional[str] = None
+ parent: Optional[str] = None
+ permission: Optional[list] = None
+
+
+class ModelList(BaseModel):
+ object: str = 'list'
+ data: List[ModelCard] = []
+
+
+class ChatMessage(BaseModel):
+ role: Literal['user', 'assistant', 'system', 'function']
+ content: Optional[str]
+ function_call: Optional[Dict] = None
+
+
+class DeltaMessage(BaseModel):
+ role: Optional[Literal['user', 'assistant', 'system']] = None
+ content: Optional[str] = None
+
+
+class ChatCompletionRequest(BaseModel):
+ model: str
+ messages: List[ChatMessage]
+ functions: Optional[List[Dict]] = None
+ temperature: Optional[float] = None
+ top_p: Optional[float] = None
+ top_k: Optional[int] = None
+ max_length: Optional[int] = None
+ stream: Optional[bool] = False
+ stop: Optional[List[str]] = None
+
+
+class ChatCompletionResponseChoice(BaseModel):
+ index: int
+ message: Union[ChatMessage]
+ finish_reason: Literal['stop', 'length', 'function_call']
+
+
+class ChatCompletionResponseStreamChoice(BaseModel):
+ index: int
+ delta: DeltaMessage
+ finish_reason: Optional[Literal['stop', 'length']]
+
+
+class ChatCompletionResponse(BaseModel):
+ model: str
+ object: Literal['chat.completion', 'chat.completion.chunk']
+ choices: List[Union[ChatCompletionResponseChoice,
+ ChatCompletionResponseStreamChoice]]
+ created: Optional[int] = Field(default_factory=lambda: int(time.time()))
+
+
+@app.get('/v1/models', response_model=ModelList)
+async def list_models():
+ global model_args
+ model_card = ModelCard(id='gpt-3.5-turbo')
+ return ModelList(data=[model_card])
+
+
+# To work around that unpleasant leading-\n tokenization issue!
+def add_extra_stop_words(stop_words: list):
+ if stop_words:
+ _stop_words = []
+ _stop_words.extend(stop_words)
+ for x in stop_words:
+ s = x.lstrip('\n')
+ if s and (s not in _stop_words):
+ _stop_words.append(s)
+ return _stop_words
+ return stop_words
+
+
+def trim_stop_words(response: str, stop_words: list):
+ # Remove the first occurrence of the stop word and everything after it in the response
+ if stop_words:
+ for stop in stop_words:
+ idx = response.find(stop)
+ if idx != -1:
+ response = response[:idx]
+ return response
+
+
+TOOL_DESC_WITH_PARAMETERS = (
+ '{name_for_model}: Call this tool to interact with the {name_for_human} API.'
+ ' What is the {name_for_human} API useful for? {description_for_model} Parameters: {parameters}'
+)
+TOOL_DESC_NO_PARAMETERS = (
+ '{name_for_model}: Call this tool to interact with the {name_for_human} API.'
+ ' What is the {name_for_human} API useful for? {description_for_model}'
+)
+
+REACT_INSTRUCTION = """Answer the following questions as best you can. You have access to the following APIs:
+
+{tools_text}
+
+Use the following format:
+
+Question: the input question you must answer
+Thought: you should always think about what to do
+Action: the action to take, should be one of [{tools_name_text}]
+Action Input: the input to the action, if no parameters are provided, marking this as empty.
+Observation: the result of the action
+... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
+Thought: I now know the final answer
+Final Answer: the final answer to the original input question
+
+Begin!"""
+
+REACT_INSTRUCTION_NO_PARAMETERS = """Answer the following questions as best you can. You have access to the following APIs:
+
+{tools_text}
+
+Use the following format:
+
+Question: the input question you must answer
+Thought: you should always think about what to do
+Action: the action to take, should be one of [{tools_name_text}]
+Observation: the result of the action
+... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
+Thought: I now know the final answer
+Final Answer: the final answer to the original input question
+
+Begin!"""
+
+_TEXT_COMPLETION_CMD = object()
+
+
+def parse_messages(messages, functions):
+ if all(m.role != 'user' for m in messages):
+ raise HTTPException(
+ status_code=400,
+ detail='Invalid request: Expecting at least one user message.',
+ )
+
+ messages = copy.deepcopy(messages)
+ if messages[0].role == 'system':
+ system = messages.pop(0).content.lstrip('\n').rstrip()
+ else:
+ system = 'You are a helpful assistant.' # 拿出系统消息,如果没有的话用默认的
+
+ if functions:
+ tools_text = []
+ tools_name_text = []
+ for func_info in functions: # functions have 2 styles, one is qwen style, the other is openai style. here porcess the two style simultaneously.
+ name = func_info.get('name', '')
+ name_m = func_info.get('name_for_model', name)
+ name_h = func_info.get('name_for_human', name)
+ desc = func_info.get('description', '')
+ desc_m = func_info.get('description_for_model', desc)
+ if "parameters" in func_info:
+ tool = TOOL_DESC_WITH_PARAMETERS.format( # qwen style
+ name_for_model=name_m,
+ name_for_human=name_h,
+ # Hint: You can add the following format requirements in description:
+ # "Format the arguments as a JSON object."
+ # "Enclose the code within triple backticks (`) at the beginning and end of the code."
+ description_for_model=desc_m,
+ parameters=json.dumps(func_info['parameters'],
+ ensure_ascii=False),
+ )
+ else:
+ tool = TOOL_DESC_NO_PARAMETERS.format( # qwen style
+ name_for_model=name_m,
+ name_for_human=name_h,
+ description_for_model=desc_m,
+ )
+ tools_text.append(tool)
+ tools_name_text.append(name_m)
+ tools_text = '\n\n'.join(tools_text)
+ tools_name_text = ', '.join(tools_name_text)
+ instruction = (REACT_INSTRUCTION.format(
+ tools_text=tools_text,
+ tools_name_text=tools_name_text,
+ ).lstrip('\n').rstrip())
+ else:
+ instruction = ''
+
+ messages_with_fncall = messages
+ messages = []
+ for m_idx, m in enumerate(messages_with_fncall):
+ role, content, func_call = m.role, m.content, m.function_call
+ content = content or ''
+ content = content.lstrip('\n').rstrip()
+ if role == 'function':
+ if (len(messages) == 0) or (messages[-1].role != 'assistant'):
+ raise HTTPException(
+ status_code=400,
+ detail=
+ 'Invalid request: Expecting role assistant before role function.',
+ )
+ messages[-1].content += f'\nObservation: {content}'
+ if m_idx == len(messages_with_fncall) - 1:
+ # add a prefix for text completion
+ messages[-1].content += '\nThought:'
+ elif role == 'assistant':
+ if len(messages) == 0:
+ raise HTTPException(
+ status_code=400,
+ detail=
+ 'Invalid request: Expecting role user before role assistant.',
+ )
+ if func_call is None:
+ if functions:
+ content = f'Thought: I now know the final answer.\nFinal Answer: {content}'
+ else:
+ f_name, f_args = func_call['name'], func_call['arguments']
+ if not content.startswith('Thought:'):
+ content = f'Thought: {content}'
+ content = f'{content}\nAction: {f_name}\nAction Input: {f_args}'
+ if messages[-1].role == 'user':
+ messages.append(
+ ChatMessage(role='assistant',
+ content=content.lstrip('\n').rstrip()))
+ else:
+ messages[-1].content += '\n' + content
+ elif role == 'user':
+ messages.append(
+ ChatMessage(role='user',
+ content=content.lstrip('\n').rstrip()))
+ else:
+ raise HTTPException(
+ status_code=400,
+ detail=f'Invalid request: Incorrect role {role}.')
+
+ query = _TEXT_COMPLETION_CMD
+ if messages[-1].role == 'user':
+ query = messages[-1].content
+ messages = messages[:-1]
+
+ if len(messages) % 2 != 0:
+ raise HTTPException(status_code=400, detail='Invalid request')
+
+ history = [] # [(Q1, A1), (Q2, A2), ..., (Q_last_turn, A_last_turn)]
+ for i in range(0, len(messages), 2):
+ if messages[i].role == 'user' and messages[i + 1].role == 'assistant':
+ usr_msg = messages[i].content.lstrip('\n').rstrip()
+ bot_msg = messages[i + 1].content.lstrip('\n').rstrip()
+ if instruction and (i == len(messages) - 2):
+ usr_msg = f'{instruction}\n\nQuestion: {usr_msg}'
+ instruction = ''
+ history.append([usr_msg, bot_msg])
+ else:
+ raise HTTPException(
+ status_code=400,
+ detail=
+ 'Invalid request: Expecting exactly one user (or function) role before every assistant role.',
+ )
+ if instruction:
+ assert query is not _TEXT_COMPLETION_CMD # if false, will show an error
+ query = f'{instruction}\n\nQuestion: {query}'
+ return query, history, system
+
+
+def parse_response(response):
+ """
+ Parsing into Openai's response format:
+ ChatCompletionResponseChoice(index=0, message=ChatMessage(role='assistant', content='我需要查询波士顿的当前天气情况。',
+ function_call={'name': 'get_current_weather', 'arguments': '{"location": "波士顿"}'}), finish_reason='function_call')
+ """
+ func_name, func_args = '', ''
+ i = response.find('\nAction:')
+ j = response.find('\nAction Input:')
+ k = response.find('\nObservation:')
+ if 0 <= i < j: # If the text has `Action` and `Action input`,
+ if k < j: # but does not contain `Observation`,
+ # then it is likely that `Observation` is omitted by the LLM,
+ # because the output text may have discarded the stop word.
+ response = response.rstrip() + '\nObservation:' # Add it back.
+ k = response.find('\nObservation:')
+ func_name = response[i + len('\nAction:'):j].strip()
+ func_args = response[j + len('\nAction Input:'):k].strip()
+
+ if func_name:
+ response = response[:i]
+ t = response.find('Thought: ')
+ if t >= 0:
+ response = response[t + len('Thought: '):]
+ response = response.strip()
+ choice_data = ChatCompletionResponseChoice(
+ index=0,
+ message=ChatMessage(
+ role='assistant',
+ content=response,
+ function_call={
+ 'name': func_name,
+ 'arguments': func_args
+ },
+ ),
+ finish_reason='function_call',
+ )
+ return choice_data
+
+ z = response.rfind('\nFinal Answer: ')
+ if z >= 0:
+ response = response[z + len('\nFinal Answer: '):]
+ choice_data = ChatCompletionResponseChoice(
+ index=0,
+ message=ChatMessage(role='assistant', content=response),
+ finish_reason='stop',
+ )
+ return choice_data
+
+
+# completion mode, not chat mode
+def text_complete_last_message(history, stop_words_ids, gen_kwargs, system):
+ im_start = '<|im_start|>'
+ im_end = '<|im_end|>'
+ prompt = f'{im_start}system\n{system}{im_end}'
+ for i, (query, response) in enumerate(history):
+ query = query.lstrip('\n').rstrip()
+ response = response.lstrip('\n').rstrip()
+ prompt += f'\n{im_start}user\n{query}{im_end}'
+ prompt += f'\n{im_start}assistant\n{response}{im_end}'
+ prompt = prompt[:-len(im_end)]
+
+ _stop_words_ids = [tokenizer.encode(im_end)]
+ if stop_words_ids:
+ for s in stop_words_ids:
+ _stop_words_ids.append(s)
+ stop_words_ids = _stop_words_ids
+
+ input_ids = torch.tensor([tokenizer.encode(prompt)]).to(model.device)
+ output = model.generate(input_ids,
+ stop_words_ids=stop_words_ids,
+ **gen_kwargs).tolist()[0]
+ output = tokenizer.decode(output, errors='ignore')
+ assert output.startswith(prompt)
+ output = output[len(prompt):]
+ output = trim_stop_words(output, ['<|endoftext|>', im_end])
+ print(f'\n{prompt}\n\n{output}\n')
+ return output
+
+
+@app.post('/v1/chat/completions', response_model=ChatCompletionResponse)
+async def create_chat_completion(request: ChatCompletionRequest):
+ global model, tokenizer
+
+ gen_kwargs = {}
+ if request.top_k is not None:
+ gen_kwargs['top_k'] = request.top_k
+ if request.temperature is not None:
+ if request.temperature < 0.01:
+ gen_kwargs['top_k'] = 1 # greedy decoding
+ else:
+ # Not recommended. Please tune top_p instead.
+ gen_kwargs['temperature'] = request.temperature
+ if request.top_p is not None:
+ gen_kwargs['top_p'] = request.top_p
+ if request.max_length is not None:
+ gen_kwargs['max_new_tokens'] = request.max_length
+ else:
+ gen_kwargs['max_new_tokens'] = 512
+
+ stop_words = add_extra_stop_words(request.stop)
+ if request.functions:
+ stop_words = stop_words or []
+ if 'Observation:' not in stop_words:
+ stop_words.append('Observation:')
+
+ query, history, system = parse_messages(request.messages,
+ request.functions)
+
+ if request.stream:
+ if request.functions:
+ raise HTTPException(
+ status_code=400,
+ detail=
+ 'Invalid request: Function calling is not yet implemented for stream mode.',
+ )
+ generate = predict(query,
+ history,
+ request.model,
+ stop_words,
+ gen_kwargs,
+ system=system)
+ return EventSourceResponse(generate, media_type='text/event-stream')
+
+ stop_words_ids = [tokenizer.encode(s)
+ for s in stop_words] if stop_words else None
+ if query is _TEXT_COMPLETION_CMD:
+ response = text_complete_last_message(history,
+ stop_words_ids=stop_words_ids,
+ gen_kwargs=gen_kwargs,
+ system=system)
+ else:
+ response, _ = model.chat(
+ tokenizer,
+ query,
+ history=history,
+ system=system,
+ stop_words_ids=stop_words_ids,
+ **gen_kwargs,
+ )
+ print('')
+ pprint(history, indent=2)
+ print(f'{query}\n\n{response}\n')
+ _gc()
+
+ response = trim_stop_words(response, stop_words)
+ if request.functions:
+ choice_data = parse_response(response)
+ else:
+ choice_data = ChatCompletionResponseChoice(
+ index=0,
+ message=ChatMessage(role='assistant', content=response),
+ finish_reason='stop',
+ )
+ return ChatCompletionResponse(model=request.model,
+ choices=[choice_data],
+ object='chat.completion')
+
+
+def _dump_json(data: BaseModel, *args, **kwargs) -> str:
+ try:
+ return data.model_dump_json(*args, **kwargs)
+ except AttributeError: # pydantic<2.0.0
+ return data.json(*args, **kwargs) # noqa
+
+
+async def predict(
+ query: str,
+ history: List[List[str]],
+ model_id: str,
+ stop_words: List[str],
+ gen_kwargs: Dict,
+ system: str,
+):
+ global model, tokenizer
+ choice_data = ChatCompletionResponseStreamChoice(
+ index=0, delta=DeltaMessage(role='assistant'), finish_reason=None)
+ chunk = ChatCompletionResponse(model=model_id,
+ choices=[choice_data],
+ object='chat.completion.chunk')
+ yield '{}'.format(_dump_json(chunk, exclude_unset=True))
+
+ current_length = 0
+ stop_words_ids = [tokenizer.encode(s)
+ for s in stop_words] if stop_words else None
+
+ delay_token_num = max([len(x) for x in stop_words]) if stop_words_ids else 0
+ response_generator = model.chat_stream(tokenizer,
+ query,
+ history=history,
+ stop_words_ids=stop_words_ids,
+ system=system,
+ **gen_kwargs)
+ for _new_response in response_generator:
+ if len(_new_response) <= delay_token_num:
+ continue
+ new_response = _new_response[:-delay_token_num] if delay_token_num else _new_response
+
+ if len(new_response) == current_length:
+ continue
+
+ new_text = new_response[current_length:]
+ current_length = len(new_response)
+
+ choice_data = ChatCompletionResponseStreamChoice(
+ index=0, delta=DeltaMessage(content=new_text), finish_reason=None)
+ chunk = ChatCompletionResponse(model=model_id,
+ choices=[choice_data],
+ object='chat.completion.chunk')
+ yield '{}'.format(_dump_json(chunk, exclude_unset=True))
+
+ if current_length != len(_new_response):
+ # Determine whether to print the delay tokens
+ delayed_text = _new_response[current_length:]
+ new_text = trim_stop_words(delayed_text, stop_words)
+ if len(new_text) > 0:
+ choice_data = ChatCompletionResponseStreamChoice(
+ index=0, delta=DeltaMessage(content=new_text), finish_reason=None)
+ chunk = ChatCompletionResponse(model=model_id,
+ choices=[choice_data],
+ object='chat.completion.chunk')
+ yield '{}'.format(_dump_json(chunk, exclude_unset=True))
+
+ choice_data = ChatCompletionResponseStreamChoice(index=0,
+ delta=DeltaMessage(),
+ finish_reason='stop')
+ chunk = ChatCompletionResponse(model=model_id,
+ choices=[choice_data],
+ object='chat.completion.chunk')
+ yield '{}'.format(_dump_json(chunk, exclude_unset=True))
+ yield '[DONE]'
+
+ _gc()
+
+
+def _get_args():
+ parser = ArgumentParser()
+ parser.add_argument(
+ '-c',
+ '--checkpoint-path',
+ type=str,
+ default='Qwen/Qwen2-7B-Instruct',
+ help='Checkpoint name or path, default to %(default)r'
+ )
+ parser.add_argument('--device',
+ help='number of device of cuda, e.g cuda:0',
+ type=str,
+ default='cuda:2'
+ )
+ parser.add_argument('--api-auth', help='API authentication credentials')
+ parser.add_argument('--cpu-only',
+ action='store_true',
+ help='Run demo with CPU only')
+ parser.add_argument('--server-port',
+ type=int,
+ default=6071,
+ help='Demo server port.')
+ parser.add_argument(
+ '--server-name',
+ type=str,
+ default='0.0.0.0',
+ help=
+ 'Demo server name. Default: 127.0.0.1, which is only visible from the local computer.'
+ ' If you want other computers to access your server, use 0.0.0.0 instead.',
+ )
+ parser.add_argument(
+ '--disable-gc',
+ action='store_true',
+ help='Disable GC after each response generated.',
+ )
+
+ args = parser.parse_args()
+ return args
+
+
+if __name__ == '__main__':
+ args = _get_args()
+
+ tokenizer = Qwen2Tokenizer.from_pretrained(
+ args.checkpoint_path,
+ resume_download=True
+ )
+
+ if args.api_auth:
+ app.add_middleware(BasicAuthMiddleware,
+ username=args.api_auth.split(':')[0],
+ password=args.api_auth.split(':')[1])
+
+ if args.cpu_only:
+ device_map = 'cpu'
+ else:
+ device_map = args.device
+
+ model = Qwen2ForCausalLM.from_pretrained(
+ args.checkpoint_path,
+ device_map=device_map,
+ resume_download=True,
+ torch_dtype="auto",
+ )
+ model.eval()
+
+ model.generation_config = GenerationConfig.from_pretrained(
+ args.checkpoint_path,
+ resume_download=True,
+ )
+ model.__class__ = Qwen2ForChatLM
+
+ uvicorn.run(app, host=args.server_name, port=args.server_port, workers=1)
diff --git a/openai_api/openai_service.sh b/openai_api/openai_service.sh
new file mode 100644
index 00000000..3931f3f5
--- /dev/null
+++ b/openai_api/openai_service.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+PORT=6069
+lsof -i :$PORT | grep LISTEN | awk '{print $2}' | xargs kill -9
+
+nohup python openai_api.py --checkpoint-path Qwen/Qwen1.5-7B-Chat --device 1 --server-port $PORT \
+--server-name '0.0.0.0' > nohup.out 2>&1 &
+
diff --git a/openai_api/qwen2chat.py b/openai_api/qwen2chat.py
new file mode 100644
index 00000000..b54bbc55
--- /dev/null
+++ b/openai_api/qwen2chat.py
@@ -0,0 +1,144 @@
+from transformers import Qwen2ForCausalLM, Qwen2Tokenizer
+from transformers import PreTrainedTokenizer, GenerationConfig, StoppingCriteriaList
+from typing import TYPE_CHECKING, Optional, Tuple, Union, Callable, List, Any, Generator
+from qwen_generation_utils import (
+ HistoryType,
+ make_context,
+ decode_tokens,
+ get_stop_words_ids,
+ StopWordsLogitsProcessor,
+)
+import copy
+import torch
+from transformers.generation.logits_process import LogitsProcessorList
+from transformers.generation.utils import GenerateOutput
+from transformers.modeling_utils import PreTrainedModel
+from transformers.generation.streamers import BaseStreamer
+
+_ERROR_BAD_CHAT_FORMAT = """\
+We detect you are probably using the pretrained model (rather than chat model) for chatting, since the chat_format in generation_config is not "chatml".
+If you are directly using the model downloaded from Huggingface, please make sure you are using our "Qwen/Qwen-7B-Chat" Huggingface model (rather than "Qwen/Qwen-7B") when you call model.chat().
+我们检测到您可能在使用预训练模型(而非chat模型)进行多轮chat,因为您当前在generation_config指定的chat_format,并未设置为我们在对话中所支持的"chatml"格式。
+如果您在直接使用我们从Huggingface提供的模型,请确保您在调用model.chat()时,使用的是"Qwen/Qwen-7B-Chat"模型(而非"Qwen/Qwen-7B"预训练模型)。
+"""
+
+_SENTINEL = object()
+_ERROR_STREAM_IN_CHAT = """\
+Pass argument `stream` to model.chat() is buggy, deprecated, and marked for removal. Please use model.chat_stream(...) instead of model.chat(..., stream=True).
+向model.chat()传入参数stream的用法可能存在Bug,该用法已被废弃,将在未来被移除。请使用model.chat_stream(...)代替model.chat(..., stream=True)。
+"""
+
+_ERROR_INPUT_CPU_QUERY_WITH_FLASH_ATTN_ACTIVATED = """\
+We detect you have activated flash attention support, but running model computation on CPU. Please make sure that your input data has been placed on GPU. If you actually want to run CPU computation, please following the readme and set device_map="cpu" to disable flash attention when loading the model (calling AutoModelForCausalLM.from_pretrained).
+检测到您的模型已激活了flash attention支持,但正在执行CPU运算任务。如使用flash attention,请您确认模型输入已经传到GPU上。如果您确认要执行CPU运算,请您在载入模型(调用AutoModelForCausalLM.from_pretrained)时,按照readme说法,指定device_map="cpu"以禁用flash attention。
+"""
+
+class Qwen2ForChatLM(Qwen2ForCausalLM):
+ def chat(
+ self,
+ tokenizer: PreTrainedTokenizer,
+ query: str,
+ history: Optional[HistoryType],
+ system: str = "You are a helpful assistant.",
+ stream: Optional[bool] = _SENTINEL,
+ stop_words_ids: Optional[List[List[int]]] = None,
+ generation_config: Optional[GenerationConfig] = None,
+ max_window_size=32000,
+ **kwargs,
+ ) -> Tuple[str, HistoryType]:
+ generation_config = generation_config if generation_config is not None else self.generation_config
+
+ assert stream is _SENTINEL, _ERROR_STREAM_IN_CHAT
+ # assert generation_config.chat_format == 'chatml', _ERROR_BAD_CHAT_FORMAT
+ if history is None:
+ history = []
+ else:
+ # make a copy of the user's input such that is is left untouched
+ history = copy.deepcopy(history)
+
+ if stop_words_ids is None:
+ stop_words_ids = []
+ chat_format = 'chatml'
+
+ raw_text, context_tokens = make_context(
+ tokenizer,
+ query,
+ history=history,
+ system=system,
+ max_window_size=max_window_size,
+ chat_format=chat_format
+ )
+
+ stop_words_ids.extend((get_stop_words_ids(chat_format, tokenizer)))
+ input_ids = torch.tensor([context_tokens]).to(self.device)
+
+ outputs = self.generate(
+ input_ids,
+ stop_words_ids=stop_words_ids,
+ return_dict_in_generate=False,
+ generation_config=generation_config,
+ **kwargs,
+ )
+
+ response = decode_tokens(
+ outputs[0],
+ tokenizer,
+ raw_text_len=len(raw_text),
+ context_length=len(context_tokens),
+ chat_format=chat_format,
+ verbose=False,
+ errors='replace'
+ )
+
+ # as history is a copy of the user inputs,
+ # we can always return the new turn to the user.
+ # separating input history and output history also enables the user
+ # to implement more complex history management
+ history.append((query, response))
+
+ return response, history
+
+ def generate(
+ self,
+ inputs: Optional[torch.Tensor] = None,
+ generation_config: Optional[GenerationConfig] = None,
+ logits_processor: Optional[LogitsProcessorList] = None,
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
+ prefix_allowed_tokens_fn: Optional[
+ Callable[[int, torch.Tensor], List[int]]
+ ] = None,
+ synced_gpus: Optional[bool] = None,
+ assistant_model: Optional["PreTrainedModel"] = None,
+ streamer: Optional["BaseStreamer"] = None,
+ **kwargs,
+ ) -> Union[GenerateOutput, torch.LongTensor]:
+ generation_config = generation_config if generation_config is not None else self.generation_config
+
+ # Process stop_words_ids.
+ stop_words_ids = kwargs.pop("stop_words_ids", None)
+ if stop_words_ids is None and generation_config is not None:
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
+ if stop_words_ids is None:
+ stop_words_ids = getattr(generation_config, "stop_words_ids", None)
+
+ if stop_words_ids is not None:
+ stop_words_logits_processor = StopWordsLogitsProcessor(
+ stop_words_ids=stop_words_ids,
+ eos_token_id=generation_config.eos_token_id,
+ )
+ if logits_processor is None:
+ logits_processor = LogitsProcessorList([stop_words_logits_processor])
+ else:
+ logits_processor.append(stop_words_logits_processor)
+
+ return super().generate(
+ inputs,
+ generation_config=generation_config,
+ logits_processor=logits_processor,
+ stopping_criteria=stopping_criteria,
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
+ synced_gpus=synced_gpus,
+ assistant_model=assistant_model,
+ streamer=streamer,
+ **kwargs,
+ )
\ No newline at end of file
diff --git a/openai_api/qwen_generation_utils.py b/openai_api/qwen_generation_utils.py
new file mode 100644
index 00000000..6b412c1c
--- /dev/null
+++ b/openai_api/qwen_generation_utils.py
@@ -0,0 +1,428 @@
+# Copyright (c) Alibaba Cloud.
+#
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+"""Generation support."""
+
+from typing import Tuple, List, Union, Iterable
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from transformers import PreTrainedTokenizer
+from transformers import logging
+from transformers.generation import LogitsProcessor
+
+logger = logging.get_logger(__name__)
+
+# Types.
+HistoryType = List[Tuple[str, str]]
+TokensType = List[int]
+BatchTokensType = List[List[int]]
+
+
+def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
+ for tokens in batch:
+ context_length = len(tokens)
+ if context_length < seq_length:
+ tokens.extend([pad_id] * (seq_length - context_length))
+ return batch
+
+
+def get_ltor_masks_and_position_ids(
+ data,
+ eod_token,
+ reset_position_ids,
+ reset_attention_mask,
+ eod_mask_loss,
+):
+ """Build masks and position id for left to right model."""
+
+ # Extract batch size and sequence length.
+ micro_batch_size, seq_length = data.size()
+
+ # Attention mask (lower triangular).
+ if reset_attention_mask:
+ att_mask_batch = micro_batch_size
+ else:
+ att_mask_batch = 1
+ attention_mask = torch.tril(
+ torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
+ ).view(att_mask_batch, 1, seq_length, seq_length)
+
+ # Loss mask.
+ loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
+ if eod_mask_loss:
+ loss_mask[data == eod_token] = 0.0
+
+ # Position ids.
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
+ position_ids = position_ids.unsqueeze(0).expand_as(data)
+ # We need to clone as the ids will be modifed based on batch index.
+ if reset_position_ids:
+ position_ids = position_ids.clone()
+
+ if reset_position_ids or reset_attention_mask:
+ # Loop through the batches:
+ for b in range(micro_batch_size):
+
+ # Find indecies where EOD token is.
+ eod_index = position_ids[b, data[b] == eod_token]
+ # Detach indecies from positions if going to modify positions.
+ if reset_position_ids:
+ eod_index = eod_index.clone()
+
+ # Loop through EOD indecies:
+ prev_index = 0
+ for j in range(eod_index.size()[0]):
+ i = eod_index[j]
+ # Mask attention loss.
+ if reset_attention_mask:
+ attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
+ # Reset positions.
+ if reset_position_ids:
+ position_ids[b, (i + 1) :] -= i + 1 - prev_index
+ prev_index = i + 1
+
+ # Convert attention mask to binary:
+ attention_mask = attention_mask < 0.5
+
+ return attention_mask, loss_mask, position_ids
+
+
+def get_batch(context_tokens: torch.LongTensor, eod_id: int):
+ """Generate batch from context tokens."""
+ # Move to GPU.
+ tokens = context_tokens.contiguous().to(context_tokens.device)
+ # Get the attention mask and postition ids.
+ attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
+ tokens,
+ eod_id,
+ reset_position_ids=False,
+ reset_attention_mask=False,
+ eod_mask_loss=False,
+ )
+ return tokens, attention_mask, position_ids
+
+
+def get_stop_words_ids(chat_format, tokenizer):
+ if chat_format == "raw":
+ stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
+ elif chat_format == "chatml":
+ #stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
+ #stop_words_ids = [tokenizer.encode("<|im_start|>"), tokenizer.encode("<|im_end|>")]
+ stop_words_ids = [[tokenizer.convert_tokens_to_ids("<|im_start|>")], [tokenizer.convert_tokens_to_ids("<|im_end|>")]]
+ else:
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
+ return stop_words_ids
+
+
+def make_context(
+ tokenizer: PreTrainedTokenizer,
+ query: str,
+ history: List[Tuple[str, str]] = None,
+ system: str = "",
+ max_window_size: int = 6144,
+ chat_format: str = "chatml",
+):
+ if history is None:
+ history = []
+
+ if chat_format == "chatml":
+ im_start, im_end = "<|im_start|>", "<|im_end|>"
+ im_start_tokens = [tokenizer.convert_tokens_to_ids("<|im_start|>")]
+ im_end_tokens = [tokenizer.convert_tokens_to_ids("<|im_end|>")]
+
+ # im_start_tokens = [tokenizer.im_start_id]
+ # im_end_tokens = [tokenizer.im_end_id]
+ nl_tokens = tokenizer.convert_tokens_to_ids(tokenizer.tokenize("\n"))
+
+ # def _tokenize_str(role, content):
+ # return f"{role}\n{content}", tokenizer.encode(
+ # role, allowed_special=set()
+ # ) + nl_tokens + tokenizer.encode(content, allowed_special=set())
+ def _tokenize_str(role, content):
+ return (f"{role}\n{content}", tokenizer.convert_tokens_to_ids(tokenizer.tokenize(role))
+ + nl_tokens + tokenizer.convert_tokens_to_ids(tokenizer.tokenize(content)))
+
+
+ return f"{role}\n{content}"
+ system_text, system_tokens_part = _tokenize_str("system", system)
+ system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
+
+ raw_text = ""
+ context_tokens = []
+
+ for turn_query, turn_response in reversed(history):
+ query_text, query_tokens_part = _tokenize_str("user", turn_query)
+ query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
+ response_text, response_tokens_part = _tokenize_str(
+ "assistant", turn_response
+ )
+ response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
+
+ next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
+ prev_chat = (
+ f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
+ )
+
+ current_context_size = (
+ len(system_tokens) + len(next_context_tokens) + len(context_tokens)
+ )
+ if current_context_size < max_window_size:
+ context_tokens = next_context_tokens + context_tokens
+ raw_text = prev_chat + raw_text
+ else:
+ break
+
+ context_tokens = system_tokens + context_tokens
+ raw_text = f"{im_start}{system_text}{im_end}" + raw_text
+ context_tokens += (
+ nl_tokens
+ + im_start_tokens
+ + _tokenize_str("user", query)[1]
+ + im_end_tokens
+ + nl_tokens
+ + im_start_tokens
+ #+ tokenizer.encode("assistant")
+ + tokenizer.convert_tokens_to_ids(tokenizer.tokenize("assistant"))
+ + nl_tokens
+ )
+ raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
+
+ elif chat_format == "raw":
+ raw_text = query
+ context_tokens = tokenizer.encode(raw_text)
+ else:
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
+
+ return raw_text, context_tokens
+
+
+def _decode_default(
+ tokens: List[int],
+ *,
+ stop_words: List[str],
+ eod_words: List[str],
+ tokenizer: PreTrainedTokenizer,
+ raw_text_len: int,
+ verbose: bool = False,
+ return_end_reason: bool = False,
+ errors: str='replace',
+):
+ trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
+ if verbose:
+ print("\nRaw Generate: ", trim_decode_tokens)
+
+ end_reason = f"Gen length {len(tokens)}"
+ for stop_word in stop_words:
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
+ for eod_word in eod_words:
+ if eod_word in trim_decode_tokens:
+ end_reason = f"Gen {eod_word!r}"
+ trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
+ trim_decode_tokens = trim_decode_tokens.strip()
+ if verbose:
+ print("\nEnd Reason:", end_reason)
+ print("\nGenerate: ", trim_decode_tokens)
+
+ if return_end_reason:
+ return trim_decode_tokens, end_reason
+ else:
+ return trim_decode_tokens
+
+
+def _decode_chatml(
+ tokens: List[int],
+ *,
+ stop_words: List[str],
+ eod_token_ids: List[int],
+ tokenizer: PreTrainedTokenizer,
+ raw_text_len: int,
+ context_length: int,
+ verbose: bool = False,
+ return_end_reason: bool = False,
+ errors: str='replace'
+):
+ end_reason = f"Gen length {len(tokens)}"
+ eod_token_idx = context_length
+ for eod_token_idx in range(context_length, len(tokens)):
+ if tokens[eod_token_idx] in eod_token_ids:
+ end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
+ break
+
+ trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
+ if verbose:
+ print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
+ print("\nRaw Generate:", trim_decode_tokens)
+ print("\nEnd Reason:", end_reason)
+ for stop_word in stop_words:
+ trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
+ trim_decode_tokens = trim_decode_tokens.strip()
+ if verbose:
+ print("\nGenerate:", trim_decode_tokens)
+
+ if return_end_reason:
+ return trim_decode_tokens, end_reason
+ else:
+ return trim_decode_tokens
+
+
+def decode_tokens(
+ tokens: Union[torch.LongTensor, TokensType],
+ tokenizer: PreTrainedTokenizer,
+ raw_text_len: int,
+ context_length: int,
+ chat_format: str="chatml",
+ verbose: bool = False,
+ return_end_reason: bool = False,
+ errors: str="replace",
+) -> str:
+ if torch.is_tensor(tokens):
+ tokens = tokens.cpu().numpy().tolist()
+
+ if chat_format == "chatml":
+ return _decode_chatml(
+ tokens,
+ stop_words=[],
+ #eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
+ eod_token_ids=[tokenizer.convert_tokens_to_ids("<|im_start|>"), tokenizer.convert_tokens_to_ids("<|im_start|>")],
+ tokenizer=tokenizer,
+ raw_text_len=raw_text_len,
+ context_length=context_length,
+ verbose=verbose,
+ return_end_reason=return_end_reason,
+ errors=errors,
+ )
+ elif chat_format == "raw":
+ return _decode_default(
+ tokens,
+ stop_words=["<|endoftext|>"],
+ eod_words=["<|endoftext|>"],
+ tokenizer=tokenizer,
+ raw_text_len=raw_text_len,
+ verbose=verbose,
+ return_end_reason=return_end_reason,
+ errors=errors,
+ )
+ else:
+ raise NotImplementedError(f"Unknown chat format {chat_format!r}")
+
+
+class StopWordsLogitsProcessor(LogitsProcessor):
+ """
+ :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
+
+ Args:
+ stop_words_ids (:obj:`List[List[int]]`):
+ List of list of token ids of stop ids. In order to get the tokens of the words
+ that should not appear in the generated text, use :obj:`tokenizer(bad_word,
+ add_prefix_space=True).input_ids`.
+ eos_token_id (:obj:`int`):
+ The id of the `end-of-sequence` token.
+ """
+
+ def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
+
+ if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
+ raise ValueError(
+ f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
+ )
+ if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
+ raise ValueError(
+ f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
+ )
+ if any(
+ any(
+ (not isinstance(token_id, (int, np.integer)) or token_id < 0)
+ for token_id in stop_word_ids
+ )
+ for stop_word_ids in stop_words_ids
+ ):
+ raise ValueError(
+ f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
+ )
+
+ self.stop_words_ids = list( # stop_words_ids 中所有不等于 eos_token_id 的元素, eos_token是结束符
+ filter(
+ lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
+ )
+ )
+ self.eos_token_id = eos_token_id
+ for stop_token_seq in self.stop_words_ids:
+ assert (
+ len(stop_token_seq) > 0
+ ), "Stop words token sequences {} cannot have an empty list".format(
+ stop_words_ids
+ )
+
+ def __call__(
+ self, input_ids: torch.LongTensor, scores: torch.FloatTensor
+ ) -> torch.FloatTensor:
+ stopped_samples = self._calc_stopped_samples(input_ids)
+ for i, should_stop in enumerate(stopped_samples):
+ if should_stop:
+ scores[i, self.eos_token_id] = float(2**15)
+ return scores
+
+ def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
+ if len(tokens) == 0:
+ # if bad word tokens is just one token always ban it
+ return True
+ elif len(tokens) > len(prev_tokens):
+ # if bad word tokens are longer then prev input_ids they can't be equal
+ return False
+ elif prev_tokens[-len(tokens) :].tolist() == tokens:
+ # if tokens match
+ return True
+ else:
+ return False
+
+ def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
+ stopped_samples = []
+ for prev_input_ids_slice in prev_input_ids:
+ match = False
+ for stop_token_seq in self.stop_words_ids:
+ if self._tokens_match(prev_input_ids_slice, stop_token_seq):
+ # if tokens do not match continue
+ match = True
+ break
+ stopped_samples.append(match)
+
+ return stopped_samples
+
+
+def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
+ """This function has been mostly taken from huggingface conversational
+ ai code at
+ https://medium.com/huggingface/how-to-build-a-state-of-the-art-
+ conversational-ai-with-transfer-learning-2d818ac26313"""
+
+ if top_k > 0:
+ # Remove all tokens with a probability less than the
+ # last token of the top-k
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
+ logits[indices_to_remove] = filter_value
+
+ if top_p > 0.0:
+ # Cconvert to 1D
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
+
+ # Remove tokens with cumulative probability above the threshold
+ sorted_indices_to_remove = cumulative_probs > top_p
+ # Shift the indices to the right to keep also the first token
+ # above the threshold
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
+ sorted_indices_to_remove[..., 0] = 0
+ for i in range(sorted_indices.size(0)):
+ indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
+ logits[i][indices_to_remove] = filter_value
+
+ return logits
+
+
+def switch(val1, val2, boolean):
+ boolean = boolean.type_as(val1)
+ return (1 - boolean) * val1 + boolean * val2