├── .gitignore ├── .vscode ├── launch.json └── settings.json ├── LICENSE ├── README.md ├── licenses └── MosaicML-mpt-7b-chat-hf-space.Apache.LICENSE.txt ├── requirements.txt ├── scripts └── chat_play.py └── src ├── callback_text_iterator_streamer.py └── mps_type_monkeypatch.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Falcon play", 9 | "type": "python", 10 | "request": "launch", 11 | "module": "scripts.chat_play", 12 | "justMyCode": false, 13 | "args": [ 14 | "--bf16", 15 | "--trust_remote_code", 16 | "--system_prompt", "Reimu is the shrine maiden of the Hakurei Shrine, responsible for maintaining the Great Hakurei Barrier. Marisa is her friend.", 17 | "--your_name", "Marisa", 18 | "--bot_name", "Reimu", 19 | ], 20 | "env": { 21 | } 22 | }, 23 | { 24 | "name": "Python: Falcon play (Mac)", 25 | "type": "python", 26 | "request": "launch", 27 | "module": "scripts.chat_play", 28 | "justMyCode": false, 29 | "args": [ 30 | "--trust_remote_code", 31 | "--system_prompt", "Reimu is the shrine maiden of the Hakurei Shrine, responsible for maintaining the Great Hakurei Barrier. Marisa is her friend.", 32 | "--your_name", "Marisa", 33 | "--bot_name", "Reimu", 34 | ], 35 | "env": { 36 | // if you are on a recently PyTorch nightly, you actually don't need this. it'll just be a no-op so there's no harm keeping it. 37 | "PYTORCH_ENABLE_MPS_FALLBACK": "1" 38 | } 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.analysis.extraPaths": ["src"] 3 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Alex Birch 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Falcon-Play 2 | 3 | Python script to demonstrate how to invoke models such as [falcon-7b-instruct](https://huggingface.co/tiiuae/falcon-7b-instruct) from the command-line. 4 | 5 | ## Setup 6 | 7 | All instructions are written assuming your command-line shell is bash. 8 | 9 | Clone repository: 10 | 11 | ```bash 12 | git clone https://github.com/Birch-san/falcon-play.git 13 | cd falcon-play 14 | ``` 15 | 16 | ### Create + activate a new virtual environment 17 | 18 | This is to avoid interfering with your current Python environment (other Python scripts on your computer might not appreciate it if you update a bunch of packages they were relying on). 19 | 20 | Follow the instructions for virtualenv, or conda, or neither (if you don't care what happens to other Python scripts on your computer). 21 | 22 | #### Using `venv` 23 | 24 | **Create environment**: 25 | 26 | ```bash 27 | . ./venv/bin/activate 28 | pip install --upgrade pip 29 | ``` 30 | 31 | **Activate environment**: 32 | 33 | ```bash 34 | . ./venv/bin/activate 35 | ``` 36 | 37 | **(First-time) update environment's `pip`**: 38 | 39 | ```bash 40 | pip install --upgrade pip 41 | ``` 42 | 43 | #### Using `conda` 44 | 45 | **Download [conda](https://www.anaconda.com/products/distribution).** 46 | 47 | _Skip this step if you already have conda._ 48 | 49 | **Install conda**: 50 | 51 | _Skip this step if you already have conda._ 52 | 53 | Assuming you're using a `bash` shell: 54 | 55 | ```bash 56 | # Linux installs Anaconda via this shell script. Mac installs by running a .pkg installer. 57 | bash Anaconda-latest-Linux-x86_64.sh 58 | # this step probably works on both Linux and Mac. 59 | eval "$(~/anaconda3/bin/conda shell.bash hook)" 60 | conda config --set auto_activate_base false 61 | conda init 62 | ``` 63 | 64 | **Create environment**: 65 | 66 | ```bash 67 | conda create -n p311-mpt python=3.11 68 | ``` 69 | 70 | **Activate environment**: 71 | 72 | ```bash 73 | conda activate p311-mpt 74 | ``` 75 | 76 | ### Install package dependencies 77 | 78 | **Ensure you have activated the environment you created above.** 79 | 80 | (Optional) treat yourself to latest nightly of PyTorch, with support for Python 3.11 and CUDA 12.1: 81 | 82 | ```bash 83 | # CUDA 84 | pip install --upgrade --pre torch --extra-index-url https://download.pytorch.org/whl/nightly/cu121 85 | # Mac 86 | pip install --upgrade --pre torch --extra-index-url https://download.pytorch.org/whl/nightly/cpu 87 | ``` 88 | 89 | Install dependencies: 90 | 91 | ```bash 92 | pip install -r requirements.txt 93 | ``` 94 | 95 | ## Run: 96 | 97 | From root of repository: 98 | 99 | ```bash 100 | python -m scripts.chat_play --trust_remote_code --bf16 101 | ``` 102 | 103 | On Mac you'll need to disable bfloat16. `PYTORCH_ENABLE_MPS_FALLBACK=1` is not necessary in current PyTorch nightly, but there's no harm keeping it (and it may help on older PyTorch): 104 | 105 | ```bash 106 | PYTORCH_ENABLE_MPS_FALLBACK=1 python -m scripts.chat_play --trust_remote_code 107 | ``` 108 | 109 | ## Fun parameters 110 | 111 | Falcon seems to respond okay to system prompting, so you can give the bot (and yourself) a name, and set the scene at the start of the conversation. 112 | 113 | By default, it is configured with the identity "Girafatron", somebody who really likes giraffes. You are Daniel. 114 | This plays out the scenario from the [model card](https://huggingface.co/tiiuae/falcon-7b-instruct). 115 | 116 | You can become residents of Gensokyo instead: 117 | 118 | ```bash 119 | python -m scripts.chat_play --trust_remote_code --bf16 \ 120 | --system_prompt 'Reimu is the shrine maiden of the Hakurei Shrine, responsible for maintaining the Great Hakurei Barrier. Marisa is her friend.' \ 121 | --your_name Marisa \ 122 | --bot_name Reimu 123 | ``` 124 | 125 | ## Mac support 126 | 127 | I mean it runs, but it's slow. Try [MPT-7B-Chat](https://github.com/Birch-san/mpt-play) instead, which for some reason performs far better on PyTorch MPS (egregious memory leak notwithstanding). 128 | 129 | ## License 130 | 131 | This repository is itself MIT-licensed. 132 | 133 | Includes MIT-licensed code copied from Artidoro Pagnoni's [qlora](https://github.com/artidoro/qlora) and [Apache-licensed](licenses/MosaicML-mpt-7b-chat-hf-space.Apache.LICENSE.txt) code copied from MosaicML's [mpt-7b-chat](https://huggingface.co/spaces/mosaicml/mpt-7b-chat/blob/main/app.py) Huggingface Space. 134 | -------------------------------------------------------------------------------- /licenses/MosaicML-mpt-7b-chat-hf-space.Apache.LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch 2 | # transformers haven't yet cut a release including the 4-bit quantization, so we'll install from source 3 | transformers @ git+https://github.com/huggingface/transformers.git@3416bba 4 | # accelerate haven't yet cut a release including the 4-bit quantization, so we'll install from source 5 | accelerate @ git+https://github.com/huggingface/accelerate.git@0226f75 6 | einops 7 | bitsandbytes>=0.39.0 8 | scipy -------------------------------------------------------------------------------- /scripts/chat_play.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, field 2 | from typing import Optional, TypedDict, NamedTuple, List, Dict, Callable 3 | import torch 4 | from torch import LongTensor 5 | from transformers import ( 6 | AutoConfig, 7 | AutoModelForCausalLM, 8 | AutoTokenizer, 9 | BitsAndBytesConfig, 10 | GenerationConfig, 11 | HfArgumentParser, 12 | set_seed, 13 | StoppingCriteria, 14 | StoppingCriteriaList, 15 | PreTrainedTokenizerBase, 16 | ) 17 | from src.callback_text_iterator_streamer import CallbackTextIteratorStreamer 18 | from src.mps_type_monkeypatch import monkeypatch_tensor_type_mps 19 | import logging 20 | from enum import Enum 21 | import sys 22 | 23 | monkeypatch_tensor_type_mps() 24 | 25 | logger = logging.getLogger(__name__) 26 | 27 | class TokenizerOutput(TypedDict): 28 | input_ids: LongTensor 29 | attention_mask: LongTensor 30 | 31 | class Participant(Enum): 32 | User = 'user' 33 | Assistant = 'assistant' 34 | System = 'system' 35 | 36 | class ParticipantNames(TypedDict): 37 | user: str 38 | assistant: str 39 | 40 | class Message(NamedTuple): 41 | participant: Participant 42 | message: str 43 | 44 | class SufficientResponse(BaseException): ... 45 | 46 | @dataclass 47 | class StopOnTokens(StoppingCriteria): 48 | stop_token_ids: List[int] 49 | def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: 50 | for stop_id in self.stop_token_ids: 51 | if input_ids[0][-1] == stop_id: 52 | return True 53 | return False 54 | 55 | @dataclass 56 | class ModelArguments: 57 | model_name_or_path: Optional[str] = field( 58 | default="tiiuae/falcon-7b-instruct" 59 | ) 60 | trust_remote_code: Optional[bool] = field( 61 | default=False, 62 | metadata={"help": "Enable unpickling of arbitrary code in AutoModelForCausalLM#from_pretrained."} 63 | ) 64 | double_quant: bool = field( 65 | default=True, 66 | metadata={"help": "Compress the quantization statistics through double quantization."} 67 | ) 68 | quant_type: str = field( 69 | default="nf4", 70 | metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} 71 | ) 72 | bits: int = field( 73 | default=4, 74 | metadata={"help": "How many bits to use."} 75 | ) 76 | bf16: Optional[bool] = field( 77 | default=False, 78 | metadata={"help": "Compute type of the model. If quantizing: this is also the compute type used for quantized computations. Prefer to turn this on if you are quantizing and your GPU supports it. You probably also want it even if you're not quantizing."} 79 | ) 80 | context_length: int = field( 81 | default=2048, 82 | metadata={"help": "How many bits to use."} 83 | ) 84 | 85 | @dataclass 86 | class MiscArguments: 87 | seed: Optional[int] = field( 88 | default=64, 89 | metadata={"help": "Random seed, for deterministic generation."} 90 | ) 91 | compile: bool = field( 92 | default=False, 93 | metadata={"help": "Invoke torch.compile() on the model, with mode='max-autotune'. Requires PyTorch 2, CUDA, and either Python 3.10 or Python 3.11 with a recent torch nightly. Will make the first inference from the model take a bit longer, but subsequent inferences will be faster."} 94 | ) 95 | overrun_countermeasures: bool = field( 96 | default=True, 97 | metadata={"help": "Detect when bot is about to start talking to itself; end the generation before that happens. The bot is *supposed* to emit an end-of-sentence token to indicate that it's finished its reply, but very often it neglects to do this, and continues to sequence-complete the conversation. Hence this countermeasure tries to detect and prevent that."} 98 | ) 99 | trim_leading_whitespace: bool = field( 100 | default=True, 101 | metadata={"help": "Don't allow bot to start a reply with a space or a line break."} 102 | ) 103 | your_name: str = field( 104 | default='Daniel', 105 | metadata={"help": "Your name in the chat log."} 106 | ) 107 | bot_name: str = field( 108 | default='Girafatron', 109 | metadata={"help": "Chatbot's name in the chat log."} 110 | ) 111 | system_prompt: str = field( 112 | default="Girafatron is obsessed with giraffes, the most glorious animal on the face of this Earth. Giraftron believes all other animals are irrelevant when compared to the glorious majesty of the giraffe.", 113 | metadata={"help": "Influence how the chatbot responds, by seeding the conversation with some context."} 114 | ) 115 | 116 | @dataclass 117 | class GenerationArguments: 118 | # For more hyperparameters check: 119 | # https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig 120 | # Length arguments 121 | max_new_tokens: Optional[int] = field( 122 | default=256, 123 | metadata={"help": "Maximum number of new tokens to be generated in evaluation or prediction loops" 124 | "if predict_with_generate is set."} 125 | ) 126 | min_new_tokens: Optional[int] = field( 127 | default=None, 128 | metadata={"help": "Minimum number of new tokens to generate."} 129 | ) 130 | 131 | # Generation strategy 132 | # do_sample: Optional[bool] = field(default=True) 133 | num_beams: Optional[int] = field(default=1) 134 | num_beam_groups: Optional[int] = field(default=1) 135 | penalty_alpha: Optional[float] = field(default=None) 136 | use_cache: Optional[bool] = field(default=True) 137 | 138 | # Hyperparameters for logit manipulation 139 | temperature: Optional[float] = field(default=1.0) 140 | top_k: Optional[int] = field(default=10) 141 | top_p: Optional[float] = field(default=1.0) 142 | typical_p: Optional[float] = field(default=1.0) 143 | diversity_penalty: Optional[float] = field(default=0.0) 144 | repetition_penalty: Optional[float] = field(default=1.0) 145 | length_penalty: Optional[float] = field(default=1.0) 146 | no_repeat_ngram_size: Optional[int] = field(default=0) 147 | 148 | def get_model(args: ModelArguments) -> AutoModelForCausalLM: 149 | config = AutoConfig.from_pretrained( 150 | args.model_name_or_path, 151 | trust_remote_code=args.trust_remote_code, 152 | ) 153 | config.update({"max_seq_len": args.context_length}) # was originally trained on 2048 154 | cuda_avail = torch.cuda.is_available() 155 | compute_dtype = torch.bfloat16 if args.bf16 else torch.float16 156 | load_in_4bit = args.bits == 4 and cuda_avail 157 | load_in_8bit = args.bits == 8 and cuda_avail 158 | 159 | quantization_config = BitsAndBytesConfig( 160 | load_in_4bit=load_in_4bit, 161 | load_in_8bit=load_in_8bit, 162 | llm_int8_threshold=6.0, 163 | llm_int8_has_fp16_weight=False, 164 | bnb_4bit_compute_dtype=compute_dtype, 165 | bnb_4bit_use_double_quant=args.double_quant, 166 | bnb_4bit_quant_type=args.quant_type, 167 | ) if cuda_avail else None 168 | 169 | if not cuda_avail: 170 | logger.warning("You don't have CUDA, so we have turned off quantization. If you happen to be on a Mac: you probably have enough unified memory to run in fp16 anyway…") 171 | 172 | if compute_dtype == torch.float16 and cuda_avail and torch.cuda.is_bf16_supported(): 173 | print("Your GPU supports bfloat16; you may want to try it with --bf16 (note: I'm not sure how important this is for inference, but it's certainly preferred when training with 4-bit quantization.)") 174 | 175 | device_map = {'': 'mps'} if torch.backends.mps.is_available() else 'auto' 176 | model = AutoModelForCausalLM.from_pretrained( 177 | args.model_name_or_path, 178 | config=config, 179 | load_in_4bit=load_in_4bit, 180 | load_in_8bit=load_in_8bit, 181 | device_map=device_map, 182 | quantization_config=quantization_config, 183 | torch_dtype=compute_dtype, 184 | trust_remote_code=args.trust_remote_code, 185 | ).eval() 186 | model.config.torch_dtype=compute_dtype 187 | 188 | return model 189 | 190 | def main(): 191 | hfparser = HfArgumentParser((ModelArguments, GenerationArguments, MiscArguments)) 192 | model_args, generation_args, misc_args, extra_args = hfparser.parse_args_into_dataclasses(return_remaining_strings=True) 193 | if extra_args: 194 | raise f"Received unsupported command-line args: {extra_args}" 195 | generation_config = GenerationConfig(**vars(generation_args)) 196 | model: AutoModelForCausalLM = get_model(model_args) 197 | set_seed(misc_args.seed) 198 | if misc_args.compile: 199 | torch.compile(model, mode='max-autotune') 200 | 201 | tokenizer: PreTrainedTokenizerBase = AutoTokenizer.from_pretrained( 202 | model_args.model_name_or_path, 203 | padding=False, 204 | add_special_tokens=False, 205 | ) 206 | generation_config.eos_token_id = generation_config.pad_token_id = tokenizer.eos_token_id 207 | 208 | stop = StopOnTokens([tokenizer.eos_token_id]) 209 | stopping_criteria=StoppingCriteriaList([stop]) 210 | 211 | history: List[Message] = [Message(Participant.System, misc_args.system_prompt)] if misc_args.system_prompt else [] 212 | 213 | reset_ansi='\x1b[0m' 214 | blue_ansi='\x1b[31;34m' 215 | green_ansi='\x1b[31;32m' 216 | purple_ansi='\x1b[31;35m' 217 | prompt=f'{purple_ansi}$ ' 218 | 219 | participant_names: Dict[Participant, str] = { 220 | Participant.User: misc_args.your_name, 221 | Participant.Assistant: misc_args.bot_name, 222 | } 223 | 224 | tokenizer: PreTrainedTokenizerBase = AutoTokenizer.from_pretrained(model_args.model_name_or_path) 225 | 226 | first = True 227 | while True: 228 | try: 229 | user_input = input(f'{blue_ansi}Type a message to begin the conversation…{reset_ansi}\n{prompt}' if first else prompt) 230 | except KeyboardInterrupt: 231 | sys.exit(0) 232 | print(reset_ansi, end='') 233 | 234 | first = False 235 | history += [Message(Participant.User, user_input)] 236 | 237 | chat_to_complete: str = '\n'.join([ 238 | *[ 239 | f"{'' if participant is Participant.System else f'{participant_names[participant]}: '}{message}" 240 | for participant, message in history 241 | ], 242 | f'{participant_names[Participant.Assistant]}:' 243 | ]) 244 | 245 | tokenized_prompts: TokenizerOutput = tokenizer(chat_to_complete, return_tensors='pt', padding=False, add_special_tokens=False) 246 | 247 | print(green_ansi, end='', flush=True) 248 | 249 | response = '' 250 | if misc_args.trim_leading_whitespace: 251 | strip_whitespace: Callable[[str], str] = lambda x: x.lstrip() if response == '' else x 252 | else: 253 | strip_whitespace: Callable[[str], str] = lambda x: x 254 | 255 | if misc_args.overrun_countermeasures: 256 | # the model may continue adding to the conversation (replying to itself) instead of emitting an EOS token. 257 | # we try to intercept this. If it looks like it's starting a new message in the voice of either of the chat participants: don't print that, and stop generation. 258 | acc_overrun = '' 259 | 260 | def on_text(message: str, stream_end = False): 261 | nonlocal response, acc_overrun 262 | 263 | overrun_and_message = f'{acc_overrun}{message}' 264 | 265 | newline_ix = overrun_and_message.find('\n') 266 | if newline_ix > -1: 267 | pre_newline, post_newline = overrun_and_message.split('\n', maxsplit=1) 268 | 269 | potential_participant_name = post_newline[:overrun_and_message.find(':')] 270 | if potential_participant_name == f'{misc_args.your_name}:' or potential_participant_name == f'{misc_args.bot_name}:': 271 | raise SufficientResponse() 272 | if potential_participant_name.rstrip(f'{misc_args.your_name}:') == '' or potential_participant_name.rstrip(f'{misc_args.bot_name}:') == '': 273 | # could potentially grow to match one of the names. we need to accumulate to see whether that's where the bot was going. 274 | acc_overrun = f'\n{post_newline}' 275 | 276 | addendum: str = strip_whitespace(pre_newline) 277 | response += addendum 278 | print(addendum, end='', flush=True) 279 | return 280 | # the potential_participant_name cannot grow into a reply from either chat participant, so this must be something else. flush everything we accumulated. 281 | 282 | addendum: str = strip_whitespace(overrun_and_message) 283 | response += addendum 284 | print(addendum, end='', flush=True) 285 | acc_overrun = '' 286 | else: 287 | def on_text(message: str, stream_end = False): 288 | nonlocal response 289 | addendum: str = strip_whitespace(message) 290 | response += addendum 291 | print(addendum, end='', flush=True) 292 | 293 | streamer = CallbackTextIteratorStreamer(tokenizer, callback=on_text, skip_prompt=True, skip_special_tokens=True) 294 | 295 | try: 296 | prediction: LongTensor = model.generate( 297 | input_ids=tokenized_prompts.input_ids.to(model.device), 298 | attention_mask=tokenized_prompts.attention_mask.to(model.device), 299 | generation_config=generation_config, 300 | do_sample=generation_config.temperature > 0., 301 | stopping_criteria=stopping_criteria, 302 | streamer=streamer, 303 | ) 304 | # if you wanted to see the result, you can do so like this: 305 | # decode: List[str] = tokenizer.decode(prediction[0,tokenized_prompts.input_ids.size(-1):], skip_special_tokens=True, clean_up_tokenization_spaces=True) 306 | # but we're already streaming it to the console via our callback 307 | except (KeyboardInterrupt, SufficientResponse): 308 | pass 309 | 310 | # reset ANSI control sequence (plus line break) 311 | print(reset_ansi) 312 | 313 | # TODO: cull older history, otherwise context will just keep growing larger. 314 | # ideally by measuring each message to work out the smallest cull possible. 315 | history += [Message(Participant.Assistant, response)] 316 | 317 | if __name__ == "__main__": 318 | main() -------------------------------------------------------------------------------- /src/callback_text_iterator_streamer.py: -------------------------------------------------------------------------------- 1 | from transformers import AutoTokenizer, TextIteratorStreamer 2 | from typing import Optional, Protocol 3 | 4 | class TextCallback(Protocol): 5 | def __call__(self, text: str, stream_end: bool = False) -> None: ... 6 | 7 | 8 | class CallbackTextIteratorStreamer(TextIteratorStreamer): 9 | callback: TextCallback 10 | def __init__( 11 | self, tokenizer: AutoTokenizer, callback: TextCallback, skip_prompt: bool = False, timeout: Optional[float] = None, **decode_kwargs 12 | ): 13 | super().__init__(tokenizer, skip_prompt, **decode_kwargs) 14 | self.callback = callback 15 | 16 | def on_finalized_text(self, text: str, stream_end: bool = False): 17 | self.callback(text, stream_end=stream_end) 18 | -------------------------------------------------------------------------------- /src/mps_type_monkeypatch.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import Tensor 3 | import logging 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | def monkeypatch_tensor_type_mps(): 8 | # Falcon's modelling_RW.py`RotaryEmbedding#cos_sin has a hardcoded dtype=torch.bfloat16 param, which is no bueno for MPS 9 | # https://huggingface.co/tiiuae/falcon-7b-instruct/blob/b6efaea5d78e4313145bda4d688675414a76fc22/modelling_RW.py#L71 10 | # I don't know how to import RotaryEmbedding (it doesn't begin on our PYTHONPATH; Huggingface libraries import it somehow later) 11 | # but I *do* know how to monkeypatch torch.Tensor.type, so let's gooo 12 | if torch.backends.mps.is_available(): 13 | logger.warning("Monkey-patching Tensor#type to avoid casting to bfloat16 (and prefer float16), to get around a hardcoded cast which wouldn't work on Mac.") 14 | orig_type = Tensor.type 15 | def monkeypatched_type(self: Tensor, *args, **kwargs): 16 | if args: 17 | first, *rest = args 18 | if first is torch.bfloat16: 19 | return orig_type(self, torch.float16, *rest, **kwargs) 20 | return orig_type(self, *args, **kwargs) 21 | Tensor.type = monkeypatched_type --------------------------------------------------------------------------------