├── assets ├── Wechat.jpeg ├── 这个男人能嫁吗.jpg ├── product1.png ├── product3.png ├── saofund2.png └── sft_demo.png ├── .gitignore ├── README_zh.md ├── README.md ├── cli_demo.py └── LICENSE /assets/Wechat.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saofund/marrywise-llm/HEAD/assets/Wechat.jpeg -------------------------------------------------------------------------------- /assets/这个男人能嫁吗.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saofund/marrywise-llm/HEAD/assets/这个男人能嫁吗.jpg -------------------------------------------------------------------------------- /assets/product1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saofund/marrywise-llm/HEAD/assets/product1.png -------------------------------------------------------------------------------- /assets/product3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saofund/marrywise-llm/HEAD/assets/product3.png -------------------------------------------------------------------------------- /assets/saofund2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saofund/marrywise-llm/HEAD/assets/saofund2.png -------------------------------------------------------------------------------- /assets/sft_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saofund/marrywise-llm/HEAD/assets/sft_demo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /README_zh.md: -------------------------------------------------------------------------------- 1 | ![# MarryWise](assets/这个男人能嫁吗.jpg) 2 | 3 | 4 | 5 | [![GitHub Code License](https://img.shields.io/github/license/saofund/marrywise-llm)](LICENSE) 6 | [![GitHub last commit](https://img.shields.io/github/last-commit/saofund/marrywise-llm)](https://github.com/saofund/marrywise-llm/commits/main) 7 | [![Studios](https://img.shields.io/badge/ModelScope-Open%20in%20ModelScope-blue)](https://www.modelscope.cn/models/saofund/marrywise-7b-lora) 8 | [![Spaces](https://img.shields.io/badge/🤗-Open%20in%20huggingface-blue)](https://huggingface.co/saofund/marrywise-7b-lora) 9 | [![Twitter](https://img.shields.io/twitter/follow/sáofund)](https://x.com/976582772Wyt) 10 | 11 | \[ English | [中文](README_zh.md) \] 12 | 13 | 14 | 15 | 16 | | [![在线体验](https://img.shields.io/badge/在线地址-这个男人能嫁吗.com-blue)](https://xn--ciqpnj1l70hxw9az0oyqy.com/) | [![在线体验2](https://img.shields.io/badge/在线地址2-访问-blue)](https://can-he-marry.com/) | 17 | |---|---| 18 | | [![Product 1](assets/product1.png)](https://can-he-marry.com/) | [![Product 2](assets/product3.png)](https://can-he-marry.com/) | 19 | 20 | 21 | ## 功能特点 22 | 23 | - **AI 相亲分析师**:利用先进的 AI 技术,自动分析约会中的行为和言语模式,揭示隐藏的动机和真实的性格特征。 24 | - **AI 打假媒婆**:帮助用户识别约会过程中的潜在欺骗行为,确保伴侣的真实性和可靠性。 25 | 26 | ## 主要分析维度 27 | 28 | - **性格真实性**:通过行为和言语分析,评估潜在伴侣的真实性格。 29 | - **实际动机**:揭示求婚者行为背后的真实意图,防止被表象所迷惑。 30 | - **个人成就**:评估求婚者的个人成就和能力,确保其描述与实际情况一致。 31 | 32 | 33 | ## 微调数据示例 34 | 使用 [Qwen2-7B](https://qwen.readthedocs.io/en/latest/getting_started/quickstart.html) 微调,微调数据示例(即将开源)。 35 | 36 | 37 | | 输入(条件) | 输出:(分析、大模型转换后) | 38 | | -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 39 | | 1. 32岁,178
2. 收房租,年收入15104
3. 6套房,一辆代步车
4. 爱干净,爱做饭,爱老婆,父母离异跟母亲,母亲温柔。 | 🔍 隐藏的秘密:他不想让你知道的真相
在闪耀的相亲市场,每个人都试图展示自己最好的一面。但小心那些未被言说的秘密,它们可能是你幸福之路上的绊脚石。
🍳 烹饪背后的体重迷思
他自称烹饪大师,生活轻松自在。但数字不会说谎:未提及的体重可能暗示着不健康的生活方式。在你品尝美食的同时,不要忽视长期健康的风险。
💰 财产来源的疑问
六套房产,一辆车——看似稳固的经济基础。但这些财产来自何方?拆迁户的身份可能是幸运的象征,也可能是缺乏进取心的标志。
👨‍👩‍👦 家庭关系的复杂性
他称赞母亲的温柔和易相处,但这是否意味着他无法独立?单亲家庭背景下的母子关系可能比表面看起来要复杂得多,这可能会影响未来的家庭和谐。
💍 “爱妻”标签的陷阱
“爱老婆”听起来很完美,但小心这是一种心理战术。在深入了解他的真实意图之前,不要轻易被这个标签迷惑。
🔍 深入挖掘:真正的动机是什么?
他了解女性,但为何仍单身?在他的完美外表下,可能隐藏着不为人知的秘密。在做出决定之前,请揭开那层薄纱,看清他的真实动机。 | 40 | 41 | 42 | ## 本地启动 43 | 44 | ##### 详细步骤: 45 | 46 | ```shell 47 | # 下载Qwen2-7B-Instruct模型:https://modelscope.cn/models/qwen/Qwen2-7B/files 48 | git lfs install 49 | git clone https://www.modelscope.cn/qwen/Qwen2-7B.git 50 | 51 | # 下载lora权重,中文区使用modelscope下载会更快 52 | git clone https://oauth2:pVjFTH_CP5Jrqu6DNVVF@www.modelscope.cn/saofund/marrywise-7b-lora.git 53 | 54 | # 安装 LLaMA-Factory 55 | git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git 56 | cd LLaMA-Factory 57 | pip install -e ".[torch,metrics]" # 安装依赖,这里最好按官方乖乖装完 58 | 59 | # 使用LLaMA-Factory 合并lora权重 60 | # 需要GPU,大概12G显存占用 61 | llamafactory-cli export \ 62 | --model_name_or_path Qwen2-7B-Instruct \ # 刚下载的Qwen2-7B权重 63 | --adapter_name_or_path output_qwen\ # lora权重路径 64 | --template qwen \ # 默认 65 | --finetuning_type lora \ # 默认 66 | --export_dir lora_full_param_model \ # 完整权重的输出路径 67 | --export_size 2 \ # 默认 68 | --export_legacy_format False # 默认 69 | 70 | # Qwen2的官方推理测试脚本,替换权重路径为刚才的合并后的路径 71 | python cli_demo.py -c 合并后的权重路径 # 大概15G显存 72 | 73 | # 请注意,由于lora微调的“风格”特性,需要在问题的开头加入特定提示词: 74 | # 你的身份是一个相亲条件分析师,专门寻找男方条件中“隐瞒没有说”的条件,分析“相亲中男生没有说的秘密”。xxxx(后面跟具体条件) 75 | 76 | ``` 77 | 78 | 79 | ##### 本地运行cli结果: 80 | CLI Result 81 | 82 | 83 | #### 欢迎联系作者 84 | 85 | 数据集获取、模型、算法、技术交流、合作开发等,欢迎添加作者微信。 86 | 87 | | 作者微信二维码 | sáo基金赞助 | 88 | |---|---| 89 | | ![作者的微信二维码](assets/Wechat.jpeg) | ![sáo基金标志](assets/saofund2.png) | 90 | | 数据集获取、模型、算法、技术交流、合作开发等,欢迎添加作者微信。 | 由 sáo 基金赞助,感谢。 | 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![# MarryWise](assets/这个男人能嫁吗.jpg) 2 | 3 | 4 | 5 | [![GitHub Code License](https://img.shields.io/github/license/saofund/marrywise-llm)](LICENSE) 6 | [![GitHub last commit](https://img.shields.io/github/last-commit/saofund/marrywise-llm)](https://github.com/saofund/marrywise-llm/commits/main) 7 | [![Studios](https://img.shields.io/badge/ModelScope-Open%20in%20ModelScope-blue)](https://www.modelscope.cn/models/saofund/marrywise-7b-lora) 8 | [![Spaces](https://img.shields.io/badge/🤗-Open%20in%20huggingface-blue)](https://huggingface.co/saofund/marrywise-7b-lora) 9 | [![Twitter](https://img.shields.io/twitter/follow/sáofund)](https://x.com/976582772Wyt) 10 | 11 | \[ English | [中文](README_zh.md) \] 12 | 13 | https://private-user-images.githubusercontent.com/42131304/346282862-d152cc91-5c53-49d8-89de-b65327b1d490.mp4 14 | 15 | 16 | 17 | | [![Online Experience](https://img.shields.io/badge/Online%20Experience-Can%20He%20Marry%20.com-blue)](https://xn--ciqpnj1l70hxw9az0oyqy.com/) | [![Online Experience 2](https://img.shields.io/badge/Online%20Experience2-Visit-blue)](https://can-he-marry.com/) | 18 | |---|---| 19 | | [![Product 1](assets/product1.png)](https://can-he-marry.com/) | [![Product 2](assets/product3.png)](https://can-he-marry.com/) | 20 | 21 | 22 | ## Features 23 | 24 | - **AI Matchmaking Analyst**: Utilizing advanced AI technology to automatically analyze behavior and speech patterns during dates, revealing hidden motives and true personality traits. 25 | - **AI Fake Matchmaker Detector**: Helps users identify potential deceitful behavior during the dating process, ensuring the authenticity and reliability of partners. 26 | 27 | ## Main Analysis Dimensions 28 | 29 | - **Personality Authenticity**: Assessing the true character of a potential partner through behavior and speech analysis. 30 | - **Actual Motives**: Revealing the real intentions behind a suitor's actions to prevent being deceived by appearances. 31 | - **Personal Achievements**: Evaluating a suitor's personal achievements and capabilities to ensure their descriptions match reality. 32 | 33 | ## Fine-tuning Data Example 34 | Fine-tuned using [Qwen2-7B](https://qwen.readthedocs.io/en/latest/getting_started/quickstart.html), example of fine-tuning data (coming soon). 35 | 36 | | Input (Conditions) | Output (After analysis, large model conversion) | 37 | | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 38 | | 1. 32 years old, 178cm
2. Collects rent, annual income of 15104
3. 6 houses, one car
4. Loves cleanliness, cooking, wife, parents divorced and lives with mother, mother is gentle. | 🔍 Hidden Secrets: The truth he doesn't want you to know
In the dazzling matchmaking market, everyone tries to show their best side. But beware of those unspoken secrets, they could be stumbling blocks on your path to happiness.
🍳 The weight mystery behind cooking
He claims to be a cooking master, living an easy and comfortable life. But numbers don't lie: the undisclosed weight may hint at an unhealthy lifestyle. Don't overlook long-term health risks while enjoying the delicacies.
💰 Questions about property origin
Six properties, one car—seemingly solid financial foundation. But where do these assets come from? Being a demolition household might signify luck, or it could indicate a lack of ambition.
👨‍👩‍👦 Complexity of family relationships
He praises his mother's gentleness and easy-going nature, but does it mean he cannot be independent? The mother-son relationship in a single-parent family may be more complex than it appears, potentially affecting future family harmony.
💍 The "loving wife" label trap
"Loving wife" sounds perfect, but beware it could be a psychological tactic. Don't be easily fooled by this label without delving into his true intentions.
🔍 Deep Dive: What are the real motives?
He understands women, but why is he still single? There might be hidden secrets under his perfect exterior. Uncover the veil and see his true motives before making a decision. | 39 | 40 | ## Local Setup 41 | 42 | ##### Detailed Steps: 43 | 44 | ```shell 45 | # Download Qwen2-7B-Instruct model: https://modelscope.cn/models/qwen/Qwen2-7B/files 46 | git lfs install 47 | git clone https://www.modelscope.cn/qwen/Qwen2-7B.git 48 | 49 | # Download lora weights 50 | git clone https://huggingface.co/saofund/marrywise-7b-lora 51 | 52 | # Install LLaMA-Factory 53 | git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git 54 | cd LLaMA-Factory 55 | pip install -e ".[torch,metrics]" # Install dependencies, follow the official instructions 56 | 57 | # Use LLaMA-Factory to merge lora weights 58 | # Requires GPU, approximately 12G VRAM usage 59 | llamafactory-cli export \ 60 | --model_name_or_path Qwen2-7B-Instruct \ # The just downloaded Qwen2-7B weights 61 | --adapter_name_or_path output_qwen\ # Path to lora weights 62 | --template qwen \ # Default 63 | --finetuning_type lora \ # Default 64 | --export_dir lora_full_param_model \ # Output path for full weights 65 | --export_size 2 \ # Default 66 | --export_legacy_format False # Default 67 | 68 | # Official Qwen2 inference test script, replace the weight path with the merged path 69 | python cli_demo.py -c path_to_merged_weights # Approximately 15G VRAM 70 | 71 | # Note: Due to the "style" characteristics of lora fine-tuning, specific prompt words need to be added at the beginning of the question: 72 | # Your role is a matchmaking condition analyst, specializing in identifying the "hidden" conditions not mentioned by the male party, analyzing the "secrets not mentioned" in matchmaking. xxxx (followed by specific conditions) 73 | 74 | ``` 75 | ##### Local CLI Result: 76 | CLI Result 77 | 78 | #### Contact the Author 79 | 80 | For dataset acquisition, models, algorithms, technical exchanges, and collaborative development, feel free to add the author's WeChat. 81 | 82 | | Author's WeChat QR Code | sáo Fund Sponsorship | 83 | |---|---| 84 | | ![Author's WeChat QR Code](assets/Wechat.jpeg) | ![sáo Fund Logo](assets/saofund2.png) | 85 | | For dataset acquisition, models, algorithms, technical exchanges, and collaborative development, feel free to add the author's WeChat. | Sponsored by sáo Fund, thank you. | 86 | -------------------------------------------------------------------------------- /cli_demo.py: -------------------------------------------------------------------------------- 1 | """A simple command-line interactive chat demo.""" 2 | 3 | import argparse 4 | import os 5 | import platform 6 | import shutil 7 | from copy import deepcopy 8 | from threading import Thread 9 | 10 | import torch 11 | from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer 12 | from transformers.trainer_utils import set_seed 13 | 14 | DEFAULT_CKPT_PATH = 'Qwen/Qwen2-7B-Instruct' 15 | 16 | _WELCOME_MSG = '''\ 17 | Welcome to use Qwen2-Instruct model, type text to start chat, type :h to show command help. 18 | (欢迎使用 Qwen2-Instruct 模型,输入内容即可进行对话,:h 显示命令帮助。) 19 | 20 | Note: This demo is governed by the original license of Qwen2. 21 | We strongly advise users not to knowingly generate or allow others to knowingly generate harmful content, including hate speech, violence, pornography, deception, etc. 22 | (注:本演示受Qwen2的许可协议限制。我们强烈建议,用户不应传播及不应允许他人传播以下内容,包括但不限于仇恨言论、暴力、色情、欺诈相关的有害信息。) 23 | ''' 24 | _HELP_MSG = '''\ 25 | Commands: 26 | :help / :h Show this help message 显示帮助信息 27 | :exit / :quit / :q Exit the demo 退出Demo 28 | :clear / :cl Clear screen 清屏 29 | :clear-history / :clh Clear history 清除对话历史 30 | :history / :his Show history 显示对话历史 31 | :seed Show current random seed 显示当前随机种子 32 | :seed Set random seed to 设置随机种子 33 | :conf Show current generation config 显示生成配置 34 | :conf = Change generation config 修改生成配置 35 | :reset-conf Reset generation config 重置生成配置 36 | ''' 37 | _ALL_COMMAND_NAMES = [ 38 | 'help', 'h', 'exit', 'quit', 'q', 'clear', 'cl', 'clear-history', 'clh', 'history', 'his', 39 | 'seed', 'conf', 'reset-conf', 40 | ] 41 | 42 | 43 | def _setup_readline(): 44 | try: 45 | import readline 46 | except ImportError: 47 | return 48 | 49 | _matches = [] 50 | 51 | def _completer(text, state): 52 | nonlocal _matches 53 | 54 | if state == 0: 55 | _matches = [cmd_name for cmd_name in _ALL_COMMAND_NAMES if cmd_name.startswith(text)] 56 | if 0 <= state < len(_matches): 57 | return _matches[state] 58 | return None 59 | 60 | readline.set_completer(_completer) 61 | readline.parse_and_bind('tab: complete') 62 | 63 | 64 | def _load_model_tokenizer(args): 65 | tokenizer = AutoTokenizer.from_pretrained( 66 | args.checkpoint_path, resume_download=True, 67 | ) 68 | 69 | if args.cpu_only: 70 | device_map = "cpu" 71 | else: 72 | device_map = "auto" 73 | 74 | model = AutoModelForCausalLM.from_pretrained( 75 | args.checkpoint_path, 76 | torch_dtype="auto", 77 | device_map=device_map, 78 | resume_download=True, 79 | ).eval() 80 | model.generation_config.max_new_tokens = 2048 # For chat. 81 | 82 | return model, tokenizer 83 | 84 | 85 | def _gc(): 86 | import gc 87 | gc.collect() 88 | if torch.cuda.is_available(): 89 | torch.cuda.empty_cache() 90 | 91 | 92 | def _clear_screen(): 93 | if platform.system() == "Windows": 94 | os.system("cls") 95 | else: 96 | os.system("clear") 97 | 98 | 99 | def _print_history(history): 100 | terminal_width = shutil.get_terminal_size()[0] 101 | print(f'History ({len(history)})'.center(terminal_width, '=')) 102 | for index, (query, response) in enumerate(history): 103 | print(f'User[{index}]: {query}') 104 | print(f'QWen[{index}]: {response}') 105 | print('=' * terminal_width) 106 | 107 | 108 | def _get_input() -> str: 109 | while True: 110 | try: 111 | message = input('User> ').strip() 112 | except UnicodeDecodeError: 113 | print('[ERROR] Encoding error in input') 114 | continue 115 | except KeyboardInterrupt: 116 | exit(1) 117 | if message: 118 | return message 119 | print('[ERROR] Query is empty') 120 | 121 | 122 | def _chat_stream(model, tokenizer, query, history): 123 | conversation = [ 124 | {'role': 'system', 'content': 'You are a helpful assistant.'}, 125 | ] 126 | for query_h, response_h in history: 127 | conversation.append({'role': 'user', 'content': query_h}) 128 | conversation.append({'role': 'assistant', 'content': response_h}) 129 | conversation.append({'role': 'user', 'content': query}) 130 | inputs = tokenizer.apply_chat_template( 131 | conversation, 132 | add_generation_prompt=True, 133 | return_tensors='pt', 134 | ) 135 | inputs = inputs.to(model.device) 136 | streamer = TextIteratorStreamer(tokenizer=tokenizer, skip_prompt=True, timeout=60.0, skip_special_tokens=True) 137 | generation_kwargs = dict( 138 | input_ids=inputs, 139 | streamer=streamer, 140 | ) 141 | thread = Thread(target=model.generate, kwargs=generation_kwargs) 142 | thread.start() 143 | 144 | for new_text in streamer: 145 | yield new_text 146 | 147 | 148 | def main(): 149 | parser = argparse.ArgumentParser( 150 | description='QWen2-Instruct command-line interactive chat demo.') 151 | parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH, 152 | help="Checkpoint name or path, default to %(default)r") 153 | parser.add_argument("-s", "--seed", type=int, default=1234, help="Random seed") 154 | parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only") 155 | args = parser.parse_args() 156 | 157 | history, response = [], '' 158 | 159 | model, tokenizer = _load_model_tokenizer(args) 160 | orig_gen_config = deepcopy(model.generation_config) 161 | 162 | _setup_readline() 163 | 164 | _clear_screen() 165 | print(_WELCOME_MSG) 166 | 167 | seed = args.seed 168 | 169 | while True: 170 | query = _get_input() 171 | 172 | # Process commands. 173 | if query.startswith(':'): 174 | command_words = query[1:].strip().split() 175 | if not command_words: 176 | command = '' 177 | else: 178 | command = command_words[0] 179 | 180 | if command in ['exit', 'quit', 'q']: 181 | break 182 | elif command in ['clear', 'cl']: 183 | _clear_screen() 184 | print(_WELCOME_MSG) 185 | _gc() 186 | continue 187 | elif command in ['clear-history', 'clh']: 188 | print(f'[INFO] All {len(history)} history cleared') 189 | history.clear() 190 | _gc() 191 | continue 192 | elif command in ['help', 'h']: 193 | print(_HELP_MSG) 194 | continue 195 | elif command in ['history', 'his']: 196 | _print_history(history) 197 | continue 198 | elif command in ['seed']: 199 | if len(command_words) == 1: 200 | print(f'[INFO] Current random seed: {seed}') 201 | continue 202 | else: 203 | new_seed_s = command_words[1] 204 | try: 205 | new_seed = int(new_seed_s) 206 | except ValueError: 207 | print(f'[WARNING] Fail to change random seed: {new_seed_s!r} is not a valid number') 208 | else: 209 | print(f'[INFO] Random seed changed to {new_seed}') 210 | seed = new_seed 211 | continue 212 | elif command in ['conf']: 213 | if len(command_words) == 1: 214 | print(model.generation_config) 215 | else: 216 | for key_value_pairs_str in command_words[1:]: 217 | eq_idx = key_value_pairs_str.find('=') 218 | if eq_idx == -1: 219 | print('[WARNING] format: =') 220 | continue 221 | conf_key, conf_value_str = key_value_pairs_str[:eq_idx], key_value_pairs_str[eq_idx + 1:] 222 | try: 223 | conf_value = eval(conf_value_str) 224 | except Exception as e: 225 | print(e) 226 | continue 227 | else: 228 | print(f'[INFO] Change config: model.generation_config.{conf_key} = {conf_value}') 229 | setattr(model.generation_config, conf_key, conf_value) 230 | continue 231 | elif command in ['reset-conf']: 232 | print('[INFO] Reset generation config') 233 | model.generation_config = deepcopy(orig_gen_config) 234 | print(model.generation_config) 235 | continue 236 | else: 237 | # As normal query. 238 | pass 239 | 240 | # Run chat. 241 | set_seed(seed) 242 | _clear_screen() 243 | print(f"\nUser: {query}") 244 | print(f"\nQwen2-Instruct: ", end="") 245 | try: 246 | partial_text = '' 247 | for new_text in _chat_stream(model, tokenizer, query, history): 248 | print(new_text, end='', flush=True) 249 | partial_text += new_text 250 | response = partial_text 251 | print() 252 | 253 | except KeyboardInterrupt: 254 | print('[WARNING] Generation interrupted') 255 | continue 256 | 257 | history.append((query, response)) 258 | 259 | 260 | if __name__ == "__main__": 261 | main() 262 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------