1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
| import json from shutil import copyfile
from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel
from settings import *
def gen_prompt(instruction, input=None, template=PROMPT_TEMPLATE): """Generate prompt before feeding inputs into LLM""" if input: instruction = instruction + '\n' + input return template.format_map({'instruction': instruction})
class ModelInterface: def __init__(self): self.args = None self.generation_config = None self.model_path = None self.model = None self.tokenizer = None self.device = None self.setup()
def setup(self): self.args = parse_args() self.device = apply_settings(args=self.args) self.model_path = model_path[self.args.model_name] self.generation_config = GenerationConfig( temperature=self.args.temperature, repetition_penalty=self.args.repetition_penalty, do_sample=self.args.do_sample, num_beams=self.args.num_beams, top_p=self.args.top_p, top_k=self.args.top_k, max_new_tokens=self.args.max_new_tokens, ) self.load_model() def load_model(self): tokenizer = AutoTokenizer.from_pretrained(self.model_path) base_model = AutoModelForCausalLM.from_pretrained( self.model_path, device_map='auto', load_in_4bit=True ) model_vocab_size = base_model.get_input_embeddings().weight.size(0) tokenzier_vocab_size = len(tokenizer) print(f">>> Model name: {self.args.model_name}") print(f">>> Vocab of the base model: {model_vocab_size}") print(f">>> Vocab of the tokenizer: {tokenzier_vocab_size}") if model_vocab_size!=tokenzier_vocab_size: assert tokenzier_vocab_size > model_vocab_size print(">>> Resize model embeddings to fit tokenizer") base_model.resize_token_embeddings(tokenzier_vocab_size) if self.args.lora_model is not None: print(">>> Loading peft model") load_type = torch.float16 model = PeftModel.from_pretrained( base_model, self.args.lora_model, torch_dtype=load_type, device_map='auto',) else: model = base_model if self.device==torch.device('cpu'): model.float() model.eval() print(">>> Finish loading model and tokenizer") self.model, self.tokenizer = model, tokenizer def run_iter(self): """Run LLM iteratively""" print(">>> Running LLM iteratively") with torch.no_grad(): while True: raw_input_text = input(">>> Input: ") if len(raw_input_text.strip())==0: break if self.args.with_prompt: input_text = gen_prompt(instruction=raw_input_text) else: input_text = raw_input_text model_inputs = self.tokenizer(input_text, return_tensors="pt") generated_ids = self.model.generate( input_ids = model_inputs["input_ids"].to(self.device), attention_mask = model_inputs['attention_mask'].to(self.device), eos_token_id=self.tokenizer.eos_token_id, pad_token_id=self.tokenizer.pad_token_id, generation_config=self.generation_config )[0] output = self.tokenizer.decode(generated_ids, skip_special_tokens=True) if self.args.with_prompt: response = output.split("### Response:")[1].strip() else: response = output print(">>> Response: ", response, "\n") def run_batch(self, data, file_out): print(">>> Feeding data to LLM in a batch") results = [] with torch.no_grad(): for index, example in enumerate(data): if self.args.with_prompt is True: input_text = gen_prompt(instruction=example) else: input_text = example inputs = self.tokenizer(input_text,return_tensors="pt") generated_ids = self.model.generate( input_ids = inputs["input_ids"].to(self.device), attention_mask = inputs['attention_mask'].to(self.device), eos_token_id=2, pad_token_id=2, generation_config=self.generation_config )[0] output = self.tokenizer.decode(generated_ids,skip_special_tokens=True) if self.args.with_prompt: response = output.split("### Response:")[1].strip() else: response = output print(f"======={index}=======") print(f"Input: \n{example}\n") print(f"Output: \n{response}\n") results.append({"Input":input_text, "Output":response}) if file_out: if os.path.exists(file_out): copyfile(file_out, file_out+".bak") with open(file_out, 'w') as f: json.dump(results, f, ensure_ascii=False, indent=2) else: return results if __name__ == '__main__': mi = ModelInterface() mi.setup() data = [ "Please tell me a joke.", "Please ...", ] file_out = "test.json" mi.run_batch(data, file_out)
|