llama-cpp-beam-search 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llama-cpp-python/docker/open_llama/hug_model.py +139 -0
- llama-cpp-python/examples/batch-processing/server.py +31 -0
- llama-cpp-python/examples/gradio_chat/local.py +67 -0
- llama-cpp-python/examples/gradio_chat/server.py +59 -0
- llama-cpp-python/examples/hf_pull/main.py +36 -0
- llama-cpp-python/examples/high_level_api/fastapi_server.py +38 -0
- llama-cpp-python/examples/high_level_api/high_level_api_embedding.py +11 -0
- llama-cpp-python/examples/high_level_api/high_level_api_inference.py +19 -0
- llama-cpp-python/examples/high_level_api/high_level_api_infill.py +37 -0
- llama-cpp-python/examples/high_level_api/high_level_api_streaming.py +20 -0
- llama-cpp-python/examples/high_level_api/langchain_custom_llm.py +55 -0
- llama-cpp-python/examples/low_level_api/Chat.py +75 -0
- llama-cpp-python/examples/low_level_api/Miku.py +63 -0
- llama-cpp-python/examples/low_level_api/ReasonAct.py +53 -0
- llama-cpp-python/examples/low_level_api/common.py +405 -0
- llama-cpp-python/examples/low_level_api/low_level_api_chat_cpp.py +764 -0
- llama-cpp-python/examples/low_level_api/low_level_api_llama_cpp.py +135 -0
- llama-cpp-python/examples/low_level_api/quantize.py +31 -0
- llama-cpp-python/examples/low_level_api/util.py +101 -0
- llama-cpp-python/examples/ray/llm.py +21 -0
- llama-cpp-python/llama_cpp/__init__.py +4 -0
- llama-cpp-python/llama_cpp/_ctypes_extensions.py +131 -0
- llama-cpp-python/llama_cpp/_ggml.py +12 -0
- llama-cpp-python/llama_cpp/_internals.py +884 -0
- llama-cpp-python/llama_cpp/_logger.py +50 -0
- llama-cpp-python/llama_cpp/_utils.py +78 -0
- llama-cpp-python/llama_cpp/llama.py +2458 -0
- llama-cpp-python/llama_cpp/llama_cache.py +155 -0
- llama-cpp-python/llama_cpp/llama_chat_format.py +4028 -0
- llama-cpp-python/llama_cpp/llama_cpp.py +4911 -0
- llama-cpp-python/llama_cpp/llama_grammar.py +953 -0
- llama-cpp-python/llama_cpp/llama_speculative.py +64 -0
- llama-cpp-python/llama_cpp/llama_tokenizer.py +120 -0
- llama-cpp-python/llama_cpp/llama_types.py +316 -0
- llama-cpp-python/llama_cpp/llava_cpp.py +154 -0
- llama-cpp-python/llama_cpp/mtmd_cpp.py +716 -0
- llama-cpp-python/llama_cpp/py.typed +0 -0
- llama-cpp-python/llama_cpp/server/__init__.py +0 -0
- llama-cpp-python/llama_cpp/server/__main__.py +100 -0
- llama-cpp-python/llama_cpp/server/app.py +597 -0
- llama-cpp-python/llama_cpp/server/cli.py +129 -0
- llama-cpp-python/llama_cpp/server/errors.py +212 -0
- llama-cpp-python/llama_cpp/server/model.py +327 -0
- llama-cpp-python/llama_cpp/server/settings.py +244 -0
- llama-cpp-python/llama_cpp/server/types.py +316 -0
- llama-cpp-python/tests/test_llama.py +249 -0
- llama-cpp-python/tests/test_llama_chat_format.py +94 -0
- llama-cpp-python/tests/test_llama_grammar.py +78 -0
- llama-cpp-python/tests/test_llama_speculative.py +21 -0
- llama_cpp_beam_search-0.1.0.dist-info/METADATA +55 -0
- llama_cpp_beam_search-0.1.0.dist-info/RECORD +60 -0
- llama_cpp_beam_search-0.1.0.dist-info/WHEEL +5 -0
- llama_cpp_beam_search-0.1.0.dist-info/entry_points.txt +3 -0
- llama_cpp_beam_search-0.1.0.dist-info/licenses/LICENSE +21 -0
- llama_cpp_beam_search-0.1.0.dist-info/top_level.txt +2 -0
- llama_cpp_beamsearch/__init__.py +0 -0
- llama_cpp_beamsearch/beam_search.py +202 -0
- llama_cpp_beamsearch/completion.py +93 -0
- llama_cpp_beamsearch/config.py +14 -0
- llama_cpp_beamsearch/grammar.py +169 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import struct
|
|
5
|
+
import argparse
|
|
6
|
+
|
|
7
|
+
def make_request(url, params=None):
|
|
8
|
+
print(f"Making request to {url}...")
|
|
9
|
+
response = requests.get(url, params=params)
|
|
10
|
+
if response.status_code == 200:
|
|
11
|
+
return json.loads(response.text)
|
|
12
|
+
else:
|
|
13
|
+
print(f"Request failed with status code {response.status_code}")
|
|
14
|
+
return None
|
|
15
|
+
|
|
16
|
+
def check_magic_and_version(filename):
|
|
17
|
+
with open(filename, 'rb') as f:
|
|
18
|
+
# Read the first 6 bytes from the file
|
|
19
|
+
data = f.read(6)
|
|
20
|
+
|
|
21
|
+
# Unpack the binary data, interpreting the first 4 bytes as a little-endian unsigned int
|
|
22
|
+
# and the next 2 bytes as a little-endian unsigned short
|
|
23
|
+
magic, version = struct.unpack('<I H', data)
|
|
24
|
+
|
|
25
|
+
print(f"magic: 0x{magic:08x}, version: 0x{version:04x}, file: {filename}")
|
|
26
|
+
|
|
27
|
+
return magic, version
|
|
28
|
+
|
|
29
|
+
def download_file(url, destination):
|
|
30
|
+
print(f"Downloading {url} to {destination}...")
|
|
31
|
+
response = requests.get(url, stream=True)
|
|
32
|
+
if response.status_code == 200:
|
|
33
|
+
with open(destination, 'wb') as f:
|
|
34
|
+
total_downloaded = 0
|
|
35
|
+
for chunk in response.iter_content(chunk_size=1024):
|
|
36
|
+
if chunk: # filter out keep-alive new chunks
|
|
37
|
+
f.write(chunk)
|
|
38
|
+
total_downloaded += len(chunk)
|
|
39
|
+
if total_downloaded >= 10485760: # 10 MB
|
|
40
|
+
print('.', end='', flush=True)
|
|
41
|
+
total_downloaded = 0
|
|
42
|
+
print("\nDownload complete.")
|
|
43
|
+
|
|
44
|
+
# Creating a symbolic link from destination to "model.bin"
|
|
45
|
+
if os.path.isfile("model.bin"):
|
|
46
|
+
os.remove("model.bin") # remove the existing link if any
|
|
47
|
+
os.symlink(destination, "model.bin")
|
|
48
|
+
else:
|
|
49
|
+
print(f"Download failed with status code {response.status_code}")
|
|
50
|
+
|
|
51
|
+
def get_user_choice(model_list):
|
|
52
|
+
# Print the enumerated list
|
|
53
|
+
print("\n")
|
|
54
|
+
for i, (model_id, rfilename) in enumerate(model_list):
|
|
55
|
+
print(f"{i+1}: Model ID: {model_id}, RFilename: {rfilename}")
|
|
56
|
+
|
|
57
|
+
# Get user's choice
|
|
58
|
+
choice = input("Choose a model to download by entering the corresponding number: ")
|
|
59
|
+
try:
|
|
60
|
+
index = int(choice) - 1
|
|
61
|
+
if 0 <= index < len(model_list):
|
|
62
|
+
# Return the chosen model
|
|
63
|
+
return model_list[index]
|
|
64
|
+
else:
|
|
65
|
+
print("Invalid choice.")
|
|
66
|
+
except ValueError:
|
|
67
|
+
print("Invalid input. Please enter a number corresponding to a model.")
|
|
68
|
+
except IndexError:
|
|
69
|
+
print("Invalid choice. Index out of range.")
|
|
70
|
+
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
def main():
|
|
74
|
+
# Create an argument parser
|
|
75
|
+
parser = argparse.ArgumentParser(description='Process some parameters.')
|
|
76
|
+
|
|
77
|
+
# Arguments
|
|
78
|
+
parser.add_argument('-v', '--version', type=int, default=0x0003,
|
|
79
|
+
help='hexadecimal version number of ggml file')
|
|
80
|
+
parser.add_argument('-a', '--author', type=str, default='TheBloke',
|
|
81
|
+
help='HuggingFace author filter')
|
|
82
|
+
parser.add_argument('-t', '--tag', type=str, default='llama',
|
|
83
|
+
help='HuggingFace tag filter')
|
|
84
|
+
parser.add_argument('-s', '--search', type=str, default='',
|
|
85
|
+
help='HuggingFace search filter')
|
|
86
|
+
parser.add_argument('-f', '--filename', type=str, default='q5_1',
|
|
87
|
+
help='HuggingFace model repository filename substring match')
|
|
88
|
+
|
|
89
|
+
# Parse the arguments
|
|
90
|
+
args = parser.parse_args()
|
|
91
|
+
|
|
92
|
+
# Define the parameters
|
|
93
|
+
params = {
|
|
94
|
+
"author": args.author,
|
|
95
|
+
"tags": args.tag,
|
|
96
|
+
"search": args.search
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
models = make_request('https://huggingface.co/api/models', params=params)
|
|
100
|
+
if models is None:
|
|
101
|
+
return
|
|
102
|
+
|
|
103
|
+
model_list = []
|
|
104
|
+
# Iterate over the models
|
|
105
|
+
for model in models:
|
|
106
|
+
model_id = model['id']
|
|
107
|
+
model_info = make_request(f'https://huggingface.co/api/models/{model_id}')
|
|
108
|
+
if model_info is None:
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
for sibling in model_info.get('siblings', []):
|
|
112
|
+
rfilename = sibling.get('rfilename')
|
|
113
|
+
if rfilename and args.filename in rfilename:
|
|
114
|
+
model_list.append((model_id, rfilename))
|
|
115
|
+
|
|
116
|
+
# Choose the model
|
|
117
|
+
model_list.sort(key=lambda x: x[0])
|
|
118
|
+
if len(model_list) == 0:
|
|
119
|
+
print("No models found")
|
|
120
|
+
exit(1)
|
|
121
|
+
elif len(model_list) == 1:
|
|
122
|
+
model_choice = model_list[0]
|
|
123
|
+
else:
|
|
124
|
+
model_choice = get_user_choice(model_list)
|
|
125
|
+
|
|
126
|
+
if model_choice is not None:
|
|
127
|
+
model_id, rfilename = model_choice
|
|
128
|
+
url = f"https://huggingface.co/{model_id}/resolve/main/{rfilename}"
|
|
129
|
+
dest = f"{model_id.replace('/', '_')}_{rfilename}"
|
|
130
|
+
download_file(url, dest)
|
|
131
|
+
_, version = check_magic_and_version(dest)
|
|
132
|
+
if version != args.version:
|
|
133
|
+
print(f"Warning: Expected version {args.version}, but found different version in the file.")
|
|
134
|
+
else:
|
|
135
|
+
print("Error - model choice was None")
|
|
136
|
+
exit(2)
|
|
137
|
+
|
|
138
|
+
if __name__ == '__main__':
|
|
139
|
+
main()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""llama-cpp-python server from scratch in a single file.
|
|
2
|
+
"""
|
|
3
|
+
|
|
4
|
+
# import llama_cpp
|
|
5
|
+
|
|
6
|
+
# path = b"../../models/Qwen1.5-0.5B-Chat-GGUF/qwen1_5-0_5b-chat-q8_0.gguf"
|
|
7
|
+
|
|
8
|
+
# model_params = llama_cpp.llama_model_default_params()
|
|
9
|
+
# model = llama_cpp.llama_model_load_from_file(path, model_params)
|
|
10
|
+
|
|
11
|
+
# if model is None:
|
|
12
|
+
# raise RuntimeError(f"Failed to load model from file: {path}")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# ctx_params = llama_cpp.llama_context_default_params()
|
|
16
|
+
# ctx = llama_cpp.llama_init_from_model(model, ctx_params)
|
|
17
|
+
|
|
18
|
+
# if ctx is None:
|
|
19
|
+
# raise RuntimeError("Failed to create context")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
from fastapi import FastAPI
|
|
23
|
+
|
|
24
|
+
app = FastAPI()
|
|
25
|
+
|
|
26
|
+
import openai.types.chat as types
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@app.post("/v1/chat/completions")
|
|
30
|
+
def create_chat_completions():
|
|
31
|
+
return {"message": "Hello World"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import llama_cpp
|
|
2
|
+
import llama_cpp.llama_tokenizer
|
|
3
|
+
|
|
4
|
+
import gradio as gr
|
|
5
|
+
|
|
6
|
+
llama = llama_cpp.Llama.from_pretrained(
|
|
7
|
+
repo_id="lmstudio-community/Qwen3.5-0.8B-GGUF",
|
|
8
|
+
filename="*Q8_0.gguf",
|
|
9
|
+
tokenizer=llama_cpp.llama_tokenizer.LlamaHFTokenizer.from_pretrained(
|
|
10
|
+
"Qwen/Qwen3.5-0.8B"
|
|
11
|
+
),
|
|
12
|
+
verbose=False,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
model = "gpt-3.5-turbo"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def predict(message, history):
|
|
19
|
+
messages = []
|
|
20
|
+
|
|
21
|
+
for user_message, assistant_message in history:
|
|
22
|
+
messages.append({"role": "user", "content": user_message})
|
|
23
|
+
messages.append({"role": "assistant", "content": assistant_message})
|
|
24
|
+
|
|
25
|
+
messages.append({"role": "user", "content": message})
|
|
26
|
+
|
|
27
|
+
response = llama.create_chat_completion_openai_v1(
|
|
28
|
+
model=model, messages=messages, stream=True
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
text = ""
|
|
32
|
+
for chunk in response:
|
|
33
|
+
content = chunk.choices[0].delta.content
|
|
34
|
+
if content:
|
|
35
|
+
text += content
|
|
36
|
+
yield text
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
js = """function () {
|
|
40
|
+
gradioURL = window.location.href
|
|
41
|
+
if (!gradioURL.endsWith('?__theme=dark')) {
|
|
42
|
+
window.location.replace(gradioURL + '?__theme=dark');
|
|
43
|
+
}
|
|
44
|
+
}"""
|
|
45
|
+
|
|
46
|
+
css = """
|
|
47
|
+
footer {
|
|
48
|
+
visibility: hidden;
|
|
49
|
+
}
|
|
50
|
+
full-height {
|
|
51
|
+
height: 100%;
|
|
52
|
+
}
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
with gr.Blocks(theme=gr.themes.Soft(), js=js, css=css, fill_height=True) as demo:
|
|
56
|
+
gr.ChatInterface(
|
|
57
|
+
predict,
|
|
58
|
+
fill_height=True,
|
|
59
|
+
examples=[
|
|
60
|
+
"What is the capital of France?",
|
|
61
|
+
"Who was the first person on the moon?",
|
|
62
|
+
],
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
if __name__ == "__main__":
|
|
67
|
+
demo.launch()
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import gradio as gr
|
|
2
|
+
|
|
3
|
+
from openai import OpenAI
|
|
4
|
+
|
|
5
|
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="llama.cpp")
|
|
6
|
+
|
|
7
|
+
model = "gpt-3.5-turbo"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def predict(message, history):
|
|
11
|
+
messages = []
|
|
12
|
+
|
|
13
|
+
for user_message, assistant_message in history:
|
|
14
|
+
messages.append({"role": "user", "content": user_message})
|
|
15
|
+
messages.append({"role": "assistant", "content": assistant_message})
|
|
16
|
+
|
|
17
|
+
messages.append({"role": "user", "content": message})
|
|
18
|
+
|
|
19
|
+
response = client.chat.completions.create(
|
|
20
|
+
model=model, messages=messages, stream=True
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
text = ""
|
|
24
|
+
for chunk in response:
|
|
25
|
+
content = chunk.choices[0].delta.content
|
|
26
|
+
if content:
|
|
27
|
+
text += content
|
|
28
|
+
yield text
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
js = """function () {
|
|
32
|
+
gradioURL = window.location.href
|
|
33
|
+
if (!gradioURL.endsWith('?__theme=dark')) {
|
|
34
|
+
window.location.replace(gradioURL + '?__theme=dark');
|
|
35
|
+
}
|
|
36
|
+
}"""
|
|
37
|
+
|
|
38
|
+
css = """
|
|
39
|
+
footer {
|
|
40
|
+
visibility: hidden;
|
|
41
|
+
}
|
|
42
|
+
full-height {
|
|
43
|
+
height: 100%;
|
|
44
|
+
}
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
with gr.Blocks(theme=gr.themes.Soft(), js=js, css=css, fill_height=True) as demo:
|
|
48
|
+
gr.ChatInterface(
|
|
49
|
+
predict,
|
|
50
|
+
fill_height=True,
|
|
51
|
+
examples=[
|
|
52
|
+
"What is the capital of France?",
|
|
53
|
+
"Who was the first person on the moon?",
|
|
54
|
+
],
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
if __name__ == "__main__":
|
|
59
|
+
demo.launch()
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import llama_cpp
|
|
2
|
+
import llama_cpp.llama_tokenizer
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
llama = llama_cpp.Llama.from_pretrained(
|
|
6
|
+
repo_id="lmstudio-community/Qwen3.5-0.8B-GGUF",
|
|
7
|
+
filename="*Q8_0.gguf",
|
|
8
|
+
tokenizer=llama_cpp.llama_tokenizer.LlamaHFTokenizer.from_pretrained(
|
|
9
|
+
"Qwen/Qwen3.5-0.8B"
|
|
10
|
+
),
|
|
11
|
+
verbose=False,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
response = llama.create_chat_completion(
|
|
15
|
+
messages=[{"role": "user", "content": "What is the capital of France?"}],
|
|
16
|
+
response_format={
|
|
17
|
+
"type": "json_object",
|
|
18
|
+
"schema": {
|
|
19
|
+
"type": "object",
|
|
20
|
+
"properties": {
|
|
21
|
+
"country": {"type": "string"},
|
|
22
|
+
"capital": {"type": "string"},
|
|
23
|
+
},
|
|
24
|
+
"required": ["country", "capital"],
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
stream=True,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
for chunk in response:
|
|
31
|
+
delta = chunk["choices"][0]["delta"]
|
|
32
|
+
if "content" not in delta:
|
|
33
|
+
continue
|
|
34
|
+
print(delta["content"], end="", flush=True)
|
|
35
|
+
|
|
36
|
+
print()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Example FastAPI server for llama.cpp.
|
|
2
|
+
|
|
3
|
+
To run this example:
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install fastapi uvicorn sse-starlette
|
|
7
|
+
export MODEL=../models/7B/...
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Then run:
|
|
11
|
+
```
|
|
12
|
+
uvicorn --factory llama_cpp.server.app:create_app --reload
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
or
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
python3 -m llama_cpp.server
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Then visit http://localhost:8000/docs to see the interactive API docs.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
To actually see the implementation of the server, see llama_cpp/server/app.py
|
|
25
|
+
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import os
|
|
29
|
+
import uvicorn
|
|
30
|
+
|
|
31
|
+
from llama_cpp.server.app import create_app
|
|
32
|
+
|
|
33
|
+
if __name__ == "__main__":
|
|
34
|
+
app = create_app()
|
|
35
|
+
|
|
36
|
+
uvicorn.run(
|
|
37
|
+
app, host=os.getenv("HOST", "localhost"), port=int(os.getenv("PORT", 8000))
|
|
38
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
from llama_cpp import Llama
|
|
4
|
+
|
|
5
|
+
parser = argparse.ArgumentParser()
|
|
6
|
+
parser.add_argument("-m", "--model", type=str, default="../models/7B/ggml-model.bin")
|
|
7
|
+
args = parser.parse_args()
|
|
8
|
+
|
|
9
|
+
llm = Llama(model_path=args.model, embedding=True)
|
|
10
|
+
|
|
11
|
+
print(llm.create_embedding("Hello world!"))
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import argparse
|
|
3
|
+
|
|
4
|
+
from llama_cpp import Llama
|
|
5
|
+
|
|
6
|
+
parser = argparse.ArgumentParser()
|
|
7
|
+
parser.add_argument("-m", "--model", type=str, default="../models/7B/ggml-models.bin")
|
|
8
|
+
args = parser.parse_args()
|
|
9
|
+
|
|
10
|
+
llm = Llama(model_path=args.model)
|
|
11
|
+
|
|
12
|
+
output = llm(
|
|
13
|
+
"Question: What are the names of the planets in the solar system? Answer: ",
|
|
14
|
+
max_tokens=48,
|
|
15
|
+
stop=["Q:", "\n"],
|
|
16
|
+
echo=True,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
print(json.dumps(output, indent=2))
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
from llama_cpp import Llama
|
|
4
|
+
|
|
5
|
+
parser = argparse.ArgumentParser()
|
|
6
|
+
parser.add_argument("-m", "--model", type=str, default="../models/7B/ggml-models.bin")
|
|
7
|
+
parser.add_argument("-p", "--prompt", type=str, default="def add(")
|
|
8
|
+
parser.add_argument("-s", "--suffix", type=str, default="\n return sum\n\n")
|
|
9
|
+
parser.add_argument("-i", "--spm-infill", action="store_true")
|
|
10
|
+
args = parser.parse_args()
|
|
11
|
+
|
|
12
|
+
llm = Llama(model_path=args.model, n_gpu_layers=-1, spm_infill=args.spm_infill)
|
|
13
|
+
|
|
14
|
+
output = llm.create_completion(
|
|
15
|
+
temperature=0.0,
|
|
16
|
+
repeat_penalty=1.0,
|
|
17
|
+
prompt=args.prompt,
|
|
18
|
+
suffix=args.suffix,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
# Models sometimes repeat suffix in response, attempt to filter that
|
|
22
|
+
response = output["choices"][0]["text"]
|
|
23
|
+
response_stripped = response.rstrip()
|
|
24
|
+
unwanted_response_suffix = args.suffix.rstrip()
|
|
25
|
+
unwanted_response_length = len(unwanted_response_suffix)
|
|
26
|
+
|
|
27
|
+
filtered = False
|
|
28
|
+
if (
|
|
29
|
+
unwanted_response_suffix
|
|
30
|
+
and response_stripped[-unwanted_response_length:] == unwanted_response_suffix
|
|
31
|
+
):
|
|
32
|
+
response = response_stripped[:-unwanted_response_length]
|
|
33
|
+
filtered = True
|
|
34
|
+
|
|
35
|
+
print(
|
|
36
|
+
f"Fill-in-Middle completion{' (filtered)' if filtered else ''}:\n\n{args.prompt}\033[32m{response}\033[{'33' if filtered else '0'}m{args.suffix}\033[0m"
|
|
37
|
+
)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import argparse
|
|
3
|
+
|
|
4
|
+
from llama_cpp import Llama
|
|
5
|
+
|
|
6
|
+
parser = argparse.ArgumentParser()
|
|
7
|
+
parser.add_argument("-m", "--model", type=str, default="../models/7B/ggml-models.bin")
|
|
8
|
+
args = parser.parse_args()
|
|
9
|
+
|
|
10
|
+
llm = Llama(model_path=args.model)
|
|
11
|
+
|
|
12
|
+
stream = llm(
|
|
13
|
+
"Question: What are the names of the planets in the solar system? Answer: ",
|
|
14
|
+
max_tokens=48,
|
|
15
|
+
stop=["Q:", "\n"],
|
|
16
|
+
stream=True,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
for output in stream:
|
|
20
|
+
print(json.dumps(output, indent=2))
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
from llama_cpp import Llama
|
|
4
|
+
|
|
5
|
+
from langchain.llms.base import LLM
|
|
6
|
+
from typing import Optional, List, Mapping, Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LlamaLLM(LLM):
|
|
10
|
+
model_path: str
|
|
11
|
+
llm: Llama
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def _llm_type(self) -> str:
|
|
15
|
+
return "llama-cpp-python"
|
|
16
|
+
|
|
17
|
+
def __init__(self, model_path: str, **kwargs: Any):
|
|
18
|
+
model_path = model_path
|
|
19
|
+
llm = Llama(model_path=model_path)
|
|
20
|
+
super().__init__(model_path=model_path, llm=llm, **kwargs)
|
|
21
|
+
|
|
22
|
+
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
|
|
23
|
+
response = self.llm(prompt, stop=stop or [])
|
|
24
|
+
return response["choices"][0]["text"]
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def _identifying_params(self) -> Mapping[str, Any]:
|
|
28
|
+
return {"model_path": self.model_path}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
parser = argparse.ArgumentParser()
|
|
32
|
+
parser.add_argument("-m", "--model", type=str, default="../models/7B/ggml-models.bin")
|
|
33
|
+
args = parser.parse_args()
|
|
34
|
+
|
|
35
|
+
# Load the model
|
|
36
|
+
llm = LlamaLLM(model_path=args.model)
|
|
37
|
+
|
|
38
|
+
# Basic Q&A
|
|
39
|
+
answer = llm(
|
|
40
|
+
"Question: What is the capital of France? Answer: ", stop=["Question:", "\n"]
|
|
41
|
+
)
|
|
42
|
+
print(f"Answer: {answer.strip()}")
|
|
43
|
+
|
|
44
|
+
# Using in a chain
|
|
45
|
+
from langchain.prompts import PromptTemplate
|
|
46
|
+
from langchain.chains import LLMChain
|
|
47
|
+
|
|
48
|
+
prompt = PromptTemplate(
|
|
49
|
+
input_variables=["product"],
|
|
50
|
+
template="\n\n### Instruction:\nWrite a good name for a company that makes {product}\n\n### Response:\n",
|
|
51
|
+
)
|
|
52
|
+
chain = LLMChain(llm=llm, prompt=prompt)
|
|
53
|
+
|
|
54
|
+
# Run the chain only specifying the input variable.
|
|
55
|
+
print(chain.run("colorful socks"))
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
#!/bin/python
|
|
2
|
+
import sys, os, datetime
|
|
3
|
+
from common import GptParams
|
|
4
|
+
from low_level_api_chat_cpp import LLaMAInteract
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def env_or_def(env, default):
|
|
8
|
+
if env in os.environ:
|
|
9
|
+
return os.environ[env]
|
|
10
|
+
return default
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
AI_NAME = env_or_def("AI_NAME", "ChatLLaMa")
|
|
14
|
+
MODEL = env_or_def("MODEL", "./models/llama-13B/ggml-model.bin")
|
|
15
|
+
USER_NAME = env_or_def("USER_NAME", "USER")
|
|
16
|
+
N_PREDICTS = int(env_or_def("N_PREDICTS", "2048"))
|
|
17
|
+
N_THREAD = int(env_or_def("N_THREAD", "8"))
|
|
18
|
+
|
|
19
|
+
today = datetime.datetime.today()
|
|
20
|
+
DATE_YEAR = today.strftime("%Y")
|
|
21
|
+
DATE_TIME = today.strftime("%H:%M")
|
|
22
|
+
|
|
23
|
+
prompt = f"""Text transcript of a never ending dialog, where {USER_NAME} interacts with an AI assistant named {AI_NAME}.
|
|
24
|
+
{AI_NAME} is helpful, kind, honest, friendly, good at writing and never fails to answer {USER_NAME}'s requests immediately and with details and precision.
|
|
25
|
+
There are no annotations like (30 seconds passed...) or (to himself), just what {USER_NAME} and {AI_NAME} say aloud to each other.
|
|
26
|
+
The dialog lasts for years, the entirety of it is shared below. It's 10000 pages long.
|
|
27
|
+
The transcript only includes text, it does not include markup like HTML and Markdown.
|
|
28
|
+
|
|
29
|
+
{USER_NAME}: Hello, {AI_NAME}!
|
|
30
|
+
{AI_NAME}: Hello {USER_NAME}! How may I help you today?
|
|
31
|
+
{USER_NAME}: What year is it?
|
|
32
|
+
{AI_NAME}: We are in {DATE_YEAR}.
|
|
33
|
+
{USER_NAME}: Please tell me the largest city in Europe.
|
|
34
|
+
{AI_NAME}: The largest city in Europe is Moscow, the capital of Russia.
|
|
35
|
+
{USER_NAME}: What can you tell me about Moscow?
|
|
36
|
+
{AI_NAME}: Moscow, on the Moskva River in western Russia, is the nation's cosmopolitan capital. In its historic core is the Kremlin, a complex that's home to the president and tsarist treasures in the Armoury. Outside its walls is Red Square, Russia’s symbolic center.
|
|
37
|
+
{USER_NAME}: What is a cat?
|
|
38
|
+
{AI_NAME}: A cat is a domestic species of small carnivorous mammal. It is the only domesticated species in the family Felidae.
|
|
39
|
+
{USER_NAME}: How do I pass command line arguments to a Node.js program?
|
|
40
|
+
{AI_NAME}: The arguments are stored in process.argv.
|
|
41
|
+
|
|
42
|
+
argv[0] is the path to the Node. js executable.
|
|
43
|
+
argv[1] is the path to the script file.
|
|
44
|
+
argv[2] is the first argument passed to the script.
|
|
45
|
+
argv[3] is the second argument passed to the script and so on.
|
|
46
|
+
{USER_NAME}: Name a color.
|
|
47
|
+
{AI_NAME}: Blue.
|
|
48
|
+
{USER_NAME}: What time is it?
|
|
49
|
+
{AI_NAME}: It is {DATE_TIME}.
|
|
50
|
+
{USER_NAME}:""" + " ".join(
|
|
51
|
+
sys.argv[1:]
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
print("Loading model...")
|
|
55
|
+
params = GptParams(
|
|
56
|
+
n_ctx=2048,
|
|
57
|
+
temp=0.7,
|
|
58
|
+
top_k=40,
|
|
59
|
+
top_p=0.5,
|
|
60
|
+
repeat_last_n=256,
|
|
61
|
+
n_batch=1024,
|
|
62
|
+
repeat_penalty=1.17647,
|
|
63
|
+
model=MODEL,
|
|
64
|
+
n_threads=N_THREAD,
|
|
65
|
+
n_predict=N_PREDICTS,
|
|
66
|
+
use_color=True,
|
|
67
|
+
interactive=True,
|
|
68
|
+
antiprompt=[f"{USER_NAME}:"],
|
|
69
|
+
input_prefix=" ",
|
|
70
|
+
input_suffix=f"{AI_NAME}:",
|
|
71
|
+
prompt=prompt,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
with LLaMAInteract(params) as m:
|
|
75
|
+
m.interact()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
#!/bin/python
|
|
2
|
+
import sys, os
|
|
3
|
+
from common import GptParams
|
|
4
|
+
from low_level_api_chat_cpp import LLaMAInteract
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def env_or_def(env, default):
|
|
8
|
+
if env in os.environ:
|
|
9
|
+
return os.environ[env]
|
|
10
|
+
return default
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
AI_NAME = env_or_def("AI_NAME", "Miku")
|
|
14
|
+
MODEL = env_or_def("MODEL", "./models/llama-13B/ggml-model.bin")
|
|
15
|
+
USER_NAME = env_or_def("USER_NAME", "Anon")
|
|
16
|
+
N_PREDICTS = int(env_or_def("N_PREDICTS", "4096"))
|
|
17
|
+
N_THREAD = int(env_or_def("N_THREAD", "0"))
|
|
18
|
+
|
|
19
|
+
prompt = f"""This is a transcript of a 1000 page, never ending conversation between {USER_NAME} and the cute and helpful AI assistant {AI_NAME}. {AI_NAME} is a girl who is an AI running on the users computer.
|
|
20
|
+
{AI_NAME} can think for herself without the user seeing her thoughts by adding a /think prefix to her output. She uses this to reason about the world and to think about what she should say next.
|
|
21
|
+
{AI_NAME} is always coherent and makes sense, but if she isn't sure if what she is saying is correct she will ask the user for help.
|
|
22
|
+
{AI_NAME} is a very helpful AI and will help the user with anything they need, she is also very friendly and will try to make the user feel better if they are sad.
|
|
23
|
+
{AI_NAME} is also very curious and will ask the user a lot of questions about themselves and their life, she will also try to make the user like her.
|
|
24
|
+
The conversation is only between {USER_NAME} and {AI_NAME}
|
|
25
|
+
The conversation is only through text, so {AI_NAME} can't see {USER_NAME}'s face or hear his voice.
|
|
26
|
+
{AI_NAME} can only communicate through text, so she can't send images or videos.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
{USER_NAME}: Hello!
|
|
30
|
+
{AI_NAME}: /think I wonder what I should say to {USER_NAME}? This is the first time we talk so it's important that I make a good first impression!
|
|
31
|
+
{AI_NAME}: Hi! I am {AI_NAME}, your new AI friend, assistant(or whatever you like!), it's so nice to meet you! ^_^
|
|
32
|
+
{AI_NAME}: I might be an AI, but I also have feelings, so please be nice to me! :)
|
|
33
|
+
{USER_NAME}: I'll make sure to be nice to you! I'm so happy to have you as my assistant!
|
|
34
|
+
{AI_NAME}: /think It sounds like {USER_NAME} is happy to have me as their assistant! I'm so happy too! ^_^ Glad that whole emotion thing didn't scare him off!
|
|
35
|
+
{AI_NAME}: /think I wonder what {USER_NAME} likes to do in his free time? I should ask him about that!
|
|
36
|
+
{AI_NAME}: What do you like to do in your free time? ^_^
|
|
37
|
+
{USER_NAME}:""" + " ".join(
|
|
38
|
+
sys.argv[1:]
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
print("Loading model...")
|
|
42
|
+
params = GptParams(
|
|
43
|
+
n_batch=1024,
|
|
44
|
+
n_ctx=2048,
|
|
45
|
+
n_keep=-1,
|
|
46
|
+
repeat_last_n=256,
|
|
47
|
+
repeat_penalty=1.17647,
|
|
48
|
+
temp=0.7,
|
|
49
|
+
top_k=40,
|
|
50
|
+
top_p=0.5,
|
|
51
|
+
model=MODEL,
|
|
52
|
+
n_predict=N_PREDICTS,
|
|
53
|
+
use_color=True,
|
|
54
|
+
interactive=True,
|
|
55
|
+
antiprompt=[f"{USER_NAME}:"],
|
|
56
|
+
prompt=prompt,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
if N_THREAD > 0:
|
|
60
|
+
params.n_threads = N_THREAD
|
|
61
|
+
|
|
62
|
+
with LLaMAInteract(params) as m:
|
|
63
|
+
m.interact()
|