llama-cpp-beam-search 0.1.0__tar.gz
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_beam_search-0.1.0/LICENSE +21 -0
- llama_cpp_beam_search-0.1.0/PKG-INFO +55 -0
- llama_cpp_beam_search-0.1.0/README.md +40 -0
- llama_cpp_beam_search-0.1.0/pyproject.toml +28 -0
- llama_cpp_beam_search-0.1.0/setup.cfg +4 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/docker/open_llama/hug_model.py +139 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/batch-processing/server.py +31 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/gradio_chat/local.py +67 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/gradio_chat/server.py +59 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/hf_pull/main.py +36 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/fastapi_server.py +38 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_embedding.py +11 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_inference.py +19 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_infill.py +37 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_streaming.py +20 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/langchain_custom_llm.py +55 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/Chat.py +75 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/Miku.py +63 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/ReasonAct.py +53 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/common.py +405 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/low_level_api_chat_cpp.py +764 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/low_level_api_llama_cpp.py +135 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/quantize.py +31 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/low_level_api/util.py +101 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/ray/llm.py +21 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/__init__.py +4 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/_ctypes_extensions.py +131 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/_ggml.py +12 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/_internals.py +884 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/_logger.py +50 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/_utils.py +78 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama.py +2458 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama_cache.py +155 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama_chat_format.py +4028 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama_cpp.py +4911 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama_grammar.py +953 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama_speculative.py +64 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama_tokenizer.py +120 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llama_types.py +316 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/llava_cpp.py +154 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/mtmd_cpp.py +716 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/py.typed +0 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/__init__.py +0 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/__main__.py +100 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/app.py +597 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/cli.py +129 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/errors.py +212 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/model.py +327 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/settings.py +244 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/llama_cpp/server/types.py +316 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/tests/test_llama.py +249 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/tests/test_llama_chat_format.py +94 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/tests/test_llama_grammar.py +78 -0
- llama_cpp_beam_search-0.1.0/src/llama-cpp-python/tests/test_llama_speculative.py +21 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beam_search.egg-info/PKG-INFO +55 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beam_search.egg-info/SOURCES.txt +64 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beam_search.egg-info/dependency_links.txt +1 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beam_search.egg-info/entry_points.txt +3 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beam_search.egg-info/requires.txt +4 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beam_search.egg-info/top_level.txt +2 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beamsearch/__init__.py +0 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beamsearch/beam_search.py +202 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beamsearch/completion.py +93 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beamsearch/config.py +14 -0
- llama_cpp_beam_search-0.1.0/src/llama_cpp_beamsearch/grammar.py +169 -0
- llama_cpp_beam_search-0.1.0/tests/test_basic_beams.py +35 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Benedikt Kantz
|
|
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.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llama-cpp-beam-search
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Author-email: Benedikt Kantz <benedikt.kantz@tugraz.at>
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/Dakantz/CHASTE
|
|
7
|
+
Requires-Python: >=3.13
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: lark>=1.3.1
|
|
11
|
+
Requires-Dist: llama-cpp-python
|
|
12
|
+
Requires-Dist: pytest>=9.1.1
|
|
13
|
+
Requires-Dist: tqdm>=4.67.3
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# Beam Search over Efficient `llama.cpp` generations
|
|
17
|
+
|
|
18
|
+
## Theory
|
|
19
|
+
|
|
20
|
+
> Forthcoming...
|
|
21
|
+
|
|
22
|
+
## Example Usage
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from llama_cpp_beamsearch.completion import BeamSearchCompletion
|
|
26
|
+
from llama_cpp_beamsearch.config import BeamSearchConfig
|
|
27
|
+
from llama_cpp import Llama, LlamaGrammar, ChatCompletionRequestMessage
|
|
28
|
+
|
|
29
|
+
model = Llama.from_pretrained(
|
|
30
|
+
repo_id="unsloth/Qwen3-0.6B-GGUF",
|
|
31
|
+
filename="*Q4_0.gguf",
|
|
32
|
+
verbose=False,
|
|
33
|
+
logits_all=True,
|
|
34
|
+
)
|
|
35
|
+
allowed_tokens = ["Wrench", "Screwdriver", "Ornament"]
|
|
36
|
+
allowed_tokens_str = " | ".join(f'"{t}"' for t in allowed_tokens)
|
|
37
|
+
grammar = LlamaGrammar(
|
|
38
|
+
_grammar=f"""
|
|
39
|
+
root ::= allowed_tokens
|
|
40
|
+
start ::= ( allowed_tokens " " )*
|
|
41
|
+
allowed_tokens ::= {allowed_tokens_str}
|
|
42
|
+
"""
|
|
43
|
+
)
|
|
44
|
+
config = BeamSearchConfig(
|
|
45
|
+
max_depth=1,
|
|
46
|
+
end_token=None,
|
|
47
|
+
k_progress=[2, 3],
|
|
48
|
+
)
|
|
49
|
+
completion = BeamSearchCompletion(model, grammar, config)
|
|
50
|
+
|
|
51
|
+
message = "Hello?"
|
|
52
|
+
|
|
53
|
+
result = completion.completion_beam_search(message, max_tokens=5)
|
|
54
|
+
assert re.match(r"^((Wrench|Screwdriver|Ornament) ?)*$", result)
|
|
55
|
+
```
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Beam Search over Efficient `llama.cpp` generations
|
|
2
|
+
|
|
3
|
+
## Theory
|
|
4
|
+
|
|
5
|
+
> Forthcoming...
|
|
6
|
+
|
|
7
|
+
## Example Usage
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from llama_cpp_beamsearch.completion import BeamSearchCompletion
|
|
11
|
+
from llama_cpp_beamsearch.config import BeamSearchConfig
|
|
12
|
+
from llama_cpp import Llama, LlamaGrammar, ChatCompletionRequestMessage
|
|
13
|
+
|
|
14
|
+
model = Llama.from_pretrained(
|
|
15
|
+
repo_id="unsloth/Qwen3-0.6B-GGUF",
|
|
16
|
+
filename="*Q4_0.gguf",
|
|
17
|
+
verbose=False,
|
|
18
|
+
logits_all=True,
|
|
19
|
+
)
|
|
20
|
+
allowed_tokens = ["Wrench", "Screwdriver", "Ornament"]
|
|
21
|
+
allowed_tokens_str = " | ".join(f'"{t}"' for t in allowed_tokens)
|
|
22
|
+
grammar = LlamaGrammar(
|
|
23
|
+
_grammar=f"""
|
|
24
|
+
root ::= allowed_tokens
|
|
25
|
+
start ::= ( allowed_tokens " " )*
|
|
26
|
+
allowed_tokens ::= {allowed_tokens_str}
|
|
27
|
+
"""
|
|
28
|
+
)
|
|
29
|
+
config = BeamSearchConfig(
|
|
30
|
+
max_depth=1,
|
|
31
|
+
end_token=None,
|
|
32
|
+
k_progress=[2, 3],
|
|
33
|
+
)
|
|
34
|
+
completion = BeamSearchCompletion(model, grammar, config)
|
|
35
|
+
|
|
36
|
+
message = "Hello?"
|
|
37
|
+
|
|
38
|
+
result = completion.completion_beam_search(message, max_tokens=5)
|
|
39
|
+
assert re.match(r"^((Wrench|Screwdriver|Ornament) ?)*$", result)
|
|
40
|
+
```
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "llama-cpp-beam-search"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = ""
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.13"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"lark>=1.3.1",
|
|
9
|
+
"llama-cpp-python",
|
|
10
|
+
"pytest>=9.1.1",
|
|
11
|
+
"tqdm>=4.67.3",
|
|
12
|
+
]
|
|
13
|
+
authors = [{ name = "Benedikt Kantz", email = "benedikt.kantz@tugraz.at" }]
|
|
14
|
+
license = "MIT"
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Repository = "https://github.com/Dakantz/CHASTE"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
[tool.uv]
|
|
21
|
+
package = true
|
|
22
|
+
|
|
23
|
+
[tool.uv.sources]
|
|
24
|
+
llama-cpp-python = { workspace = true }
|
|
25
|
+
|
|
26
|
+
[project.scripts]
|
|
27
|
+
tex-typst-helper = "texty_tool.main:app"
|
|
28
|
+
texty-tool = "texty_tool.main:app"
|
|
@@ -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
|
+
)
|
llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_embedding.py
ADDED
|
@@ -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!"))
|
llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_inference.py
ADDED
|
@@ -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))
|
llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_infill.py
ADDED
|
@@ -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
|
+
)
|
llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/high_level_api_streaming.py
ADDED
|
@@ -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))
|
llama_cpp_beam_search-0.1.0/src/llama-cpp-python/examples/high_level_api/langchain_custom_llm.py
ADDED
|
@@ -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"))
|