|
| 1 | +import argparse |
| 2 | +import os |
| 3 | +import subprocess |
| 4 | +from typing import Optional |
| 5 | + |
| 6 | +from turnkeyml.state import State |
| 7 | +from turnkeyml.tools import FirstTool |
| 8 | + |
| 9 | +import turnkeyml.common.build as build |
| 10 | +from .adapter import PassthroughTokenizer, ModelAdapter |
| 11 | + |
| 12 | + |
| 13 | +def llamacpp_dir(state: State): |
| 14 | + return os.path.join(build.output_dir(state.cache_dir, state.build_name), "llamacpp") |
| 15 | + |
| 16 | +class LlamaCppAdapter(ModelAdapter): |
| 17 | + unique_name = "llama-cpp-adapter" |
| 18 | + |
| 19 | + def __init__(self, executable, model, tool_dir, context_size, threads, temp): |
| 20 | + super().__init__() |
| 21 | + |
| 22 | + self.executable = executable |
| 23 | + self.model = model |
| 24 | + self.tool_dir = tool_dir |
| 25 | + self.context_size = context_size |
| 26 | + self.threads = threads |
| 27 | + self.temp = temp |
| 28 | + |
| 29 | + def generate(self, input_ids: str, max_new_tokens: Optional[int] = None): |
| 30 | + """ |
| 31 | + Pass a text prompt into the llamacpp inference CLI. |
| 32 | +
|
| 33 | + The input_ids arg here should receive the original text that |
| 34 | + would normally be encoded by a tokenizer. |
| 35 | + """ |
| 36 | + |
| 37 | + cmd = [ |
| 38 | + self.executable, |
| 39 | + "-e", |
| 40 | + ] |
| 41 | + |
| 42 | + optional_params = { |
| 43 | + "ctx-size": self.context_size, |
| 44 | + "n-predict": max_new_tokens, |
| 45 | + "threads": self.threads, |
| 46 | + "model": self.model, |
| 47 | + "prompt": input_ids, |
| 48 | + "temp": self.temp |
| 49 | + } |
| 50 | + |
| 51 | + for flag, value in optional_params.items(): |
| 52 | + if value is not None: |
| 53 | + cmd.append(f"--{flag} {value}") |
| 54 | + |
| 55 | + cmd = [str(m) for m in cmd] |
| 56 | + |
| 57 | + process = subprocess.Popen( |
| 58 | + cmd, |
| 59 | + stdout=subprocess.PIPE, |
| 60 | + stderr=subprocess.PIPE, |
| 61 | + universal_newlines=True, |
| 62 | + ) |
| 63 | + |
| 64 | + raw_output, raw_err= process.communicate() |
| 65 | + |
| 66 | + if process.returncode != 0: |
| 67 | + raise subprocess.CalledProcessError( |
| 68 | + process.returncode, process.args, raw_output, raw_err) |
| 69 | + |
| 70 | + prompt_found = False |
| 71 | + output_text = "" |
| 72 | + prompt_first_line = input_ids.split("\n")[0] |
| 73 | + for line in raw_output.splitlines(): |
| 74 | + if prompt_first_line in line: |
| 75 | + prompt_found = True |
| 76 | + if prompt_found: |
| 77 | + line = line.replace("</s> [end of text]", "") |
| 78 | + output_text = output_text + line |
| 79 | + |
| 80 | + if not prompt_found: |
| 81 | + raise Exception("Prompt not found in result, this is a bug in lemonade.") |
| 82 | + |
| 83 | + return [output_text] |
| 84 | + |
| 85 | +class LoadLlamaCpp(FirstTool): |
| 86 | + unique_name = "load-llama-cpp" |
| 87 | + |
| 88 | + def __init__(self): |
| 89 | + super().__init__(monitor_message="Running llama.cpp model") |
| 90 | + |
| 91 | + @staticmethod |
| 92 | + def parser(add_help: bool = True) -> argparse.ArgumentParser: |
| 93 | + parser = __class__.helpful_parser( |
| 94 | + short_description="Wrap Llamacpp models with an API", |
| 95 | + add_help=add_help, |
| 96 | + ) |
| 97 | + |
| 98 | + parser.add_argument( |
| 99 | + "--executable", |
| 100 | + required=True, |
| 101 | + type=str, |
| 102 | + help="Executable name", |
| 103 | + ) |
| 104 | + |
| 105 | + default_threads = 1 |
| 106 | + parser.add_argument( |
| 107 | + "--threads", |
| 108 | + required=False, |
| 109 | + type=int, |
| 110 | + default=default_threads, |
| 111 | + help=f"Number of threads to use for generation (default: {default_threads})", |
| 112 | + ) |
| 113 | + |
| 114 | + context_size = 512 |
| 115 | + parser.add_argument( |
| 116 | + "--context-size", |
| 117 | + required=False, |
| 118 | + type=int, |
| 119 | + default=context_size, |
| 120 | + help=f"Context size of the prompt (default: {context_size})", |
| 121 | + ) |
| 122 | + |
| 123 | + parser.add_argument( |
| 124 | + "--model-binary", |
| 125 | + required=False, |
| 126 | + help="Path to a .gguf model to use with benchmarking.", |
| 127 | + ) |
| 128 | + |
| 129 | + parser.add_argument( |
| 130 | + "--temp", |
| 131 | + type=float, |
| 132 | + required=False, |
| 133 | + help="Temperature", |
| 134 | + ) |
| 135 | + |
| 136 | + return parser |
| 137 | + |
| 138 | + def run( |
| 139 | + self, |
| 140 | + state: State, |
| 141 | + input: str = None, |
| 142 | + context_size: int = None, |
| 143 | + threads: int = None, |
| 144 | + executable: str = None, |
| 145 | + model_binary: str = None, |
| 146 | + temp: float = None, |
| 147 | + ) -> State: |
| 148 | + """ |
| 149 | + Create a tokenizer instance and model instance in `state` that support: |
| 150 | +
|
| 151 | + input_ids = tokenizer(prompt, return_tensors="pt").input_ids |
| 152 | + response = model.generate(input_ids, max_new_tokens=1) |
| 153 | + response_text = tokenizer.decode(response[0], skip_special_tokens=True).strip() |
| 154 | + """ |
| 155 | + |
| 156 | + if executable is None: |
| 157 | + raise Exception(f"{self.__class__.unique_name} requires an executable") |
| 158 | + |
| 159 | + if (input is not None and input != ""): |
| 160 | + model_binary = input |
| 161 | + |
| 162 | + # Save execution parameters |
| 163 | + state.save_stat("context_size", context_size) |
| 164 | + state.save_stat("threads", threads) |
| 165 | + |
| 166 | + if model_binary is None: |
| 167 | + raise Exception( |
| 168 | + f"{self.__class__.unique_name} requires the preceding tool to pass a " |
| 169 | + "Llamacpp model, " |
| 170 | + "or for the user to supply a model with `--model-binary`" |
| 171 | + ) |
| 172 | + |
| 173 | + state.model = LlamaCppAdapter( |
| 174 | + executable = executable, |
| 175 | + model=model_binary, |
| 176 | + tool_dir=llamacpp_dir(state), |
| 177 | + context_size=context_size, |
| 178 | + threads=threads, |
| 179 | + temp=temp, |
| 180 | + ) |
| 181 | + state.tokenizer = PassthroughTokenizer() |
| 182 | + |
| 183 | + return state |
0 commit comments