├── .dockerignore ├── cog.yaml ├── scripts ├── tensorize_model.py └── download_and_prepare_model.py ├── README.md ├── predict.py ├── LICENSE └── subclass.py /.dockerignore: -------------------------------------------------------------------------------- 1 | model/*.bin 2 | model/*.tensors 3 | notebooks -------------------------------------------------------------------------------- /cog.yaml: -------------------------------------------------------------------------------- 1 | # Configuration for Cog ⚙️ 2 | # Reference: https://github.com/replicate/cog/blob/main/docs/yaml.md 3 | 4 | build: 5 | # set to true if your model requires a GPU 6 | gpu: true 7 | cuda: "11.7" 8 | 9 | # a list of ubuntu apt packages to install 10 | # system_packages: 11 | # - "libgl1-mesa-glx" 12 | # - "libglib2.0-0" 13 | 14 | # python version in the form '3.8' or '3.8.12' 15 | python_version: "3.8" 16 | 17 | # a list of packages in the format == 18 | python_packages: 19 | - "torch==1.13.1" 20 | - "einops==0.5.0" 21 | - "packaging==23.1" 22 | - "transformers==4.28" 23 | - "tensorizer==1.1.0" 24 | 25 | # commands run after the environment is setup 26 | run: 27 | - pip install flash-attn==v1.0.3.post0 28 | - pip install triton==2.0.0.dev20221202 29 | - pip install xentropy-cuda-lib@git+https://github.com/HazyResearch/flash-attention.git@v0.2.8#subdirectory=csrc/xentropy 30 | - "echo 'deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main' | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list" 31 | - "curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -" 32 | - "apt-get update && apt-get install google-cloud-cli" 33 | 34 | # - "echo another command if needed" 35 | 36 | # predict.py defines how predictions are run on your model 37 | predict: "predict.py:Predictor" 38 | -------------------------------------------------------------------------------- /scripts/tensorize_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import torch 3 | import os 4 | import argparse 5 | import logging 6 | import sys 7 | 8 | from tensorizer import TensorSerializer 9 | from transformers import AutoModelForCausalLM, AutoConfig 10 | 11 | 12 | logger = logging.getLogger(__name__) 13 | logging.basicConfig(level=logging.INFO, stream=sys.stdout) 14 | 15 | def tensorize_model( 16 | model_name: str, 17 | model_path: str, 18 | tensorizer_path: str, 19 | dtype: str = "fp32", 20 | ) -> dict: 21 | """ 22 | Create a tensorized version of model weights. If fp16 or bf16 is True, 23 | the model will be converted to fp16 or bf16. 24 | 25 | If `model_path` is None weights will be saved in `./model_weights/torch_weights/model_name`. 26 | If `tensorizer_path` is None weights will be saved in `./model_weights/tensorizer_weights/model_name/dtype_str`. 27 | 28 | Args: 29 | model_name (str): Name of model on hugging face hub 30 | model_path (str, optional): Local path where model weights are saved. 31 | tensorizer_path (str, optional): Local path where tensorizer weights are saved. 32 | path (str): Local path where tensorized model weights are saved 33 | dtype (str): One of `"fp32"`, `"fp16"`, and `"bf16"`. Defaults to `"fp32"`. 34 | 35 | Returns: 36 | dict: Dictionary containing the tensorized model path and dtype. 37 | """ 38 | 39 | 40 | if dtype == 'fp32' or dtype is None: 41 | torch_dtype = torch.float32 42 | 43 | elif dtype == 'bf16': 44 | torch_dtype = torch.bfloat16 45 | 46 | elif dtype == 'fp16': 47 | torch_dtype = torch.float16 48 | 49 | logger.info(f"Loading {model_name} in {dtype} from {model_path}...") 50 | 51 | model = AutoModelForCausalLM.from_pretrained( 52 | model_path, low_cpu_mem_usage=True 53 | ).to('cuda:0') 54 | 55 | logger.info(f"Tensorizing model {model_name} in {dtype} and writing tensors to {tensorizer_path}...") 56 | 57 | serializer = TensorSerializer(tensorizer_path) 58 | serializer.write_module(model) 59 | serializer.close() 60 | 61 | # Write config to tensorized model weights directory 62 | # dir_path = os.path.dirname(tensorizer_path) 63 | # config_path = os.path.join(dir_path, 'config.json') 64 | model_config = model.config 65 | model_config.save_pretrained(tensorizer_path) 66 | 67 | logger.info(f"Tensorized model {model_name} in {dtype} and wrote tensors to {tensorizer_path} and config to {config_path}...") 68 | 69 | return {"tensorized_weights_path": tensorizer_path, "dtype": dtype} 70 | 71 | if __name__ == "__main__": 72 | 73 | 74 | parser = argparse.ArgumentParser(description=( 75 | "A simple script for tensorizing a torch model." 76 | ) 77 | ) 78 | 79 | parser.add_argument("--model_name", type=str) 80 | parser.add_argument("--model_path", type=str, default=None) 81 | parser.add_argument("--tensorizer_path", type=str, default=None) 82 | parser.add_argument("--dtype", type=str, default="fp32") 83 | 84 | args = parser.parse_args() 85 | 86 | model_info = tensorize_model( 87 | args.model_name, 88 | model_path=args.model_path, 89 | tensorizer_path=args.tensorizer_path, 90 | dtype=args.dtype 91 | ) -------------------------------------------------------------------------------- /scripts/download_and_prepare_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | import os 5 | import shutil 6 | import argparse 7 | import logging 8 | import sys 9 | import torch 10 | 11 | from distutils.dir_util import copy_tree 12 | from pathlib import Path 13 | from tempfile import TemporaryDirectory 14 | from huggingface_hub import snapshot_download, login 15 | from tensorizer import TensorSerializer 16 | from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig 17 | 18 | from tensorize_model import tensorize_model 19 | 20 | logger = logging.getLogger(__name__) 21 | logging.basicConfig(level=logging.INFO, stream=sys.stdout) 22 | 23 | 24 | def download_model_from_hf_hub( 25 | model_name: str, 26 | model_path: str, 27 | rm_existing_model: bool = True, 28 | ) -> dict: 29 | """ 30 | This function downloads a model from the Hugging Face Hub and saves it locally. 31 | It also saves the tokenizer in a separate location so that it can be easely included in a docker Image 32 | without including the model weights. 33 | 34 | Args: 35 | model_name (str): Name of model on hugging face hub 36 | path (str): Local path where model is saved 37 | rm_existing_model (bool, optional): Whether to remove the existing model or not. Defaults to False. 38 | 39 | Returns: 40 | dict: Dictionary containing the model name and path 41 | """ 42 | 43 | # model_weights_path = os.path.join(os.getcwd(), "model_weights/torch_weights") 44 | # model_path = os.path.join(model_weights_path, model_name) 45 | 46 | 47 | if rm_existing_model: 48 | logger.info(f"Removing existing model at {model_path}") 49 | if os.path.exists(model_path): 50 | shutil.rmtree(model_path) 51 | 52 | # setup temporary directory 53 | with TemporaryDirectory() as tmpdir: 54 | logger.info(f"Downloading {model_name} weights to temp...") 55 | 56 | snapshot_dir = snapshot_download( 57 | repo_id=model_name, 58 | cache_dir=tmpdir, 59 | allow_patterns=["*.bin", "*.json", "*.md", "tokenizer.model", "checkpoint.pt", "*.py"], 60 | ) 61 | # copy snapshot to model dir 62 | logger.info(f"Copying weights to {model_path}...") 63 | copy_tree(snapshot_dir, str(model_path)) 64 | 65 | return {"model_name": model_name, "model_path": model_path} 66 | 67 | 68 | def download_hf_model_and_copy_tokenizer( 69 | model_name: str, 70 | model_path: str, 71 | tokenizer_path: str, 72 | rm_existing_model: bool = True, 73 | ): 74 | 75 | model_info = download_model_from_hf_hub(model_name, model_path) 76 | 77 | if tokenizer_path: 78 | # Move tokenizer to separate location 79 | logging.info(f"Copying tokenizer and model config to {tokenizer_path}...") 80 | tokenizer = AutoTokenizer.from_pretrained(model_path, padding_side="left") 81 | tokenizer.save_pretrained(tokenizer_path) 82 | 83 | # Set the source and destination file paths 84 | config_path = os.path.join(model_path, "config.json") 85 | 86 | # Use the shutil.copy() function to copy the file to the destination directory 87 | shutil.copy(config_path, tokenizer_path) 88 | 89 | return model_info 90 | 91 | if __name__ == "__main__": 92 | parser = argparse.ArgumentParser() 93 | parser.add_argument("--model_name", type=str) 94 | parser.add_argument("--model_path", type=str) 95 | parser.add_argument("--tokenizer_path", type=str, default=None) 96 | parser.add_argument("--hf_token", type=str, default=None) 97 | 98 | 99 | parser.add_argument("--tensorize", action="store_true", default=False) 100 | parser.add_argument("--dtype", type=str, default="fp32") 101 | 102 | args = parser.parse_args() 103 | if args.hf_token is not None: 104 | login(token=args.hf_token) 105 | 106 | download_hf_model_and_copy_tokenizer(args.model_name, model_path=args.model_path, tokenizer_path=args.tokenizer_path) 107 | 108 | if args.tensorize: 109 | model = tensorize_model(args.model_name, dtype=args.dtype, tensorizer_path=args.model_path) 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cog-mpt-7b-storywriter-65k 2 | [![Replicate](https://replicate.com/replicate/mpt-7b-storywriter/badge)](https://replicate.com/replicate/mpt-7b-storywriter) 3 | 4 | A cog implementation of MosaicML's MPT-7B-StoryWriter-65k+ Large Language Model 5 | 6 | This is a guide to running MPT-7B-StoryWriter-65k+ in the cloud using Replicate. You'll use the [Cog](https://github.com/replicate/cog) command-line tool to package the model and push it to Replicate as a web interface and API. 7 | 8 | MPT-7B-StoryWriter-65k+ is a language model that specializes in generating fictional stories with lengthy context lengths. The model was created by finetuning MPT-7B with a context length of 65k tokens on a filtered fiction subset of the books3 dataset. Thanks to ALiBi, the model can extrapolate beyond 65k tokens at inference time, allowing for longer story generations. The MosaicML team demonstrated the ability to generate stories as long as 84k tokens on a single node of 8 A100-80GB GPUs in their blog [post](https://www.mosaicml.com/blog/mpt-7b). 9 | 10 | ## Prerequisites 11 | 12 | - **GPU machine**. You'll need a Linux machine with an NVIDIA GPU attached and the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#docker) installed. If you don't already have access to a machine with a GPU, check out our [guide to getting a 13 | GPU machine](https://replicate.com/docs/guides/get-a-gpu-machine). 14 | 15 | - **Docker**. You'll be using the [Cog](https://github.com/replicate/cog) command-line tool to build and push a model. Cog uses Docker to create containers for models. 16 | 17 | ## Step 0: Install Cog 18 | 19 | First, [install Cog](https://github.com/replicate/cog#install): 20 | 21 | ``` 22 | sudo curl -o /usr/local/bin/cog -L "https://github.com/replicate/cog/releases/latest/download/cog_$(uname -s)_$(uname -m)" 23 | sudo chmod +x /usr/local/bin/cog 24 | ``` 25 | 26 | ## Step 1: Set up weights 27 | 28 | You can use the following script to pull the model weights from the Hugging Face Hub. We also recommend using `tensorizer` to tensorize your weights, which will dramatically reduce the time it takes to load your model. 29 | 30 | 31 | ``` 32 | chmod +x scripts/download_and_prepare_model.py 33 | cog run python scripts/download_and_prepare_model.py --model_name mosaicml/mpt-7b-storywriter --model_path model --tensorize --tensorizer_path model/mpt-7b-storywriter-65.tensors 34 | ``` 35 | 36 | ## Step 2: Run the model 37 | 38 | You can run the model locally to test it: 39 | 40 | ``` 41 | cog predict -i prompt="On a dark and stormy night " 42 | ``` 43 | 44 | ## Step 3: Push your model weights to cloud storage 45 | 46 | If you want to deploy your own cog version of this model, we recommend pushing the tensorized weights to a public bucket. You can then configure the `setup` method in `predict.py` to pull the tensorized weights. 47 | 48 | Currently, we provide boiler-plate code for pulling weights from GCP. To use the current configuration, simply set `TENSORIZER_WEIGHTS_PATH` to the public Google Cloud Storage Bucket path of your tensorized model weights. At setup time, they'll be downloaded and loaded into memory. 49 | 50 | Alternatively, you can implement your own solution using your cloud storage provider of choice. 51 | 52 | To see if the remote weights configuration works, you can run the model locally. 53 | 54 | ## Step 4: Create a model on Replicate 55 | 56 | Go to [replicate.com/create](https://replicate.com/create) to create a Replicate model. 57 | 58 | Make sure to specify "private" to keep the model private. 59 | 60 | ## Step 5: Configure the model to run on A100 GPUs 61 | 62 | Replicate supports running models on a variety of GPUs. The default GPU type is a T4, but for best performance you'll want to configure your model to run on an A100. 63 | 64 | Click on the "Settings" tab on your model page, scroll down to "GPU hardware", and select "A100". Then click "Save". 65 | 66 | ## Step 6: Push the model to Replicate 67 | 68 | Log in to Replicate: 69 | 70 | ``` 71 | cog login 72 | ``` 73 | 74 | Push the contents of your current directory to Replicate, using the model name you specified in step 3: 75 | 76 | ``` 77 | cog push r8.im/username/modelname 78 | ``` 79 | 80 | [Learn more about pushing models to Replicate.](https://replicate.com/docs/guides/push-a-model) 81 | -------------------------------------------------------------------------------- /predict.py: -------------------------------------------------------------------------------- 1 | import time 2 | from typing import Optional 3 | import subprocess 4 | 5 | import torch 6 | import os 7 | 8 | from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM 9 | from tensorizer import TensorDeserializer 10 | from tensorizer.utils import no_init_or_tensor 11 | from collections import OrderedDict 12 | from cog import BasePredictor, ConcatenateIterator, Input, Path 13 | 14 | 15 | # from config import DEFAULT_MODEL_NAME, DEFAULT_CONFIG_PATH, load_tokenizer, load_tensorizer 16 | from subclass import YieldingMPT 17 | 18 | TENSORIZER_WEIGHTS_PATH = "model/mpt-7b-storywriter-65.tensors" # path from which we pull weights when there's no COG_WEIGHTS environment variable 19 | # TENSORIZER_WEIGHTS_PATH = None 20 | 21 | DEFAULT_CONFIG_PATH = "model/" 22 | TOKENIZER_PATH = "model/" 23 | 24 | def maybe_download(path): 25 | if path.startswith("gs://"): 26 | st = time.time() 27 | output_path = "/tmp/weights.tensors" 28 | subprocess.check_call(["gcloud", "storage", "cp", path, output_path]) 29 | print(f"weights downloaded in {time.time() - st}") 30 | return output_path 31 | return path 32 | 33 | 34 | class Predictor(BasePredictor): 35 | def setup(self, weights: Optional[Path] = None): 36 | self.device = "cuda" if torch.cuda.is_available() else "cpu" 37 | 38 | # set TOKENIZERS_PARALLELISM to false to avoid a warning 39 | os.environ["TOKENIZERS_PARALLELISM"] = "false" 40 | 41 | if weights is not None and weights.name == "weights": 42 | # bugfix 43 | weights = None 44 | if weights is None and TENSORIZER_WEIGHTS_PATH: 45 | self.model = self.load_tensorizer( 46 | weights=maybe_download(TENSORIZER_WEIGHTS_PATH), plaid_mode=True, cls=YieldingMPT, config_path=DEFAULT_CONFIG_PATH, 47 | ) 48 | 49 | elif hasattr(weights, "filename") and "tensors" in weights.filename: 50 | self.model = self.load_tensorizer( 51 | weights=weights, plaid_mode=True, cls=YieldingMPT, config_path=DEFAULT_CONFIG_PATH, 52 | ) 53 | elif hasattr(weights, "suffix") and "tensors" in weights.suffix: 54 | self.model = self.load_tensorizer( 55 | weights=weights, plaid_mode=True, cls=YieldingMPT 56 | ) 57 | # elif "tensors" in weights: 58 | # self.model = self.load_tensorizer( 59 | # weights=weights, plaid_mode=True, cls=YieldingMPT 60 | # ) 61 | else: 62 | weights = "./model/" 63 | 64 | self.model = self.load_huggingface_model(weights=weights) 65 | 66 | self.tokenizer = self.load_tokenizer(TOKENIZER_PATH) 67 | 68 | def load_tokenizer(self, path): 69 | tokenizer = AutoTokenizer.from_pretrained(path) 70 | 71 | return tokenizer 72 | 73 | def load_huggingface_model(self, weights=None): 74 | 75 | config = AutoConfig.from_pretrained( 76 | weights, 77 | trust_remote_code=True 78 | ) 79 | 80 | config.attn_config['attn_impl'] = 'triton' 81 | 82 | st = time.time() 83 | print(f"loading weights from {weights} w/o tensorizer") 84 | model = YieldingMPT.from_pretrained( 85 | weights, torch_dtype=torch.bfloat16, trust_remote_code=True 86 | ) 87 | model.to(self.device) 88 | print(f"weights loaded in {time.time() - st}") 89 | return model 90 | 91 | def load_tensorizer(self, weights, plaid_mode, cls, config_path): 92 | st = time.time() 93 | print(f"deserializing weights from {weights}") 94 | 95 | config = AutoConfig.from_pretrained(config_path, trust_remote_code=True) 96 | config.attn_config['attn_impl'] = 'triton' 97 | 98 | 99 | model = no_init_or_tensor( 100 | lambda: cls.from_pretrained( 101 | None, config=config, state_dict=OrderedDict(), trust_remote_code=True, 102 | ) 103 | ) 104 | 105 | 106 | des = TensorDeserializer(weights, plaid_mode=True) 107 | des.load_into_module(model) 108 | model = model.to(dtype=torch.bfloat16) 109 | 110 | print(f"weights loaded in {time.time() - st}") 111 | return model 112 | 113 | def predict( 114 | self, 115 | prompt: str = Input(description=f"Prompt to send to MPT-StoryWriter."), 116 | max_length: int = Input( 117 | description="Maximum number of tokens to generate. A word is generally 2-3 tokens", 118 | ge=1, 119 | default=500, 120 | ), 121 | temperature: float = Input( 122 | description="Adjusts randomness of outputs, greater than 1 is random and 0 is deterministic, 0.75 is a good starting value.", 123 | ge=0.01, 124 | le=5, 125 | default=0.75, 126 | ), 127 | top_p: float = Input( 128 | description="When decoding text, samples from the top p percentage of most likely tokens; lower to ignore less likely tokens", 129 | ge=0.01, 130 | le=1.0, 131 | default=1.0, 132 | ), 133 | repetition_penalty: float = Input( 134 | description="Penalty for repeated words in generated text; 1 is no penalty, values greater than 1 discourage repetition, less than 1 encourage it.", 135 | ge=0.01, 136 | le=5, 137 | default=1, 138 | ), 139 | length_penalty: float = Input( 140 | description="Increasing the length_penalty parameter above 1.0 will cause the model to favor longer sequences, while decreasing it below 1.0 will cause the model to favor shorter sequences.", 141 | ge=0.01, 142 | le=5, 143 | default=1, 144 | ), 145 | no_repeat_ngram_size: int = Input( 146 | description="If set to int > 0, all ngrams of size no_repeat_ngram_size can only occur once.", 147 | ge=0, 148 | default=0, 149 | ), 150 | stop_sequence: str = Input( 151 | description="Generation will hault if this token is produced. Currently, only single token stop sequences are support and it is recommended to use `###` as the stop sequence if you want to control generation termination.", 152 | default=None, 153 | ), 154 | seed: int = Input( 155 | description="Set seed for reproducible outputs. Set to -1 for random seed.", 156 | ge=-1, 157 | default=-1, 158 | ), 159 | debug: bool = Input( 160 | description="provide debugging output in logs", default=False 161 | ), 162 | ) -> ConcatenateIterator[str]: 163 | input = self.tokenizer(prompt, return_tensors="pt").input_ids.to(self.device) 164 | 165 | # set torch seed 166 | if seed == -1: 167 | torch.seed() 168 | 169 | else: 170 | torch.manual_seed(seed) 171 | torch.cuda.manual_seed(seed) 172 | 173 | with torch.inference_mode(): 174 | first_token_yielded = False 175 | prev_ids = [] 176 | for output in self.model.generate( 177 | input, 178 | max_length=max_length, 179 | do_sample=True, 180 | temperature=temperature, 181 | top_p=top_p, 182 | repetition_penalty=repetition_penalty, 183 | length_penalty=length_penalty, 184 | no_repeat_ngram_size=no_repeat_ngram_size, 185 | ): 186 | cur_id = output.item() 187 | 188 | # in order to properly handle spaces, we need to do our own tokenizing. Fun! 189 | # we're building up a buffer of sub-word / punctuation tokens until we hit a space, and then yielding whole words + punctuation. 190 | cur_token = self.tokenizer.convert_ids_to_tokens(cur_id) 191 | 192 | # skip initial newline, which this almost always yields. hack - newline id = 13. 193 | if not first_token_yielded and not prev_ids and cur_id == 187: 194 | continue 195 | 196 | # underscore means a space, means we yield previous tokens 197 | if cur_token.startswith("Ġ"): # this is not a standard underscore. 198 | # first token 199 | if not prev_ids: 200 | prev_ids = [cur_id] 201 | continue 202 | 203 | # there are tokens to yield 204 | else: 205 | token = self.tokenizer.decode(prev_ids) 206 | prev_ids = [cur_id] 207 | 208 | if not first_token_yielded: 209 | # no leading space for first token 210 | token = token.strip() 211 | first_token_yielded = True 212 | yield token 213 | # End token 214 | elif cur_token == "<|endoftext|>": 215 | break 216 | 217 | elif stop_sequence and cur_token == stop_sequence: 218 | break 219 | 220 | else: 221 | prev_ids.append(cur_id) 222 | continue 223 | 224 | # remove any special tokens such as 225 | token = self.tokenizer.decode(prev_ids, skip_special_tokens=True) 226 | if not first_token_yielded: 227 | # no leading space for first token 228 | token = token.strip() 229 | first_token_yielded = True 230 | yield token 231 | 232 | if debug: 233 | print(f"cur memory: {torch.cuda.memory_allocated()}") 234 | print(f"max allocated: {torch.cuda.max_memory_allocated()}") 235 | print(f"peak memory: {torch.cuda.max_memory_reserved()}") 236 | 237 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /subclass.py: -------------------------------------------------------------------------------- 1 | """sampling code pulled from Transformers & slightly modified to stream tokens""" 2 | import warnings 3 | from typing import List, Optional, Union 4 | 5 | import torch 6 | import torch.distributed as dist 7 | from torch import nn 8 | 9 | from transformers.generation.logits_process import LogitsProcessorList 10 | from transformers.generation.stopping_criteria import StoppingCriteriaList, validate_stopping_criteria 11 | from transformers.generation.utils import SampleOutput, SampleDecoderOnlyOutput, SampleEncoderDecoderOutput 12 | 13 | from model.modeling_mpt import MPTForCausalLM 14 | 15 | class YieldingMPT(MPTForCausalLM): 16 | """Overriding sample to yield tokens""" 17 | def sample( 18 | self, 19 | input_ids: torch.LongTensor, 20 | logits_processor: Optional[LogitsProcessorList] = None, 21 | stopping_criteria: Optional[StoppingCriteriaList] = None, 22 | logits_warper: Optional[LogitsProcessorList] = None, 23 | max_length: Optional[int] = None, 24 | pad_token_id: Optional[int] = None, 25 | eos_token_id: Optional[Union[int, List[int]]] = None, 26 | output_attentions: Optional[bool] = None, 27 | output_hidden_states: Optional[bool] = None, 28 | output_scores: Optional[bool] = None, 29 | return_dict_in_generate: Optional[bool] = None, 30 | synced_gpus: Optional[bool] = False, 31 | **model_kwargs, 32 | ) -> Union[SampleOutput, torch.LongTensor]: 33 | r""" 34 | Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and 35 | can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models. 36 | 37 | 38 | 39 | In most cases, you do not need to call [`~generation.GenerationMixin.sample`] directly. Use generate() instead. 40 | For an overview of generation strategies and code examples, check the [following 41 | guide](./generation_strategies). 42 | 43 | 44 | 45 | Parameters: 46 | input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): 47 | The sequence used as a prompt for the generation. 48 | logits_processor (`LogitsProcessorList`, *optional*): 49 | An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`] 50 | used to modify the prediction scores of the language modeling head applied at each generation step. 51 | stopping_criteria (`StoppingCriteriaList`, *optional*): 52 | An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`] 53 | used to tell if the generation loop should stop. 54 | logits_warper (`LogitsProcessorList`, *optional*): 55 | An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsWarper`] used 56 | to warp the prediction score distribution of the language modeling head applied before multinomial 57 | sampling at each generation step. 58 | max_length (`int`, *optional*, defaults to 20): 59 | **DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated 60 | tokens. The maximum length of the sequence to be generated. 61 | pad_token_id (`int`, *optional*): 62 | The id of the *padding* token. 63 | eos_token_id (`int`, *optional*): 64 | The id of the *end-of-sequence* token. 65 | output_attentions (`bool`, *optional*, defaults to `False`): 66 | Whether or not to return the attentions tensors of all attention layers. See `attentions` under 67 | returned tensors for more details. 68 | output_hidden_states (`bool`, *optional*, defaults to `False`): 69 | Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors 70 | for more details. 71 | output_scores (`bool`, *optional*, defaults to `False`): 72 | Whether or not to return the prediction scores. See `scores` under returned tensors for more details. 73 | return_dict_in_generate (`bool`, *optional*, defaults to `False`): 74 | Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. 75 | synced_gpus (`bool`, *optional*, defaults to `False`): 76 | Whether to continue running the while loop until max_length (needed for ZeRO stage 3) 77 | model_kwargs: 78 | Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is 79 | an encoder-decoder model the kwargs should include `encoder_outputs`. 80 | 81 | Return: 82 | [`~generation.SampleDecoderOnlyOutput`], [`~generation.SampleEncoderDecoderOutput`] or `torch.LongTensor`: 83 | A `torch.LongTensor` containing the generated tokens (default behaviour) or a 84 | [`~generation.SampleDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and 85 | `return_dict_in_generate=True` or a [`~generation.SampleEncoderDecoderOutput`] if 86 | `model.config.is_encoder_decoder=True`. 87 | 88 | Examples: 89 | 90 | ```python 91 | >>> from transformers import ( 92 | ... AutoTokenizer, 93 | ... AutoModelForCausalLM, 94 | ... LogitsProcessorList, 95 | ... MinLengthLogitsProcessor, 96 | ... TopKLogitsWarper, 97 | ... TemperatureLogitsWarper, 98 | ... StoppingCriteriaList, 99 | ... MaxLengthCriteria, 100 | ... ) 101 | >>> import torch 102 | 103 | >>> tokenizer = AutoTokenizer.from_pretrained("gpt2") 104 | >>> model = AutoModelForCausalLM.from_pretrained("gpt2") 105 | 106 | >>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token 107 | >>> model.config.pad_token_id = model.config.eos_token_id 108 | >>> model.generation_config.pad_token_id = model.config.eos_token_id 109 | 110 | >>> input_prompt = "Today is a beautiful day, and" 111 | >>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids 112 | 113 | >>> # instantiate logits processors 114 | >>> logits_processor = LogitsProcessorList( 115 | ... [ 116 | ... MinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id), 117 | ... ] 118 | ... ) 119 | >>> # instantiate logits processors 120 | >>> logits_warper = LogitsProcessorList( 121 | ... [ 122 | ... TopKLogitsWarper(50), 123 | ... TemperatureLogitsWarper(0.7), 124 | ... ] 125 | ... ) 126 | 127 | >>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)]) 128 | 129 | >>> torch.manual_seed(0) # doctest: +IGNORE_RESULT 130 | >>> outputs = model.sample( 131 | ... input_ids, 132 | ... logits_processor=logits_processor, 133 | ... logits_warper=logits_warper, 134 | ... stopping_criteria=stopping_criteria, 135 | ... ) 136 | 137 | >>> tokenizer.batch_decode(outputs, skip_special_tokens=True) 138 | ['Today is a beautiful day, and a wonderful day.\n\nI was lucky enough to meet the'] 139 | ```""" 140 | # init values 141 | logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList() 142 | stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList() 143 | if max_length is not None: 144 | warnings.warn( 145 | "`max_length` is deprecated in this function, use" 146 | " `stopping_criteria=StoppingCriteriaList(MaxLengthCriteria(max_length=max_length))` instead.", 147 | UserWarning, 148 | ) 149 | stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length) 150 | logits_warper = logits_warper if logits_warper is not None else LogitsProcessorList() 151 | pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id 152 | eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id 153 | if isinstance(eos_token_id, int): 154 | eos_token_id = [eos_token_id] 155 | output_scores = output_scores if output_scores is not None else self.generation_config.output_scores 156 | output_attentions = ( 157 | output_attentions if output_attentions is not None else self.generation_config.output_attentions 158 | ) 159 | output_hidden_states = ( 160 | output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states 161 | ) 162 | return_dict_in_generate = ( 163 | return_dict_in_generate 164 | if return_dict_in_generate is not None 165 | else self.generation_config.return_dict_in_generate 166 | ) 167 | 168 | # init attention / hidden states / scores tuples 169 | scores = () if (return_dict_in_generate and output_scores) else None 170 | decoder_attentions = () if (return_dict_in_generate and output_attentions) else None 171 | cross_attentions = () if (return_dict_in_generate and output_attentions) else None 172 | decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None 173 | 174 | # if model is an encoder-decoder, retrieve encoder attention weights and hidden states 175 | if return_dict_in_generate and self.config.is_encoder_decoder: 176 | encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None 177 | encoder_hidden_states = ( 178 | model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None 179 | ) 180 | 181 | # keep track of which sequences are already finished 182 | unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1) 183 | 184 | this_peer_finished = False # used by synced_gpus only 185 | # auto-regressive generation 186 | while True: 187 | if synced_gpus: 188 | # Under synced_gpus the `forward` call must continue until all gpus complete their sequence. 189 | # The following logic allows an early break if all peers finished generating their sequence 190 | this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device) 191 | # send 0.0 if we finished, 1.0 otherwise 192 | dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM) 193 | # did all peers finish? the reduced sum will be 0.0 then 194 | if this_peer_finished_flag.item() == 0.0: 195 | break 196 | 197 | # prepare model inputs 198 | model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs) 199 | 200 | # forward pass to get next token 201 | outputs = self( 202 | **model_inputs, 203 | return_dict=True, 204 | output_attentions=output_attentions, 205 | output_hidden_states=output_hidden_states, 206 | ) 207 | 208 | if synced_gpus and this_peer_finished: 209 | continue # don't waste resources running the code we don't need 210 | 211 | next_token_logits = outputs.logits[:, -1, :] 212 | 213 | # pre-process distribution 214 | next_token_scores = logits_processor(input_ids, next_token_logits) 215 | next_token_scores = logits_warper(input_ids, next_token_scores) 216 | 217 | # Store scores, attentions and hidden_states when required 218 | if return_dict_in_generate: 219 | if output_scores: 220 | scores += (next_token_scores,) 221 | if output_attentions: 222 | decoder_attentions += ( 223 | (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,) 224 | ) 225 | if self.config.is_encoder_decoder: 226 | cross_attentions += (outputs.cross_attentions,) 227 | 228 | if output_hidden_states: 229 | decoder_hidden_states += ( 230 | (outputs.decoder_hidden_states,) 231 | if self.config.is_encoder_decoder 232 | else (outputs.hidden_states,) 233 | ) 234 | 235 | # sample 236 | probs = nn.functional.softmax(next_token_scores, dim=-1) 237 | next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1) 238 | 239 | # finished sentences should have their next token be a padding token 240 | if eos_token_id is not None: 241 | if pad_token_id is None: 242 | raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.") 243 | next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences) 244 | 245 | # update generated ids, model inputs, and length for next step 246 | input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1) 247 | model_kwargs = self._update_model_kwargs_for_generation( 248 | outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder 249 | ) 250 | 251 | # if eos_token was found in one sentence, set sentence to finished 252 | if eos_token_id is not None: 253 | unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long()) 254 | 255 | # stop when each sentence is finished, or if we exceed the maximum length 256 | if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores): 257 | if not synced_gpus: 258 | break 259 | else: 260 | this_peer_finished = True 261 | else: 262 | yield next_tokens 263 | 264 | if return_dict_in_generate: 265 | if self.config.is_encoder_decoder: 266 | yield SampleEncoderDecoderOutput( 267 | sequences=input_ids, 268 | scores=scores, 269 | encoder_attentions=encoder_attentions, 270 | encoder_hidden_states=encoder_hidden_states, 271 | decoder_attentions=decoder_attentions, 272 | cross_attentions=cross_attentions, 273 | decoder_hidden_states=decoder_hidden_states, 274 | ) 275 | else: 276 | yield SampleDecoderOnlyOutput( 277 | sequences=input_ids, 278 | scores=scores, 279 | attentions=decoder_attentions, 280 | hidden_states=decoder_hidden_states, 281 | ) 282 | else: 283 | yield next_tokens --------------------------------------------------------------------------------