Spaces:
Build error
Build error
Illumotion
commited on
Commit
•
3e5595b
1
Parent(s):
969f439
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .editorconfig +19 -0
- .gitattributes +3 -0
- .github/ISSUE_TEMPLATE/custom.md +185 -0
- .github/workflows/editorconfig.yml +17 -0
- .github/workflows/tidy-post.yml +20 -0
- .github/workflows/tidy-review.yml +23 -0
- .gitignore +62 -0
- CMakeLists.txt +299 -0
- Dockerfile +10 -0
- LICENSE.md +661 -0
- MIT_LICENSE_GGML_LLAMACPP_ONLY +26 -0
- Makefile +343 -0
- Package.swift +23 -0
- README.md +70 -10
- build-info.h +7 -0
- clblast.dll +3 -0
- convert-lora-to-ggml.py +129 -0
- convert-pth-to-ggml.py +13 -0
- convert.py +1168 -0
- docs/token_generation_performance_tips.md +40 -0
- examples/CMakeLists.txt +47 -0
- examples/Miku.sh +49 -0
- examples/alpaca.sh +19 -0
- examples/baby-llama/CMakeLists.txt +4 -0
- examples/baby-llama/baby-llama.cpp +1692 -0
- examples/benchmark/CMakeLists.txt +7 -0
- examples/benchmark/benchmark-matmult.cpp +257 -0
- examples/chat-13B.bat +57 -0
- examples/chat-13B.sh +41 -0
- examples/chat-persistent.sh +151 -0
- examples/chat.sh +16 -0
- examples/common.cpp +930 -0
- examples/common.h +136 -0
- examples/embedding/CMakeLists.txt +7 -0
- examples/embedding/README.md +3 -0
- examples/embedding/embedding.cpp +91 -0
- examples/gpt4all.sh +15 -0
- examples/jeopardy/README.md +21 -0
- examples/jeopardy/graph.py +56 -0
- examples/jeopardy/jeopardy.sh +30 -0
- examples/jeopardy/qasheet.csv +103 -0
- examples/jeopardy/questions.txt +100 -0
- examples/main/CMakeLists.txt +7 -0
- examples/main/README.md +292 -0
- examples/main/main.cpp +665 -0
- examples/metal/CMakeLists.txt +3 -0
- examples/metal/metal.cpp +102 -0
- examples/perplexity/CMakeLists.txt +7 -0
- examples/perplexity/README.md +3 -0
- examples/perplexity/perplexity.cpp +170 -0
.editorconfig
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# https://EditorConfig.org
|
2 |
+
|
3 |
+
# Top-most EditorConfig file
|
4 |
+
root = true
|
5 |
+
|
6 |
+
# Unix-style newlines with a newline ending every file, utf-8 charset
|
7 |
+
[*]
|
8 |
+
end_of_line = lf
|
9 |
+
insert_final_newline = true
|
10 |
+
trim_trailing_whitespace = true
|
11 |
+
charset = utf-8
|
12 |
+
indent_style = space
|
13 |
+
indent_size = 4
|
14 |
+
|
15 |
+
[Makefile]
|
16 |
+
indent_style = tab
|
17 |
+
|
18 |
+
[prompts/*.txt]
|
19 |
+
insert_final_newline = unset
|
.gitattributes
CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
clblast.dll filter=lfs diff=lfs merge=lfs -text
|
37 |
+
lib/libopenblas.lib filter=lfs diff=lfs merge=lfs -text
|
38 |
+
libopenblas.dll filter=lfs diff=lfs merge=lfs -text
|
.github/ISSUE_TEMPLATE/custom.md
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Issue and enhancement template
|
3 |
+
about: Used to report issues and request enhancements for llama.cpp
|
4 |
+
title: "[User] Insert summary of your issue or enhancement.."
|
5 |
+
labels: ''
|
6 |
+
assignees: ''
|
7 |
+
|
8 |
+
---
|
9 |
+
|
10 |
+
# Prerequisites
|
11 |
+
|
12 |
+
Please answer the following questions for yourself before submitting an issue.
|
13 |
+
|
14 |
+
- [ ] I am running the latest code. Development is very rapid so there are no tagged versions as of now.
|
15 |
+
- [ ] I carefully followed the [README.md](https://github.com/ggerganov/llama.cpp/blob/master/README.md).
|
16 |
+
- [ ] I [searched using keywords relevant to my issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/filtering-and-searching-issues-and-pull-requests) to make sure that I am creating a new issue that is not already open (or closed).
|
17 |
+
- [ ] I reviewed the [Discussions](https://github.com/ggerganov/llama.cpp/discussions), and have a new bug or useful enhancement to share.
|
18 |
+
|
19 |
+
# Expected Behavior
|
20 |
+
|
21 |
+
Please provide a detailed written description of what you were trying to do, and what you expected `llama.cpp` to do.
|
22 |
+
|
23 |
+
# Current Behavior
|
24 |
+
|
25 |
+
Please provide a detailed written description of what `llama.cpp` did, instead.
|
26 |
+
|
27 |
+
# Environment and Context
|
28 |
+
|
29 |
+
Please provide detailed information about your computer setup. This is important in case the issue is not reproducible except for under certain specific conditions.
|
30 |
+
|
31 |
+
* Physical (or virtual) hardware you are using, e.g. for Linux:
|
32 |
+
|
33 |
+
`$ lscpu`
|
34 |
+
|
35 |
+
* Operating System, e.g. for Linux:
|
36 |
+
|
37 |
+
`$ uname -a`
|
38 |
+
|
39 |
+
* SDK version, e.g. for Linux:
|
40 |
+
|
41 |
+
```
|
42 |
+
$ python3 --version
|
43 |
+
$ make --version
|
44 |
+
$ g++ --version
|
45 |
+
```
|
46 |
+
|
47 |
+
# Failure Information (for bugs)
|
48 |
+
|
49 |
+
Please help provide information about the failure if this is a bug. If it is not a bug, please remove the rest of this template.
|
50 |
+
|
51 |
+
# Steps to Reproduce
|
52 |
+
|
53 |
+
Please provide detailed steps for reproducing the issue. We are not sitting in front of your screen, so the more detail the better.
|
54 |
+
|
55 |
+
1. step 1
|
56 |
+
2. step 2
|
57 |
+
3. step 3
|
58 |
+
4. etc.
|
59 |
+
|
60 |
+
# Failure Logs
|
61 |
+
|
62 |
+
Please include any relevant log snippets or files. If it works under one configuration but not under another, please provide logs for both configurations and their corresponding outputs so it is easy to see where behavior changes.
|
63 |
+
|
64 |
+
Also, please try to **avoid using screenshots** if at all possible. Instead, copy/paste the console output and use [Github's markdown](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) to cleanly format your logs for easy readability.
|
65 |
+
|
66 |
+
Example environment info:
|
67 |
+
```
|
68 |
+
llama.cpp$ git log | head -1
|
69 |
+
commit 2af23d30434a677c6416812eea52ccc0af65119c
|
70 |
+
|
71 |
+
llama.cpp$ lscpu | egrep "AMD|Flags"
|
72 |
+
Vendor ID: AuthenticAMD
|
73 |
+
Model name: AMD Ryzen Threadripper 1950X 16-Core Processor
|
74 |
+
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid amd_dcm aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 xsaves clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca sme sev
|
75 |
+
Virtualization: AMD-V
|
76 |
+
|
77 |
+
llama.cpp$ python3 --version
|
78 |
+
Python 3.10.9
|
79 |
+
|
80 |
+
llama.cpp$ pip list | egrep "torch|numpy|sentencepiece"
|
81 |
+
numpy 1.24.2
|
82 |
+
numpydoc 1.5.0
|
83 |
+
sentencepiece 0.1.97
|
84 |
+
torch 1.13.1
|
85 |
+
torchvision 0.14.1
|
86 |
+
|
87 |
+
llama.cpp$ make --version | head -1
|
88 |
+
GNU Make 4.3
|
89 |
+
|
90 |
+
$ md5sum ./models/65B/ggml-model-q4_0.bin
|
91 |
+
dbdd682cce80e2d6e93cefc7449df487 ./models/65B/ggml-model-q4_0.bin
|
92 |
+
```
|
93 |
+
|
94 |
+
Example run with the Linux command [perf](https://www.brendangregg.com/perf.html)
|
95 |
+
```
|
96 |
+
llama.cpp$ perf stat ./main -m ./models/65B/ggml-model-q4_0.bin -t 16 -n 1024 -p "Please close your issue when it has been answered."
|
97 |
+
main: seed = 1679149377
|
98 |
+
llama_model_load: loading model from './models/65B/ggml-model-q4_0.bin' - please wait ...
|
99 |
+
llama_model_load: n_vocab = 32000
|
100 |
+
llama_model_load: n_ctx = 512
|
101 |
+
llama_model_load: n_embd = 8192
|
102 |
+
llama_model_load: n_mult = 256
|
103 |
+
llama_model_load: n_head = 64
|
104 |
+
llama_model_load: n_layer = 80
|
105 |
+
llama_model_load: n_rot = 128
|
106 |
+
llama_model_load: f16 = 2
|
107 |
+
llama_model_load: n_ff = 22016
|
108 |
+
llama_model_load: n_parts = 8
|
109 |
+
llama_model_load: ggml ctx size = 41477.73 MB
|
110 |
+
llama_model_load: memory_size = 2560.00 MB, n_mem = 40960
|
111 |
+
llama_model_load: loading model part 1/8 from './models/65B/ggml-model-q4_0.bin'
|
112 |
+
llama_model_load: .......................................................................................... done
|
113 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
114 |
+
llama_model_load: loading model part 2/8 from './models/65B/ggml-model-q4_0.bin.1'
|
115 |
+
llama_model_load: .......................................................................................... done
|
116 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
117 |
+
llama_model_load: loading model part 3/8 from './models/65B/ggml-model-q4_0.bin.2'
|
118 |
+
llama_model_load: .......................................................................................... done
|
119 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
120 |
+
llama_model_load: loading model part 4/8 from './models/65B/ggml-model-q4_0.bin.3'
|
121 |
+
llama_model_load: .......................................................................................... done
|
122 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
123 |
+
llama_model_load: loading model part 5/8 from './models/65B/ggml-model-q4_0.bin.4'
|
124 |
+
llama_model_load: .......................................................................................... done
|
125 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
126 |
+
llama_model_load: loading model part 6/8 from './models/65B/ggml-model-q4_0.bin.5'
|
127 |
+
llama_model_load: .......................................................................................... done
|
128 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
129 |
+
llama_model_load: loading model part 7/8 from './models/65B/ggml-model-q4_0.bin.6'
|
130 |
+
llama_model_load: .......................................................................................... done
|
131 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
132 |
+
llama_model_load: loading model part 8/8 from './models/65B/ggml-model-q4_0.bin.7'
|
133 |
+
llama_model_load: .......................................................................................... done
|
134 |
+
llama_model_load: model size = 4869.09 MB / num tensors = 723
|
135 |
+
|
136 |
+
system_info: n_threads = 16 / 32 | AVX = 1 | AVX2 = 1 | AVX512 = 0 | FMA = 1 | NEON = 0 | ARM_FMA = 0 | F16C = 1 | FP16_VA = 0 | WASM_SIMD = 0 | BLAS = 0 | SSE3 = 1 | VSX = 0 |
|
137 |
+
|
138 |
+
main: prompt: 'Please close your issue when it has been answered.'
|
139 |
+
main: number of tokens in prompt = 11
|
140 |
+
1 -> ''
|
141 |
+
12148 -> 'Please'
|
142 |
+
3802 -> ' close'
|
143 |
+
596 -> ' your'
|
144 |
+
2228 -> ' issue'
|
145 |
+
746 -> ' when'
|
146 |
+
372 -> ' it'
|
147 |
+
756 -> ' has'
|
148 |
+
1063 -> ' been'
|
149 |
+
7699 -> ' answered'
|
150 |
+
29889 -> '.'
|
151 |
+
|
152 |
+
sampling parameters: temp = 0.800000, top_k = 40, top_p = 0.950000, repeat_last_n = 64, repeat_penalty = 1.300000
|
153 |
+
|
154 |
+
|
155 |
+
Please close your issue when it has been answered.
|
156 |
+
@duncan-donut: I'm trying to figure out what kind of "support" you need for this script and why, exactly? Is there a question about how the code works that hasn't already been addressed in one or more comments below this ticket, or are we talking something else entirely like some sorta bugfixing job because your server setup is different from mine??
|
157 |
+
I can understand if your site needs to be running smoothly and you need help with a fix of sorts but there should really be nothing wrong here that the code itself could not handle. And given that I'm getting reports about how it works perfectly well on some other servers, what exactly are we talking? A detailed report will do wonders in helping us get this resolved for ya quickly so please take your time and describe the issue(s) you see as clearly & concisely as possible!!
|
158 |
+
@duncan-donut: I'm not sure if you have access to cPanel but you could try these instructions. It is worth a shot! Let me know how it goes (or what error message, exactly!) when/if ya give that code a go? [end of text]
|
159 |
+
|
160 |
+
|
161 |
+
main: mem per token = 71159620 bytes
|
162 |
+
main: load time = 19309.95 ms
|
163 |
+
main: sample time = 168.62 ms
|
164 |
+
main: predict time = 223895.61 ms / 888.47 ms per token
|
165 |
+
main: total time = 246406.42 ms
|
166 |
+
|
167 |
+
Performance counter stats for './main -m ./models/65B/ggml-model-q4_0.bin -t 16 -n 1024 -p Please close your issue when it has been answered.':
|
168 |
+
|
169 |
+
3636882.89 msec task-clock # 14.677 CPUs utilized
|
170 |
+
13509 context-switches # 3.714 /sec
|
171 |
+
2436 cpu-migrations # 0.670 /sec
|
172 |
+
10476679 page-faults # 2.881 K/sec
|
173 |
+
13133115082869 cycles # 3.611 GHz (16.77%)
|
174 |
+
29314462753 stalled-cycles-frontend # 0.22% frontend cycles idle (16.76%)
|
175 |
+
10294402631459 stalled-cycles-backend # 78.39% backend cycles idle (16.74%)
|
176 |
+
23479217109614 instructions # 1.79 insn per cycle
|
177 |
+
# 0.44 stalled cycles per insn (16.76%)
|
178 |
+
2353072268027 branches # 647.002 M/sec (16.77%)
|
179 |
+
1998682780 branch-misses # 0.08% of all branches (16.76%)
|
180 |
+
|
181 |
+
247.802177522 seconds time elapsed
|
182 |
+
|
183 |
+
3618.573072000 seconds user
|
184 |
+
18.491698000 seconds sys
|
185 |
+
```
|
.github/workflows/editorconfig.yml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: EditorConfig Checker
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
branches:
|
6 |
+
- master
|
7 |
+
pull_request:
|
8 |
+
branches:
|
9 |
+
- master
|
10 |
+
|
11 |
+
jobs:
|
12 |
+
editorconfig:
|
13 |
+
runs-on: ubuntu-latest
|
14 |
+
steps:
|
15 |
+
- uses: actions/checkout@v3
|
16 |
+
- uses: editorconfig-checker/action-editorconfig-checker@main
|
17 |
+
- run: editorconfig-checker
|
.github/workflows/tidy-post.yml
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: clang-tidy review post comments
|
2 |
+
|
3 |
+
on:
|
4 |
+
workflow_dispatch:
|
5 |
+
workflows: ["clang-tidy-review"]
|
6 |
+
types:
|
7 |
+
- completed
|
8 |
+
|
9 |
+
jobs:
|
10 |
+
build:
|
11 |
+
runs-on: ubuntu-latest
|
12 |
+
|
13 |
+
steps:
|
14 |
+
- uses: ZedThree/clang-tidy-review/post@v0.13.0
|
15 |
+
# lgtm_comment_body, max_comments, and annotations need to be set on the posting workflow in a split setup
|
16 |
+
with:
|
17 |
+
# adjust options as necessary
|
18 |
+
lgtm_comment_body: ''
|
19 |
+
annotations: false
|
20 |
+
max_comments: 25
|
.github/workflows/tidy-review.yml
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: clang-tidy-review
|
2 |
+
|
3 |
+
on:
|
4 |
+
pull_request:
|
5 |
+
branches:
|
6 |
+
- master
|
7 |
+
|
8 |
+
jobs:
|
9 |
+
clang-tidy-review:
|
10 |
+
runs-on: ubuntu-latest
|
11 |
+
|
12 |
+
steps:
|
13 |
+
- uses: actions/checkout@v3
|
14 |
+
|
15 |
+
- uses: ZedThree/clang-tidy-review@v0.13.0
|
16 |
+
id: review
|
17 |
+
with:
|
18 |
+
lgtm_comment_body: ''
|
19 |
+
build_dir: build
|
20 |
+
cmake_command: cmake . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=on
|
21 |
+
split_workflow: true
|
22 |
+
|
23 |
+
- uses: ZedThree/clang-tidy-review/upload@v0.13.0
|
.gitignore
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.o
|
2 |
+
*.a
|
3 |
+
.DS_Store
|
4 |
+
.build/
|
5 |
+
.cache/
|
6 |
+
.direnv/
|
7 |
+
.envrc
|
8 |
+
.swiftpm
|
9 |
+
.venv
|
10 |
+
.clang-tidy
|
11 |
+
.vs/
|
12 |
+
.vscode/
|
13 |
+
|
14 |
+
build/
|
15 |
+
build-em/
|
16 |
+
build-debug/
|
17 |
+
build-release/
|
18 |
+
build-static/
|
19 |
+
build-cublas/
|
20 |
+
build-opencl/
|
21 |
+
build-metal/
|
22 |
+
build-no-accel/
|
23 |
+
build-sanitize-addr/
|
24 |
+
build-sanitize-thread/
|
25 |
+
|
26 |
+
/main
|
27 |
+
/quantize
|
28 |
+
/quantize-stats
|
29 |
+
/result
|
30 |
+
/perplexity
|
31 |
+
/embedding
|
32 |
+
/benchmark-matmult
|
33 |
+
/vdot
|
34 |
+
/Pipfile
|
35 |
+
/libllama.so
|
36 |
+
|
37 |
+
arm_neon.h
|
38 |
+
compile_commands.json
|
39 |
+
|
40 |
+
__pycache__
|
41 |
+
|
42 |
+
dist/
|
43 |
+
*.spec
|
44 |
+
|
45 |
+
zig-out/
|
46 |
+
zig-cache/
|
47 |
+
|
48 |
+
ppl-*.txt
|
49 |
+
qnt-*.txt
|
50 |
+
perf-*.txt
|
51 |
+
|
52 |
+
examples/jeopardy/results.txt
|
53 |
+
koboldcpp.so
|
54 |
+
koboldcpp_failsafe.so
|
55 |
+
koboldcpp_openblas.so
|
56 |
+
koboldcpp_openblas_noavx2.so
|
57 |
+
koboldcpp_clblast.so
|
58 |
+
koboldcpp.dll
|
59 |
+
koboldcpp_failsafe.dll
|
60 |
+
koboldcpp_openblas.dll
|
61 |
+
koboldcpp_openblas_noavx2.dll
|
62 |
+
koboldcpp_clblast.dll
|
CMakeLists.txt
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# DO NOT USE THIS FILE.
|
2 |
+
# IT'S ONLY FOR CUBLAS BUILD PURPOSES ON WINDOWS VISUAL STUDIO.
|
3 |
+
# IT WILL NOT BE UPDATED OR MAINTAINED !!!
|
4 |
+
|
5 |
+
message(STATUS "============== ============== ==============")
|
6 |
+
message(STATUS "WARNING! Do NOT use this file. It is UNSUPPORTED for normal users. Use MAKE instead.")
|
7 |
+
message(STATUS "It is ONLY for CUBLAS build testing on windows visual studio. IT WILL NOT BE UPDATED OR MAINTAINED !!!")
|
8 |
+
message(STATUS "IF YOU ARE SEEING THIS, you MUST ONLY be building AN EXPERIMENAL WINDOWS CUBLAS BUILD! NOTHING ELSE WILL BE SUPPORTED !!!")
|
9 |
+
message(STATUS "============== ============== ==============")
|
10 |
+
|
11 |
+
cmake_minimum_required(VERSION 3.12) # Don't bump this version for no reason
|
12 |
+
project("llama.cpp" C CXX)
|
13 |
+
|
14 |
+
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
15 |
+
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS 1)
|
16 |
+
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
|
17 |
+
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Release")
|
18 |
+
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
19 |
+
set(LLAMA_STANDALONE ON)
|
20 |
+
set(BUILD_SHARED_LIBS_DEFAULT ON)
|
21 |
+
set(LLAMA_STATIC OFF)
|
22 |
+
set(LLAMA_NATIVE OFF)
|
23 |
+
set(LLAMA_LTO OFF)
|
24 |
+
set(LLAMA_ALL_WARNINGS OFF)
|
25 |
+
set(LLAMA_ALL_WARNINGS_3RD_PARTY OFF)
|
26 |
+
set(LLAMA_GPROF OFF)
|
27 |
+
set(LLAMA_SANITIZE_THREAD OFF)
|
28 |
+
set(LLAMA_SANITIZE_ADDRESS OFF)
|
29 |
+
set(LLAMA_SANITIZE_UNDEFINED OFF)
|
30 |
+
|
31 |
+
# instruction set specific
|
32 |
+
option(LLAMA_AVX "llama: enable AVX" ON)
|
33 |
+
option(LLAMA_AVX2 "llama: enable AVX2" ON)
|
34 |
+
option(LLAMA_AVX512 "llama: enable AVX512" OFF)
|
35 |
+
option(LLAMA_AVX512_VBMI "llama: enable AVX512-VBMI" OFF)
|
36 |
+
option(LLAMA_AVX512_VNNI "llama: enable AVX512-VNNI" OFF)
|
37 |
+
option(LLAMA_FMA "llama: enable FMA" ON)
|
38 |
+
# in MSVC F16C is implied with AVX2/AVX512
|
39 |
+
if (NOT MSVC)
|
40 |
+
option(LLAMA_F16C "llama: enable F16C" ON)
|
41 |
+
endif()
|
42 |
+
|
43 |
+
# 3rd party libs
|
44 |
+
option(LLAMA_CUBLAS "llama: use cuBLAS" ON)
|
45 |
+
|
46 |
+
|
47 |
+
|
48 |
+
#
|
49 |
+
# Compile flags
|
50 |
+
#
|
51 |
+
|
52 |
+
set(CMAKE_CXX_STANDARD 11)
|
53 |
+
set(CMAKE_CXX_STANDARD_REQUIRED true)
|
54 |
+
set(CMAKE_C_STANDARD 11)
|
55 |
+
set(CMAKE_C_STANDARD_REQUIRED true)
|
56 |
+
set(THREADS_PREFER_PTHREAD_FLAG ON)
|
57 |
+
find_package(Threads REQUIRED)
|
58 |
+
|
59 |
+
add_compile_definitions(GGML_USE_K_QUANTS)
|
60 |
+
|
61 |
+
if (LLAMA_CUBLAS)
|
62 |
+
cmake_minimum_required(VERSION 3.17)
|
63 |
+
|
64 |
+
find_package(CUDAToolkit)
|
65 |
+
if (CUDAToolkit_FOUND)
|
66 |
+
message(STATUS "cuBLAS found")
|
67 |
+
|
68 |
+
enable_language(CUDA)
|
69 |
+
|
70 |
+
set(GGML_CUDA_SOURCES ggml-cuda.cu ggml-cuda.h)
|
71 |
+
set(GGML_V2_CUDA_SOURCES otherarch/ggml_v2-cuda.cu otherarch/ggml_v2-cuda.h)
|
72 |
+
|
73 |
+
add_compile_definitions(GGML_USE_CUBLAS)
|
74 |
+
|
75 |
+
if (LLAMA_STATIC)
|
76 |
+
set(LLAMA_EXTRA_LIBS ${LLAMA_EXTRA_LIBS} CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static)
|
77 |
+
else()
|
78 |
+
set(LLAMA_EXTRA_LIBS ${LLAMA_EXTRA_LIBS} CUDA::cudart CUDA::cublas CUDA::cublasLt)
|
79 |
+
endif()
|
80 |
+
|
81 |
+
else()
|
82 |
+
message(WARNING "cuBLAS not found")
|
83 |
+
endif()
|
84 |
+
endif()
|
85 |
+
|
86 |
+
|
87 |
+
|
88 |
+
if (LLAMA_ALL_WARNINGS)
|
89 |
+
if (NOT MSVC)
|
90 |
+
set(c_flags
|
91 |
+
-Wall
|
92 |
+
-Wextra
|
93 |
+
-Wpedantic
|
94 |
+
-Wcast-qual
|
95 |
+
-Wdouble-promotion
|
96 |
+
-Wshadow
|
97 |
+
-Wstrict-prototypes
|
98 |
+
-Wpointer-arith
|
99 |
+
)
|
100 |
+
set(cxx_flags
|
101 |
+
-Wall
|
102 |
+
-Wextra
|
103 |
+
-Wpedantic
|
104 |
+
-Wcast-qual
|
105 |
+
-Wno-unused-function
|
106 |
+
-Wno-multichar
|
107 |
+
)
|
108 |
+
else()
|
109 |
+
# todo : msvc
|
110 |
+
endif()
|
111 |
+
|
112 |
+
add_compile_options(
|
113 |
+
"$<$<COMPILE_LANGUAGE:C>:${c_flags}>"
|
114 |
+
"$<$<COMPILE_LANGUAGE:CXX>:${cxx_flags}>"
|
115 |
+
)
|
116 |
+
|
117 |
+
endif()
|
118 |
+
|
119 |
+
if (MSVC)
|
120 |
+
add_compile_definitions(_CRT_SECURE_NO_WARNINGS)
|
121 |
+
|
122 |
+
if (BUILD_SHARED_LIBS)
|
123 |
+
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
|
124 |
+
endif()
|
125 |
+
endif()
|
126 |
+
|
127 |
+
if (LLAMA_LTO)
|
128 |
+
include(CheckIPOSupported)
|
129 |
+
check_ipo_supported(RESULT result OUTPUT output)
|
130 |
+
if (result)
|
131 |
+
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
|
132 |
+
else()
|
133 |
+
message(WARNING "IPO is not supported: ${output}")
|
134 |
+
endif()
|
135 |
+
endif()
|
136 |
+
|
137 |
+
# Architecture specific
|
138 |
+
# TODO: probably these flags need to be tweaked on some architectures
|
139 |
+
# feel free to update the Makefile for your architecture and send a pull request or issue
|
140 |
+
message(STATUS "CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
|
141 |
+
if (NOT MSVC)
|
142 |
+
if (LLAMA_STATIC)
|
143 |
+
add_link_options(-static)
|
144 |
+
if (MINGW)
|
145 |
+
add_link_options(-static-libgcc -static-libstdc++)
|
146 |
+
endif()
|
147 |
+
endif()
|
148 |
+
if (LLAMA_GPROF)
|
149 |
+
add_compile_options(-pg)
|
150 |
+
endif()
|
151 |
+
if (LLAMA_NATIVE)
|
152 |
+
add_compile_options(-march=native)
|
153 |
+
endif()
|
154 |
+
endif()
|
155 |
+
|
156 |
+
if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "arm" OR ${CMAKE_SYSTEM_PROCESSOR} MATCHES "aarch64")
|
157 |
+
message(STATUS "ARM detected")
|
158 |
+
if (MSVC)
|
159 |
+
# TODO: arm msvc?
|
160 |
+
else()
|
161 |
+
if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "aarch64")
|
162 |
+
# Apple M1, M2, etc.
|
163 |
+
# Raspberry Pi 3, 4, Zero 2 (64-bit)
|
164 |
+
add_compile_options(-mcpu=native)
|
165 |
+
endif()
|
166 |
+
if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "armv6")
|
167 |
+
# Raspberry Pi 1, Zero
|
168 |
+
add_compile_options(-mfpu=neon-fp-armv8 -mfp16-format=ieee -mno-unaligned-access)
|
169 |
+
endif()
|
170 |
+
if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "armv7")
|
171 |
+
# Raspberry Pi 2
|
172 |
+
add_compile_options(-mfpu=neon-fp-armv8 -mfp16-format=ieee -mno-unaligned-access -funsafe-math-optimizations)
|
173 |
+
endif()
|
174 |
+
if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "armv8")
|
175 |
+
# Raspberry Pi 3, 4, Zero 2 (32-bit)
|
176 |
+
add_compile_options(-mfp16-format=ieee -mno-unaligned-access)
|
177 |
+
endif()
|
178 |
+
endif()
|
179 |
+
elseif (${CMAKE_SYSTEM_PROCESSOR} MATCHES "^(x86_64|i686|AMD64)$")
|
180 |
+
message(STATUS "x86 detected")
|
181 |
+
if (MSVC)
|
182 |
+
if (LLAMA_AVX512)
|
183 |
+
add_compile_options($<$<COMPILE_LANGUAGE:C>:/arch:AVX512>)
|
184 |
+
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/arch:AVX512>)
|
185 |
+
# MSVC has no compile-time flags enabling specific
|
186 |
+
# AVX512 extensions, neither it defines the
|
187 |
+
# macros corresponding to the extensions.
|
188 |
+
# Do it manually.
|
189 |
+
if (LLAMA_AVX512_VBMI)
|
190 |
+
add_compile_definitions($<$<COMPILE_LANGUAGE:C>:__AVX512VBMI__>)
|
191 |
+
add_compile_definitions($<$<COMPILE_LANGUAGE:CXX>:__AVX512VBMI__>)
|
192 |
+
endif()
|
193 |
+
if (LLAMA_AVX512_VNNI)
|
194 |
+
add_compile_definitions($<$<COMPILE_LANGUAGE:C>:__AVX512VNNI__>)
|
195 |
+
add_compile_definitions($<$<COMPILE_LANGUAGE:CXX>:__AVX512VNNI__>)
|
196 |
+
endif()
|
197 |
+
elseif (LLAMA_AVX2)
|
198 |
+
add_compile_options($<$<COMPILE_LANGUAGE:C>:/arch:AVX2>)
|
199 |
+
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/arch:AVX2>)
|
200 |
+
elseif (LLAMA_AVX)
|
201 |
+
add_compile_options($<$<COMPILE_LANGUAGE:C>:/arch:AVX>)
|
202 |
+
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/arch:AVX>)
|
203 |
+
endif()
|
204 |
+
else()
|
205 |
+
if (LLAMA_F16C)
|
206 |
+
add_compile_options(-mf16c)
|
207 |
+
endif()
|
208 |
+
if (LLAMA_FMA)
|
209 |
+
add_compile_options(-mfma)
|
210 |
+
endif()
|
211 |
+
if (LLAMA_AVX)
|
212 |
+
add_compile_options(-mavx)
|
213 |
+
endif()
|
214 |
+
if (LLAMA_AVX2)
|
215 |
+
add_compile_options(-mavx2)
|
216 |
+
endif()
|
217 |
+
if (LLAMA_AVX512)
|
218 |
+
add_compile_options(-mavx512f)
|
219 |
+
add_compile_options(-mavx512bw)
|
220 |
+
endif()
|
221 |
+
if (LLAMA_AVX512_VBMI)
|
222 |
+
add_compile_options(-mavx512vbmi)
|
223 |
+
endif()
|
224 |
+
if (LLAMA_AVX512_VNNI)
|
225 |
+
add_compile_options(-mavx512vnni)
|
226 |
+
endif()
|
227 |
+
endif()
|
228 |
+
elseif (${CMAKE_SYSTEM_PROCESSOR} MATCHES "ppc64")
|
229 |
+
message(STATUS "PowerPC detected")
|
230 |
+
add_compile_options(-mcpu=native -mtune=native)
|
231 |
+
#TODO: Add targets for Power8/Power9 (Altivec/VSX) and Power10(MMA) and query for big endian systems (ppc64/le/be)
|
232 |
+
else()
|
233 |
+
message(STATUS "Unknown architecture")
|
234 |
+
endif()
|
235 |
+
|
236 |
+
#
|
237 |
+
# Build libraries
|
238 |
+
#
|
239 |
+
|
240 |
+
add_library(ggml OBJECT
|
241 |
+
ggml.c
|
242 |
+
ggml.h
|
243 |
+
k_quants.h
|
244 |
+
k_quants.c
|
245 |
+
${GGML_CUDA_SOURCES})
|
246 |
+
target_include_directories(ggml PUBLIC . ./otherarch ./otherarch/tools)
|
247 |
+
target_compile_features(ggml PUBLIC c_std_11) # don't bump
|
248 |
+
target_link_libraries(ggml PUBLIC Threads::Threads ${LLAMA_EXTRA_LIBS})
|
249 |
+
set_target_properties(ggml PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
250 |
+
|
251 |
+
add_library(ggml_v1 OBJECT
|
252 |
+
otherarch/ggml_v1.c
|
253 |
+
otherarch/ggml_v1.h)
|
254 |
+
target_include_directories(ggml_v1 PUBLIC . ./otherarch ./otherarch/tools)
|
255 |
+
target_compile_features(ggml_v1 PUBLIC c_std_11) # don't bump
|
256 |
+
target_link_libraries(ggml_v1 PUBLIC Threads::Threads ${LLAMA_EXTRA_LIBS})
|
257 |
+
set_target_properties(ggml_v1 PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
258 |
+
|
259 |
+
add_library(ggml_v2 OBJECT
|
260 |
+
otherarch/ggml_v2.c
|
261 |
+
otherarch/ggml_v2.h
|
262 |
+
${GGML_V2_CUDA_SOURCES})
|
263 |
+
target_include_directories(ggml_v2 PUBLIC . ./otherarch ./otherarch/tools)
|
264 |
+
target_compile_features(ggml_v2 PUBLIC c_std_11) # don't bump
|
265 |
+
target_link_libraries(ggml_v2 PUBLIC Threads::Threads ${LLAMA_EXTRA_LIBS})
|
266 |
+
set_target_properties(ggml_v2 PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
267 |
+
|
268 |
+
add_library(common2
|
269 |
+
examples/common.cpp
|
270 |
+
examples/common.h)
|
271 |
+
target_include_directories(common2 PUBLIC . ./otherarch ./otherarch/tools ./examples)
|
272 |
+
target_compile_features(common2 PUBLIC cxx_std_11) # don't bump
|
273 |
+
target_link_libraries(common2 PRIVATE ggml ${LLAMA_EXTRA_LIBS})
|
274 |
+
set_target_properties(common2 PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
275 |
+
|
276 |
+
add_library(gpttype_adapter
|
277 |
+
gpttype_adapter.cpp)
|
278 |
+
target_include_directories(gpttype_adapter PUBLIC . ./otherarch ./otherarch/tools ./examples)
|
279 |
+
target_compile_features(gpttype_adapter PUBLIC cxx_std_11) # don't bump
|
280 |
+
target_link_libraries(gpttype_adapter PRIVATE common2 ggml ${LLAMA_EXTRA_LIBS})
|
281 |
+
set_target_properties(gpttype_adapter PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
282 |
+
|
283 |
+
|
284 |
+
if (GGML_CUDA_SOURCES)
|
285 |
+
message(STATUS "GGML CUDA sources found, configuring CUDA architecture")
|
286 |
+
set_property(TARGET ggml PROPERTY CUDA_ARCHITECTURES OFF)
|
287 |
+
set_property(TARGET ggml PROPERTY CUDA_SELECT_NVCC_ARCH_FLAGS "Auto")
|
288 |
+
endif()
|
289 |
+
|
290 |
+
set(TARGET koboldcpp)
|
291 |
+
add_library(${TARGET} SHARED expose.cpp expose.h)
|
292 |
+
target_include_directories(${TARGET} PUBLIC . ./otherarch ./otherarch/tools ./examples)
|
293 |
+
target_compile_features(${TARGET} PUBLIC cxx_std_11) # don't bump
|
294 |
+
set_target_properties(${TARGET} PROPERTIES PREFIX "")
|
295 |
+
set_target_properties(${TARGET} PROPERTIES OUTPUT_NAME "koboldcpp")
|
296 |
+
set_target_properties(${TARGET} PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
297 |
+
target_link_libraries(${TARGET} PUBLIC ggml ggml_v1 ggml_v2 common2 gpttype_adapter ${CMAKE_THREAD_LIBS_INIT})
|
298 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_11)
|
299 |
+
|
Dockerfile
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python
|
2 |
+
WORKDIR /app
|
3 |
+
COPY . .
|
4 |
+
RUN apt update \
|
5 |
+
&& apt install build-essential wget libopenblas-dev make -y \
|
6 |
+
&& make \
|
7 |
+
&& wget https://huggingface.co/xzuyn/GPT-J-Shinen-6B-GGML/resolve/main/ggjtv1-model-q5_1.bin \
|
8 |
+
&& apt remove build-essential wget make -y
|
9 |
+
|
10 |
+
ENTRYPOINT ["python", "koboldcpp.py", "ggjtv1-model-q5_1.bin", "--port", "7860", "--smartcontext"]
|
LICENSE.md
ADDED
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 19 November 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works, specifically designed to ensure
|
12 |
+
cooperation with the community in the case of network server software.
|
13 |
+
|
14 |
+
The licenses for most software and other practical works are designed
|
15 |
+
to take away your freedom to share and change the works. By contrast,
|
16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
17 |
+
share and change all versions of a program--to make sure it remains free
|
18 |
+
software for all its users.
|
19 |
+
|
20 |
+
When we speak of free software, we are referring to freedom, not
|
21 |
+
price. Our General Public Licenses are designed to make sure that you
|
22 |
+
have the freedom to distribute copies of free software (and charge for
|
23 |
+
them if you wish), that you receive source code or can get it if you
|
24 |
+
want it, that you can change the software or use pieces of it in new
|
25 |
+
free programs, and that you know you can do these things.
|
26 |
+
|
27 |
+
Developers that use our General Public Licenses protect your rights
|
28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
29 |
+
you this License which gives you legal permission to copy, distribute
|
30 |
+
and/or modify the software.
|
31 |
+
|
32 |
+
A secondary benefit of defending all users' freedom is that
|
33 |
+
improvements made in alternate versions of the program, if they
|
34 |
+
receive widespread use, become available for other developers to
|
35 |
+
incorporate. Many developers of free software are heartened and
|
36 |
+
encouraged by the resulting cooperation. However, in the case of
|
37 |
+
software used on network servers, this result may fail to come about.
|
38 |
+
The GNU General Public License permits making a modified version and
|
39 |
+
letting the public access it on a server without ever releasing its
|
40 |
+
source code to the public.
|
41 |
+
|
42 |
+
The GNU Affero General Public License is designed specifically to
|
43 |
+
ensure that, in such cases, the modified source code becomes available
|
44 |
+
to the community. It requires the operator of a network server to
|
45 |
+
provide the source code of the modified version running there to the
|
46 |
+
users of that server. Therefore, public use of a modified version, on
|
47 |
+
a publicly accessible server, gives the public access to the source
|
48 |
+
code of the modified version.
|
49 |
+
|
50 |
+
An older license, called the Affero General Public License and
|
51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
53 |
+
released a new version of the Affero GPL which permits relicensing under
|
54 |
+
this license.
|
55 |
+
|
56 |
+
The precise terms and conditions for copying, distribution and
|
57 |
+
modification follow.
|
58 |
+
|
59 |
+
TERMS AND CONDITIONS
|
60 |
+
|
61 |
+
0. Definitions.
|
62 |
+
|
63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
64 |
+
|
65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
66 |
+
works, such as semiconductor masks.
|
67 |
+
|
68 |
+
"The Program" refers to any copyrightable work licensed under this
|
69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
70 |
+
"recipients" may be individuals or organizations.
|
71 |
+
|
72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
73 |
+
in a fashion requiring copyright permission, other than the making of an
|
74 |
+
exact copy. The resulting work is called a "modified version" of the
|
75 |
+
earlier work or a work "based on" the earlier work.
|
76 |
+
|
77 |
+
A "covered work" means either the unmodified Program or a work based
|
78 |
+
on the Program.
|
79 |
+
|
80 |
+
To "propagate" a work means to do anything with it that, without
|
81 |
+
permission, would make you directly or secondarily liable for
|
82 |
+
infringement under applicable copyright law, except executing it on a
|
83 |
+
computer or modifying a private copy. Propagation includes copying,
|
84 |
+
distribution (with or without modification), making available to the
|
85 |
+
public, and in some countries other activities as well.
|
86 |
+
|
87 |
+
To "convey" a work means any kind of propagation that enables other
|
88 |
+
parties to make or receive copies. Mere interaction with a user through
|
89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
90 |
+
|
91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
92 |
+
to the extent that it includes a convenient and prominently visible
|
93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
94 |
+
tells the user that there is no warranty for the work (except to the
|
95 |
+
extent that warranties are provided), that licensees may convey the
|
96 |
+
work under this License, and how to view a copy of this License. If
|
97 |
+
the interface presents a list of user commands or options, such as a
|
98 |
+
menu, a prominent item in the list meets this criterion.
|
99 |
+
|
100 |
+
1. Source Code.
|
101 |
+
|
102 |
+
The "source code" for a work means the preferred form of the work
|
103 |
+
for making modifications to it. "Object code" means any non-source
|
104 |
+
form of a work.
|
105 |
+
|
106 |
+
A "Standard Interface" means an interface that either is an official
|
107 |
+
standard defined by a recognized standards body, or, in the case of
|
108 |
+
interfaces specified for a particular programming language, one that
|
109 |
+
is widely used among developers working in that language.
|
110 |
+
|
111 |
+
The "System Libraries" of an executable work include anything, other
|
112 |
+
than the work as a whole, that (a) is included in the normal form of
|
113 |
+
packaging a Major Component, but which is not part of that Major
|
114 |
+
Component, and (b) serves only to enable use of the work with that
|
115 |
+
Major Component, or to implement a Standard Interface for which an
|
116 |
+
implementation is available to the public in source code form. A
|
117 |
+
"Major Component", in this context, means a major essential component
|
118 |
+
(kernel, window system, and so on) of the specific operating system
|
119 |
+
(if any) on which the executable work runs, or a compiler used to
|
120 |
+
produce the work, or an object code interpreter used to run it.
|
121 |
+
|
122 |
+
The "Corresponding Source" for a work in object code form means all
|
123 |
+
the source code needed to generate, install, and (for an executable
|
124 |
+
work) run the object code and to modify the work, including scripts to
|
125 |
+
control those activities. However, it does not include the work's
|
126 |
+
System Libraries, or general-purpose tools or generally available free
|
127 |
+
programs which are used unmodified in performing those activities but
|
128 |
+
which are not part of the work. For example, Corresponding Source
|
129 |
+
includes interface definition files associated with source files for
|
130 |
+
the work, and the source code for shared libraries and dynamically
|
131 |
+
linked subprograms that the work is specifically designed to require,
|
132 |
+
such as by intimate data communication or control flow between those
|
133 |
+
subprograms and other parts of the work.
|
134 |
+
|
135 |
+
The Corresponding Source need not include anything that users
|
136 |
+
can regenerate automatically from other parts of the Corresponding
|
137 |
+
Source.
|
138 |
+
|
139 |
+
The Corresponding Source for a work in source code form is that
|
140 |
+
same work.
|
141 |
+
|
142 |
+
2. Basic Permissions.
|
143 |
+
|
144 |
+
All rights granted under this License are granted for the term of
|
145 |
+
copyright on the Program, and are irrevocable provided the stated
|
146 |
+
conditions are met. This License explicitly affirms your unlimited
|
147 |
+
permission to run the unmodified Program. The output from running a
|
148 |
+
covered work is covered by this License only if the output, given its
|
149 |
+
content, constitutes a covered work. This License acknowledges your
|
150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
151 |
+
|
152 |
+
You may make, run and propagate covered works that you do not
|
153 |
+
convey, without conditions so long as your license otherwise remains
|
154 |
+
in force. You may convey covered works to others for the sole purpose
|
155 |
+
of having them make modifications exclusively for you, or provide you
|
156 |
+
with facilities for running those works, provided that you comply with
|
157 |
+
the terms of this License in conveying all material for which you do
|
158 |
+
not control copyright. Those thus making or running the covered works
|
159 |
+
for you must do so exclusively on your behalf, under your direction
|
160 |
+
and control, on terms that prohibit them from making any copies of
|
161 |
+
your copyrighted material outside their relationship with you.
|
162 |
+
|
163 |
+
Conveying under any other circumstances is permitted solely under
|
164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
165 |
+
makes it unnecessary.
|
166 |
+
|
167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
168 |
+
|
169 |
+
No covered work shall be deemed part of an effective technological
|
170 |
+
measure under any applicable law fulfilling obligations under article
|
171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
172 |
+
similar laws prohibiting or restricting circumvention of such
|
173 |
+
measures.
|
174 |
+
|
175 |
+
When you convey a covered work, you waive any legal power to forbid
|
176 |
+
circumvention of technological measures to the extent such circumvention
|
177 |
+
is effected by exercising rights under this License with respect to
|
178 |
+
the covered work, and you disclaim any intention to limit operation or
|
179 |
+
modification of the work as a means of enforcing, against the work's
|
180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
181 |
+
technological measures.
|
182 |
+
|
183 |
+
4. Conveying Verbatim Copies.
|
184 |
+
|
185 |
+
You may convey verbatim copies of the Program's source code as you
|
186 |
+
receive it, in any medium, provided that you conspicuously and
|
187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
188 |
+
keep intact all notices stating that this License and any
|
189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
190 |
+
keep intact all notices of the absence of any warranty; and give all
|
191 |
+
recipients a copy of this License along with the Program.
|
192 |
+
|
193 |
+
You may charge any price or no price for each copy that you convey,
|
194 |
+
and you may offer support or warranty protection for a fee.
|
195 |
+
|
196 |
+
5. Conveying Modified Source Versions.
|
197 |
+
|
198 |
+
You may convey a work based on the Program, or the modifications to
|
199 |
+
produce it from the Program, in the form of source code under the
|
200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
201 |
+
|
202 |
+
a) The work must carry prominent notices stating that you modified
|
203 |
+
it, and giving a relevant date.
|
204 |
+
|
205 |
+
b) The work must carry prominent notices stating that it is
|
206 |
+
released under this License and any conditions added under section
|
207 |
+
7. This requirement modifies the requirement in section 4 to
|
208 |
+
"keep intact all notices".
|
209 |
+
|
210 |
+
c) You must license the entire work, as a whole, under this
|
211 |
+
License to anyone who comes into possession of a copy. This
|
212 |
+
License will therefore apply, along with any applicable section 7
|
213 |
+
additional terms, to the whole of the work, and all its parts,
|
214 |
+
regardless of how they are packaged. This License gives no
|
215 |
+
permission to license the work in any other way, but it does not
|
216 |
+
invalidate such permission if you have separately received it.
|
217 |
+
|
218 |
+
d) If the work has interactive user interfaces, each must display
|
219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
221 |
+
work need not make them do so.
|
222 |
+
|
223 |
+
A compilation of a covered work with other separate and independent
|
224 |
+
works, which are not by their nature extensions of the covered work,
|
225 |
+
and which are not combined with it such as to form a larger program,
|
226 |
+
in or on a volume of a storage or distribution medium, is called an
|
227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
228 |
+
used to limit the access or legal rights of the compilation's users
|
229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
230 |
+
in an aggregate does not cause this License to apply to the other
|
231 |
+
parts of the aggregate.
|
232 |
+
|
233 |
+
6. Conveying Non-Source Forms.
|
234 |
+
|
235 |
+
You may convey a covered work in object code form under the terms
|
236 |
+
of sections 4 and 5, provided that you also convey the
|
237 |
+
machine-readable Corresponding Source under the terms of this License,
|
238 |
+
in one of these ways:
|
239 |
+
|
240 |
+
a) Convey the object code in, or embodied in, a physical product
|
241 |
+
(including a physical distribution medium), accompanied by the
|
242 |
+
Corresponding Source fixed on a durable physical medium
|
243 |
+
customarily used for software interchange.
|
244 |
+
|
245 |
+
b) Convey the object code in, or embodied in, a physical product
|
246 |
+
(including a physical distribution medium), accompanied by a
|
247 |
+
written offer, valid for at least three years and valid for as
|
248 |
+
long as you offer spare parts or customer support for that product
|
249 |
+
model, to give anyone who possesses the object code either (1) a
|
250 |
+
copy of the Corresponding Source for all the software in the
|
251 |
+
product that is covered by this License, on a durable physical
|
252 |
+
medium customarily used for software interchange, for a price no
|
253 |
+
more than your reasonable cost of physically performing this
|
254 |
+
conveying of source, or (2) access to copy the
|
255 |
+
Corresponding Source from a network server at no charge.
|
256 |
+
|
257 |
+
c) Convey individual copies of the object code with a copy of the
|
258 |
+
written offer to provide the Corresponding Source. This
|
259 |
+
alternative is allowed only occasionally and noncommercially, and
|
260 |
+
only if you received the object code with such an offer, in accord
|
261 |
+
with subsection 6b.
|
262 |
+
|
263 |
+
d) Convey the object code by offering access from a designated
|
264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
265 |
+
Corresponding Source in the same way through the same place at no
|
266 |
+
further charge. You need not require recipients to copy the
|
267 |
+
Corresponding Source along with the object code. If the place to
|
268 |
+
copy the object code is a network server, the Corresponding Source
|
269 |
+
may be on a different server (operated by you or a third party)
|
270 |
+
that supports equivalent copying facilities, provided you maintain
|
271 |
+
clear directions next to the object code saying where to find the
|
272 |
+
Corresponding Source. Regardless of what server hosts the
|
273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
274 |
+
available for as long as needed to satisfy these requirements.
|
275 |
+
|
276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
277 |
+
you inform other peers where the object code and Corresponding
|
278 |
+
Source of the work are being offered to the general public at no
|
279 |
+
charge under subsection 6d.
|
280 |
+
|
281 |
+
A separable portion of the object code, whose source code is excluded
|
282 |
+
from the Corresponding Source as a System Library, need not be
|
283 |
+
included in conveying the object code work.
|
284 |
+
|
285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
286 |
+
tangible personal property which is normally used for personal, family,
|
287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
290 |
+
product received by a particular user, "normally used" refers to a
|
291 |
+
typical or common use of that class of product, regardless of the status
|
292 |
+
of the particular user or of the way in which the particular user
|
293 |
+
actually uses, or expects or is expected to use, the product. A product
|
294 |
+
is a consumer product regardless of whether the product has substantial
|
295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
296 |
+
the only significant mode of use of the product.
|
297 |
+
|
298 |
+
"Installation Information" for a User Product means any methods,
|
299 |
+
procedures, authorization keys, or other information required to install
|
300 |
+
and execute modified versions of a covered work in that User Product from
|
301 |
+
a modified version of its Corresponding Source. The information must
|
302 |
+
suffice to ensure that the continued functioning of the modified object
|
303 |
+
code is in no case prevented or interfered with solely because
|
304 |
+
modification has been made.
|
305 |
+
|
306 |
+
If you convey an object code work under this section in, or with, or
|
307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
308 |
+
part of a transaction in which the right of possession and use of the
|
309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
310 |
+
fixed term (regardless of how the transaction is characterized), the
|
311 |
+
Corresponding Source conveyed under this section must be accompanied
|
312 |
+
by the Installation Information. But this requirement does not apply
|
313 |
+
if neither you nor any third party retains the ability to install
|
314 |
+
modified object code on the User Product (for example, the work has
|
315 |
+
been installed in ROM).
|
316 |
+
|
317 |
+
The requirement to provide Installation Information does not include a
|
318 |
+
requirement to continue to provide support service, warranty, or updates
|
319 |
+
for a work that has been modified or installed by the recipient, or for
|
320 |
+
the User Product in which it has been modified or installed. Access to a
|
321 |
+
network may be denied when the modification itself materially and
|
322 |
+
adversely affects the operation of the network or violates the rules and
|
323 |
+
protocols for communication across the network.
|
324 |
+
|
325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
326 |
+
in accord with this section must be in a format that is publicly
|
327 |
+
documented (and with an implementation available to the public in
|
328 |
+
source code form), and must require no special password or key for
|
329 |
+
unpacking, reading or copying.
|
330 |
+
|
331 |
+
7. Additional Terms.
|
332 |
+
|
333 |
+
"Additional permissions" are terms that supplement the terms of this
|
334 |
+
License by making exceptions from one or more of its conditions.
|
335 |
+
Additional permissions that are applicable to the entire Program shall
|
336 |
+
be treated as though they were included in this License, to the extent
|
337 |
+
that they are valid under applicable law. If additional permissions
|
338 |
+
apply only to part of the Program, that part may be used separately
|
339 |
+
under those permissions, but the entire Program remains governed by
|
340 |
+
this License without regard to the additional permissions.
|
341 |
+
|
342 |
+
When you convey a copy of a covered work, you may at your option
|
343 |
+
remove any additional permissions from that copy, or from any part of
|
344 |
+
it. (Additional permissions may be written to require their own
|
345 |
+
removal in certain cases when you modify the work.) You may place
|
346 |
+
additional permissions on material, added by you to a covered work,
|
347 |
+
for which you have or can give appropriate copyright permission.
|
348 |
+
|
349 |
+
Notwithstanding any other provision of this License, for material you
|
350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
351 |
+
that material) supplement the terms of this License with terms:
|
352 |
+
|
353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
354 |
+
terms of sections 15 and 16 of this License; or
|
355 |
+
|
356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
357 |
+
author attributions in that material or in the Appropriate Legal
|
358 |
+
Notices displayed by works containing it; or
|
359 |
+
|
360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
361 |
+
requiring that modified versions of such material be marked in
|
362 |
+
reasonable ways as different from the original version; or
|
363 |
+
|
364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
365 |
+
authors of the material; or
|
366 |
+
|
367 |
+
e) Declining to grant rights under trademark law for use of some
|
368 |
+
trade names, trademarks, or service marks; or
|
369 |
+
|
370 |
+
f) Requiring indemnification of licensors and authors of that
|
371 |
+
material by anyone who conveys the material (or modified versions of
|
372 |
+
it) with contractual assumptions of liability to the recipient, for
|
373 |
+
any liability that these contractual assumptions directly impose on
|
374 |
+
those licensors and authors.
|
375 |
+
|
376 |
+
All other non-permissive additional terms are considered "further
|
377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
378 |
+
received it, or any part of it, contains a notice stating that it is
|
379 |
+
governed by this License along with a term that is a further
|
380 |
+
restriction, you may remove that term. If a license document contains
|
381 |
+
a further restriction but permits relicensing or conveying under this
|
382 |
+
License, you may add to a covered work material governed by the terms
|
383 |
+
of that license document, provided that the further restriction does
|
384 |
+
not survive such relicensing or conveying.
|
385 |
+
|
386 |
+
If you add terms to a covered work in accord with this section, you
|
387 |
+
must place, in the relevant source files, a statement of the
|
388 |
+
additional terms that apply to those files, or a notice indicating
|
389 |
+
where to find the applicable terms.
|
390 |
+
|
391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
392 |
+
form of a separately written license, or stated as exceptions;
|
393 |
+
the above requirements apply either way.
|
394 |
+
|
395 |
+
8. Termination.
|
396 |
+
|
397 |
+
You may not propagate or modify a covered work except as expressly
|
398 |
+
provided under this License. Any attempt otherwise to propagate or
|
399 |
+
modify it is void, and will automatically terminate your rights under
|
400 |
+
this License (including any patent licenses granted under the third
|
401 |
+
paragraph of section 11).
|
402 |
+
|
403 |
+
However, if you cease all violation of this License, then your
|
404 |
+
license from a particular copyright holder is reinstated (a)
|
405 |
+
provisionally, unless and until the copyright holder explicitly and
|
406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
407 |
+
holder fails to notify you of the violation by some reasonable means
|
408 |
+
prior to 60 days after the cessation.
|
409 |
+
|
410 |
+
Moreover, your license from a particular copyright holder is
|
411 |
+
reinstated permanently if the copyright holder notifies you of the
|
412 |
+
violation by some reasonable means, this is the first time you have
|
413 |
+
received notice of violation of this License (for any work) from that
|
414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
415 |
+
your receipt of the notice.
|
416 |
+
|
417 |
+
Termination of your rights under this section does not terminate the
|
418 |
+
licenses of parties who have received copies or rights from you under
|
419 |
+
this License. If your rights have been terminated and not permanently
|
420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
421 |
+
material under section 10.
|
422 |
+
|
423 |
+
9. Acceptance Not Required for Having Copies.
|
424 |
+
|
425 |
+
You are not required to accept this License in order to receive or
|
426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
428 |
+
to receive a copy likewise does not require acceptance. However,
|
429 |
+
nothing other than this License grants you permission to propagate or
|
430 |
+
modify any covered work. These actions infringe copyright if you do
|
431 |
+
not accept this License. Therefore, by modifying or propagating a
|
432 |
+
covered work, you indicate your acceptance of this License to do so.
|
433 |
+
|
434 |
+
10. Automatic Licensing of Downstream Recipients.
|
435 |
+
|
436 |
+
Each time you convey a covered work, the recipient automatically
|
437 |
+
receives a license from the original licensors, to run, modify and
|
438 |
+
propagate that work, subject to this License. You are not responsible
|
439 |
+
for enforcing compliance by third parties with this License.
|
440 |
+
|
441 |
+
An "entity transaction" is a transaction transferring control of an
|
442 |
+
organization, or substantially all assets of one, or subdividing an
|
443 |
+
organization, or merging organizations. If propagation of a covered
|
444 |
+
work results from an entity transaction, each party to that
|
445 |
+
transaction who receives a copy of the work also receives whatever
|
446 |
+
licenses to the work the party's predecessor in interest had or could
|
447 |
+
give under the previous paragraph, plus a right to possession of the
|
448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
449 |
+
the predecessor has it or can get it with reasonable efforts.
|
450 |
+
|
451 |
+
You may not impose any further restrictions on the exercise of the
|
452 |
+
rights granted or affirmed under this License. For example, you may
|
453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
454 |
+
rights granted under this License, and you may not initiate litigation
|
455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
456 |
+
any patent claim is infringed by making, using, selling, offering for
|
457 |
+
sale, or importing the Program or any portion of it.
|
458 |
+
|
459 |
+
11. Patents.
|
460 |
+
|
461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
462 |
+
License of the Program or a work on which the Program is based. The
|
463 |
+
work thus licensed is called the contributor's "contributor version".
|
464 |
+
|
465 |
+
A contributor's "essential patent claims" are all patent claims
|
466 |
+
owned or controlled by the contributor, whether already acquired or
|
467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
468 |
+
by this License, of making, using, or selling its contributor version,
|
469 |
+
but do not include claims that would be infringed only as a
|
470 |
+
consequence of further modification of the contributor version. For
|
471 |
+
purposes of this definition, "control" includes the right to grant
|
472 |
+
patent sublicenses in a manner consistent with the requirements of
|
473 |
+
this License.
|
474 |
+
|
475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
476 |
+
patent license under the contributor's essential patent claims, to
|
477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
478 |
+
propagate the contents of its contributor version.
|
479 |
+
|
480 |
+
In the following three paragraphs, a "patent license" is any express
|
481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
482 |
+
(such as an express permission to practice a patent or covenant not to
|
483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
484 |
+
party means to make such an agreement or commitment not to enforce a
|
485 |
+
patent against the party.
|
486 |
+
|
487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
488 |
+
and the Corresponding Source of the work is not available for anyone
|
489 |
+
to copy, free of charge and under the terms of this License, through a
|
490 |
+
publicly available network server or other readily accessible means,
|
491 |
+
then you must either (1) cause the Corresponding Source to be so
|
492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
494 |
+
consistent with the requirements of this License, to extend the patent
|
495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
496 |
+
actual knowledge that, but for the patent license, your conveying the
|
497 |
+
covered work in a country, or your recipient's use of the covered work
|
498 |
+
in a country, would infringe one or more identifiable patents in that
|
499 |
+
country that you have reason to believe are valid.
|
500 |
+
|
501 |
+
If, pursuant to or in connection with a single transaction or
|
502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
503 |
+
covered work, and grant a patent license to some of the parties
|
504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
505 |
+
or convey a specific copy of the covered work, then the patent license
|
506 |
+
you grant is automatically extended to all recipients of the covered
|
507 |
+
work and works based on it.
|
508 |
+
|
509 |
+
A patent license is "discriminatory" if it does not include within
|
510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
512 |
+
specifically granted under this License. You may not convey a covered
|
513 |
+
work if you are a party to an arrangement with a third party that is
|
514 |
+
in the business of distributing software, under which you make payment
|
515 |
+
to the third party based on the extent of your activity of conveying
|
516 |
+
the work, and under which the third party grants, to any of the
|
517 |
+
parties who would receive the covered work from you, a discriminatory
|
518 |
+
patent license (a) in connection with copies of the covered work
|
519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
520 |
+
for and in connection with specific products or compilations that
|
521 |
+
contain the covered work, unless you entered into that arrangement,
|
522 |
+
or that patent license was granted, prior to 28 March 2007.
|
523 |
+
|
524 |
+
Nothing in this License shall be construed as excluding or limiting
|
525 |
+
any implied license or other defenses to infringement that may
|
526 |
+
otherwise be available to you under applicable patent law.
|
527 |
+
|
528 |
+
12. No Surrender of Others' Freedom.
|
529 |
+
|
530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
531 |
+
otherwise) that contradict the conditions of this License, they do not
|
532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
534 |
+
License and any other pertinent obligations, then as a consequence you may
|
535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
536 |
+
to collect a royalty for further conveying from those to whom you convey
|
537 |
+
the Program, the only way you could satisfy both those terms and this
|
538 |
+
License would be to refrain entirely from conveying the Program.
|
539 |
+
|
540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
541 |
+
|
542 |
+
Notwithstanding any other provision of this License, if you modify the
|
543 |
+
Program, your modified version must prominently offer all users
|
544 |
+
interacting with it remotely through a computer network (if your version
|
545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
546 |
+
Source of your version by providing access to the Corresponding Source
|
547 |
+
from a network server at no charge, through some standard or customary
|
548 |
+
means of facilitating copying of software. This Corresponding Source
|
549 |
+
shall include the Corresponding Source for any work covered by version 3
|
550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
551 |
+
following paragraph.
|
552 |
+
|
553 |
+
Notwithstanding any other provision of this License, you have
|
554 |
+
permission to link or combine any covered work with a work licensed
|
555 |
+
under version 3 of the GNU General Public License into a single
|
556 |
+
combined work, and to convey the resulting work. The terms of this
|
557 |
+
License will continue to apply to the part which is the covered work,
|
558 |
+
but the work with which it is combined will remain governed by version
|
559 |
+
3 of the GNU General Public License.
|
560 |
+
|
561 |
+
14. Revised Versions of this License.
|
562 |
+
|
563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
566 |
+
address new problems or concerns.
|
567 |
+
|
568 |
+
Each version is given a distinguishing version number. If the
|
569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
570 |
+
Public License "or any later version" applies to it, you have the
|
571 |
+
option of following the terms and conditions either of that numbered
|
572 |
+
version or of any later version published by the Free Software
|
573 |
+
Foundation. If the Program does not specify a version number of the
|
574 |
+
GNU Affero General Public License, you may choose any version ever published
|
575 |
+
by the Free Software Foundation.
|
576 |
+
|
577 |
+
If the Program specifies that a proxy can decide which future
|
578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
579 |
+
public statement of acceptance of a version permanently authorizes you
|
580 |
+
to choose that version for the Program.
|
581 |
+
|
582 |
+
Later license versions may give you additional or different
|
583 |
+
permissions. However, no additional obligations are imposed on any
|
584 |
+
author or copyright holder as a result of your choosing to follow a
|
585 |
+
later version.
|
586 |
+
|
587 |
+
15. Disclaimer of Warranty.
|
588 |
+
|
589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
597 |
+
|
598 |
+
16. Limitation of Liability.
|
599 |
+
|
600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
608 |
+
SUCH DAMAGES.
|
609 |
+
|
610 |
+
17. Interpretation of Sections 15 and 16.
|
611 |
+
|
612 |
+
If the disclaimer of warranty and limitation of liability provided
|
613 |
+
above cannot be given local legal effect according to their terms,
|
614 |
+
reviewing courts shall apply local law that most closely approximates
|
615 |
+
an absolute waiver of all civil liability in connection with the
|
616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
617 |
+
copy of the Program in return for a fee.
|
618 |
+
|
619 |
+
END OF TERMS AND CONDITIONS
|
620 |
+
|
621 |
+
How to Apply These Terms to Your New Programs
|
622 |
+
|
623 |
+
If you develop a new program, and you want it to be of the greatest
|
624 |
+
possible use to the public, the best way to achieve this is to make it
|
625 |
+
free software which everyone can redistribute and change under these terms.
|
626 |
+
|
627 |
+
To do so, attach the following notices to the program. It is safest
|
628 |
+
to attach them to the start of each source file to most effectively
|
629 |
+
state the exclusion of warranty; and each file should have at least
|
630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
631 |
+
|
632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
633 |
+
Copyright (C) <year> <name of author>
|
634 |
+
|
635 |
+
This program is free software: you can redistribute it and/or modify
|
636 |
+
it under the terms of the GNU Affero General Public License as published
|
637 |
+
by the Free Software Foundation, either version 3 of the License, or
|
638 |
+
(at your option) any later version.
|
639 |
+
|
640 |
+
This program is distributed in the hope that it will be useful,
|
641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
643 |
+
GNU Affero General Public License for more details.
|
644 |
+
|
645 |
+
You should have received a copy of the GNU Affero General Public License
|
646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
647 |
+
|
648 |
+
Also add information on how to contact you by electronic and paper mail.
|
649 |
+
|
650 |
+
If your software can interact with users remotely through a computer
|
651 |
+
network, you should also make sure that it provides a way for users to
|
652 |
+
get its source. For example, if your program is a web application, its
|
653 |
+
interface could display a "Source" link that leads users to an archive
|
654 |
+
of the code. There are many ways you could offer source, and different
|
655 |
+
solutions will be better for different programs; see section 13 for the
|
656 |
+
specific requirements.
|
657 |
+
|
658 |
+
You should also get your employer (if you work as a programmer) or school,
|
659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
661 |
+
<https://www.gnu.org/licenses/>.
|
MIT_LICENSE_GGML_LLAMACPP_ONLY
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 Georgi Gerganov
|
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.
|
22 |
+
|
23 |
+
===================================
|
24 |
+
|
25 |
+
Note that the above license applies ONLY to the GGML library and llama.cpp by ggerganov which are licensed under the MIT License
|
26 |
+
Kobold Lite by Concedo and the provided python ctypes bindings in koboldcpp.dll are licensed under the AGPL v3.0 License
|
Makefile
ADDED
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
default: koboldcpp koboldcpp_failsafe koboldcpp_openblas koboldcpp_openblas_noavx2 koboldcpp_clblast
|
2 |
+
tools: quantize_gpt2 quantize_gptj quantize_llama quantize_neox quantize_mpt
|
3 |
+
dev: koboldcpp_openblas
|
4 |
+
dev2: koboldcpp_clblast
|
5 |
+
|
6 |
+
|
7 |
+
ifndef UNAME_S
|
8 |
+
UNAME_S := $(shell uname -s)
|
9 |
+
endif
|
10 |
+
|
11 |
+
ifndef UNAME_P
|
12 |
+
UNAME_P := $(shell uname -p)
|
13 |
+
endif
|
14 |
+
|
15 |
+
ifndef UNAME_M
|
16 |
+
UNAME_M := $(shell uname -m)
|
17 |
+
endif
|
18 |
+
|
19 |
+
ifneq ($(shell grep -e "Arch Linux" -e "ID_LIKE=arch" /etc/os-release 2>/dev/null),)
|
20 |
+
ARCH_ADD = -lcblas
|
21 |
+
endif
|
22 |
+
|
23 |
+
CCV := $(shell $(CC) --version | head -n 1)
|
24 |
+
CXXV := $(shell $(CXX) --version | head -n 1)
|
25 |
+
|
26 |
+
# Mac OS + Arm can report x86_64
|
27 |
+
# ref: https://github.com/ggerganov/whisper.cpp/issues/66#issuecomment-1282546789
|
28 |
+
ifeq ($(UNAME_S),Darwin)
|
29 |
+
ifneq ($(UNAME_P),arm)
|
30 |
+
SYSCTL_M := $(shell sysctl -n hw.optional.arm64 2>/dev/null)
|
31 |
+
ifeq ($(SYSCTL_M),1)
|
32 |
+
# UNAME_P := arm
|
33 |
+
# UNAME_M := arm64
|
34 |
+
warn := $(warning Your arch is announced as x86_64, but it seems to actually be ARM64. Not fixing that can lead to bad performance. For more info see: https://github.com/ggerganov/whisper.cpp/issues/66\#issuecomment-1282546789)
|
35 |
+
endif
|
36 |
+
endif
|
37 |
+
endif
|
38 |
+
|
39 |
+
#
|
40 |
+
# Compile flags
|
41 |
+
#
|
42 |
+
|
43 |
+
# keep standard at C11 and C++11
|
44 |
+
CFLAGS = -I. -I./include -I./include/CL -I./otherarch -I./otherarch/tools -Ofast -DNDEBUG -std=c11 -fPIC -DGGML_USE_K_QUANTS
|
45 |
+
CXXFLAGS = -I. -I./examples -I./include -I./include/CL -I./otherarch -I./otherarch/tools -O3 -DNDEBUG -std=c++11 -fPIC
|
46 |
+
LDFLAGS =
|
47 |
+
|
48 |
+
# these are used on windows, to build some libraries with extra old device compatibility
|
49 |
+
SIMPLECFLAGS =
|
50 |
+
FULLCFLAGS =
|
51 |
+
NONECFLAGS =
|
52 |
+
|
53 |
+
OPENBLAS_FLAGS = -DGGML_USE_OPENBLAS -I/usr/local/include/openblas
|
54 |
+
CLBLAST_FLAGS = -DGGML_USE_CLBLAST
|
55 |
+
FAILSAFE_FLAGS = -DUSE_FAILSAFE
|
56 |
+
|
57 |
+
#lets try enabling everything
|
58 |
+
CFLAGS += -pthread -s
|
59 |
+
CXXFLAGS += -pthread -s -Wno-multichar -Wno-write-strings
|
60 |
+
|
61 |
+
# OS specific
|
62 |
+
# TODO: support Windows
|
63 |
+
ifeq ($(UNAME_S),Linux)
|
64 |
+
CFLAGS += -pthread
|
65 |
+
CXXFLAGS += -pthread
|
66 |
+
endif
|
67 |
+
|
68 |
+
ifeq ($(UNAME_S),Darwin)
|
69 |
+
CFLAGS += -pthread
|
70 |
+
CXXFLAGS += -pthread
|
71 |
+
endif
|
72 |
+
ifeq ($(UNAME_S),FreeBSD)
|
73 |
+
CFLAGS += -pthread
|
74 |
+
CXXFLAGS += -pthread
|
75 |
+
endif
|
76 |
+
ifeq ($(UNAME_S),NetBSD)
|
77 |
+
CFLAGS += -pthread
|
78 |
+
CXXFLAGS += -pthread
|
79 |
+
endif
|
80 |
+
ifeq ($(UNAME_S),OpenBSD)
|
81 |
+
CFLAGS += -pthread
|
82 |
+
CXXFLAGS += -pthread
|
83 |
+
endif
|
84 |
+
ifeq ($(UNAME_S),Haiku)
|
85 |
+
CFLAGS += -pthread
|
86 |
+
CXXFLAGS += -pthread
|
87 |
+
endif
|
88 |
+
|
89 |
+
ifdef LLAMA_GPROF
|
90 |
+
CFLAGS += -pg
|
91 |
+
CXXFLAGS += -pg
|
92 |
+
endif
|
93 |
+
ifdef LLAMA_PERF
|
94 |
+
CFLAGS += -DGGML_PERF
|
95 |
+
CXXFLAGS += -DGGML_PERF
|
96 |
+
endif
|
97 |
+
|
98 |
+
# Architecture specific
|
99 |
+
# TODO: probably these flags need to be tweaked on some architectures
|
100 |
+
# feel free to update the Makefile for your architecture and send a pull request or issue
|
101 |
+
ifeq ($(UNAME_M),$(filter $(UNAME_M),x86_64 i686))
|
102 |
+
# Use all CPU extensions that are available:
|
103 |
+
# old library NEEDS mf16c to work. so we must build with it. new one doesnt
|
104 |
+
ifeq ($(OS),Windows_NT)
|
105 |
+
CFLAGS +=
|
106 |
+
NONECFLAGS += -mno-sse3
|
107 |
+
SIMPLECFLAGS += -mavx -msse3
|
108 |
+
FULLCFLAGS += -mavx2 -msse3 -mfma -mf16c -mavx
|
109 |
+
else
|
110 |
+
# if not on windows, they are clearly building it themselves, so lets just use whatever is supported
|
111 |
+
CFLAGS += -march=native -mtune=native
|
112 |
+
endif
|
113 |
+
endif
|
114 |
+
ifneq ($(filter ppc64%,$(UNAME_M)),)
|
115 |
+
POWER9_M := $(shell grep "POWER9" /proc/cpuinfo)
|
116 |
+
ifneq (,$(findstring POWER9,$(POWER9_M)))
|
117 |
+
CFLAGS += -mcpu=power9
|
118 |
+
CXXFLAGS += -mcpu=power9
|
119 |
+
endif
|
120 |
+
# Require c++23's std::byteswap for big-endian support.
|
121 |
+
ifeq ($(UNAME_M),ppc64)
|
122 |
+
CXXFLAGS += -std=c++23 -DGGML_BIG_ENDIAN
|
123 |
+
endif
|
124 |
+
endif
|
125 |
+
ifndef LLAMA_NO_ACCELERATE
|
126 |
+
# Mac M1 - include Accelerate framework.
|
127 |
+
# `-framework Accelerate` works on Mac Intel as well, with negliable performance boost (as of the predict time).
|
128 |
+
ifeq ($(UNAME_S),Darwin)
|
129 |
+
CFLAGS += -DGGML_USE_ACCELERATE
|
130 |
+
LDFLAGS += -framework Accelerate
|
131 |
+
endif
|
132 |
+
endif
|
133 |
+
|
134 |
+
# it is recommended to use the CMAKE file to build for cublas if you can - will likely work better
|
135 |
+
ifdef LLAMA_CUBLAS
|
136 |
+
CFLAGS += -DGGML_USE_CUBLAS -I/usr/local/cuda/include -I/opt/cuda/include -I$(CUDA_PATH)/targets/x86_64-linux/include
|
137 |
+
CXXFLAGS += -DGGML_USE_CUBLAS -I/usr/local/cuda/include -I/opt/cuda/include -I$(CUDA_PATH)/targets/x86_64-linux/include
|
138 |
+
LDFLAGS += -lcublas -lculibos -lcudart -lcublasLt -lpthread -ldl -lrt -L/usr/local/cuda/lib64 -L/opt/cuda/lib64 -L$(CUDA_PATH)/targets/x86_64-linux/lib
|
139 |
+
OBJS += ggml-cuda.o ggml_v2-cuda.o
|
140 |
+
NVCC = nvcc
|
141 |
+
NVCCFLAGS = --forward-unknown-to-host-compiler -arch=native
|
142 |
+
ifdef LLAMA_CUDA_DMMV_X
|
143 |
+
NVCCFLAGS += -DGGML_CUDA_DMMV_X=$(LLAMA_CUDA_DMMV_X)
|
144 |
+
else
|
145 |
+
NVCCFLAGS += -DGGML_CUDA_DMMV_X=32
|
146 |
+
endif # LLAMA_CUDA_DMMV_X
|
147 |
+
ifdef LLAMA_CUDA_DMMV_Y
|
148 |
+
NVCCFLAGS += -DGGML_CUDA_DMMV_Y=$(LLAMA_CUDA_DMMV_Y)
|
149 |
+
else
|
150 |
+
NVCCFLAGS += -DGGML_CUDA_DMMV_Y=1
|
151 |
+
endif # LLAMA_CUDA_DMMV_Y
|
152 |
+
ggml-cuda.o: ggml-cuda.cu ggml-cuda.h
|
153 |
+
$(NVCC) $(NVCCFLAGS) $(CXXFLAGS) $(CUBLAS_CXXFLAGS) -Wno-pedantic -c $< -o $@
|
154 |
+
ggml_v2-cuda.o: otherarch/ggml_v2-cuda.cu otherarch/ggml_v2-cuda.h
|
155 |
+
$(NVCC) $(NVCCFLAGS) $(CXXFLAGS) $(CUBLAS_CXXFLAGS) -Wno-pedantic -c $< -o $@
|
156 |
+
endif # LLAMA_CUBLAS
|
157 |
+
|
158 |
+
ifdef LLAMA_METAL
|
159 |
+
CFLAGS += -DGGML_USE_METAL -DGGML_METAL_NDEBUG
|
160 |
+
CXXFLAGS += -DGGML_USE_METAL
|
161 |
+
LDFLAGS += -framework Foundation -framework Metal -framework MetalKit -framework MetalPerformanceShaders
|
162 |
+
OBJS += ggml-metal.o
|
163 |
+
|
164 |
+
ggml-metal.o: ggml-metal.m ggml-metal.h
|
165 |
+
$(CC) $(CFLAGS) -c $< -o $@
|
166 |
+
endif # LLAMA_METAL
|
167 |
+
|
168 |
+
ifneq ($(filter aarch64%,$(UNAME_M)),)
|
169 |
+
# Apple M1, M2, etc.
|
170 |
+
# Raspberry Pi 3, 4, Zero 2 (64-bit)
|
171 |
+
CFLAGS +=
|
172 |
+
CXXFLAGS +=
|
173 |
+
endif
|
174 |
+
ifneq ($(filter armv6%,$(UNAME_M)),)
|
175 |
+
# Raspberry Pi 1, Zero
|
176 |
+
CFLAGS += -mfpu=neon-fp-armv8 -mfp16-format=ieee -mno-unaligned-access
|
177 |
+
endif
|
178 |
+
ifneq ($(filter armv7%,$(UNAME_M)),)
|
179 |
+
# Raspberry Pi 2
|
180 |
+
CFLAGS += -mfpu=neon-fp-armv8 -mfp16-format=ieee -mno-unaligned-access -funsafe-math-optimizations
|
181 |
+
endif
|
182 |
+
ifneq ($(filter armv8%,$(UNAME_M)),)
|
183 |
+
# Raspberry Pi 3, 4, Zero 2 (32-bit)
|
184 |
+
CFLAGS += -mfp16-format=ieee -mno-unaligned-access
|
185 |
+
endif
|
186 |
+
|
187 |
+
DEFAULT_BUILD =
|
188 |
+
FAILSAFE_BUILD =
|
189 |
+
OPENBLAS_BUILD =
|
190 |
+
OPENBLAS_NOAVX2_BUILD =
|
191 |
+
CLBLAST_BUILD =
|
192 |
+
CLBLAST_NOAVX2_BUILD =
|
193 |
+
|
194 |
+
ifeq ($(OS),Windows_NT)
|
195 |
+
DEFAULT_BUILD = $(CXX) $(CXXFLAGS) $^ -shared -o $@.dll $(LDFLAGS)
|
196 |
+
FAILSAFE_BUILD = $(CXX) $(CXXFLAGS) $^ -shared -o $@.dll $(LDFLAGS)
|
197 |
+
OPENBLAS_BUILD = $(CXX) $(CXXFLAGS) $^ lib/libopenblas.lib -shared -o $@.dll $(LDFLAGS)
|
198 |
+
OPENBLAS_NOAVX2_BUILD = $(CXX) $(CXXFLAGS) $^ lib/libopenblas.lib -shared -o $@.dll $(LDFLAGS)
|
199 |
+
CLBLAST_BUILD = $(CXX) $(CXXFLAGS) $^ lib/OpenCL.lib lib/clblast.lib -shared -o $@.dll $(LDFLAGS)
|
200 |
+
CLBLAST_NOAVX2_BUILD = $(CXX) $(CXXFLAGS) $^ lib/OpenCL.lib lib/clblast.lib -shared -o $@.dll $(LDFLAGS)
|
201 |
+
else
|
202 |
+
DEFAULT_BUILD = $(CXX) $(CXXFLAGS) $^ -shared -o $@.so $(LDFLAGS)
|
203 |
+
FAILSAFE_BUILD = $(CXX) $(CXXFLAGS) $^ -shared -o $@.so $(LDFLAGS)
|
204 |
+
ifdef LLAMA_OPENBLAS
|
205 |
+
OPENBLAS_BUILD = $(CXX) $(CXXFLAGS) $^ $(ARCH_ADD) -lopenblas -shared -o $@.so $(LDFLAGS)
|
206 |
+
OPENBLAS_NOAVX2_BUILD = $(CXX) $(CXXFLAGS) $^ $(ARCH_ADD) -lopenblas -shared -o $@.so $(LDFLAGS)
|
207 |
+
endif
|
208 |
+
ifdef LLAMA_CLBLAST
|
209 |
+
ifeq ($(UNAME_S),Darwin)
|
210 |
+
CLBLAST_BUILD = $(CXX) $(CXXFLAGS) $^ -lclblast -framework OpenCL $(ARCH_ADD) -lopenblas -shared -o $@.so $(LDFLAGS)
|
211 |
+
CLBLAST_NOAVX2_BUILD = $(CXX) $(CXXFLAGS) $^ -lclblast -framework OpenCL $(ARCH_ADD) -lopenblas -shared -o $@.so $(LDFLAGS)
|
212 |
+
else
|
213 |
+
CLBLAST_BUILD = $(CXX) $(CXXFLAGS) $^ -lclblast -lOpenCL $(ARCH_ADD) -lopenblas -shared -o $@.so $(LDFLAGS)
|
214 |
+
CLBLAST_NOAVX2_BUILD = $(CXX) $(CXXFLAGS) $^ -lclblast -lOpenCL $(ARCH_ADD) -lopenblas -shared -o $@.so $(LDFLAGS)
|
215 |
+
endif
|
216 |
+
endif
|
217 |
+
|
218 |
+
ifndef LLAMA_OPENBLAS
|
219 |
+
ifndef LLAMA_CLBLAST
|
220 |
+
OPENBLAS_BUILD = @echo 'Your OS $(OS) does not appear to be Windows. For faster speeds, install and link a BLAS library. Set LLAMA_OPENBLAS=1 to compile with OpenBLAS support or LLAMA_CLBLAST=1 to compile with ClBlast support. This is just a reminder, not an error.'
|
221 |
+
endif
|
222 |
+
endif
|
223 |
+
endif
|
224 |
+
|
225 |
+
#
|
226 |
+
# Print build information
|
227 |
+
#
|
228 |
+
|
229 |
+
$(info I llama.cpp build info: )
|
230 |
+
$(info I UNAME_S: $(UNAME_S))
|
231 |
+
$(info I UNAME_P: $(UNAME_P))
|
232 |
+
$(info I UNAME_M: $(UNAME_M))
|
233 |
+
$(info I CFLAGS: $(CFLAGS))
|
234 |
+
$(info I CXXFLAGS: $(CXXFLAGS))
|
235 |
+
$(info I LDFLAGS: $(LDFLAGS))
|
236 |
+
$(info I CC: $(CCV))
|
237 |
+
$(info I CXX: $(CXXV))
|
238 |
+
$(info )
|
239 |
+
|
240 |
+
#
|
241 |
+
# Build library
|
242 |
+
#
|
243 |
+
|
244 |
+
ggml.o: ggml.c ggml.h ggml-cuda.h k_quants.h
|
245 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) -c $< -o $@
|
246 |
+
ggml_openblas.o: ggml.c ggml.h
|
247 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) $(OPENBLAS_FLAGS) -c $< -o $@
|
248 |
+
ggml_failsafe.o: ggml.c ggml.h
|
249 |
+
$(CC) $(CFLAGS) $(NONECFLAGS) -c $< -o $@
|
250 |
+
ggml_openblas_noavx2.o: ggml.c ggml.h
|
251 |
+
$(CC) $(CFLAGS) $(SIMPLECFLAGS) $(OPENBLAS_FLAGS) -c $< -o $@
|
252 |
+
ggml_clblast.o: ggml.c ggml.h
|
253 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) $(CLBLAST_FLAGS) -c $< -o $@
|
254 |
+
ggml_clblast_noavx2.o: ggml.c ggml.h
|
255 |
+
$(CC) $(CFLAGS) $(SIMPLECFLAGS) $(CLBLAST_FLAGS) -c $< -o $@
|
256 |
+
|
257 |
+
#quants K
|
258 |
+
k_quants.o: k_quants.c k_quants.h ggml.h ggml-cuda.h
|
259 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) -c $< -o $@
|
260 |
+
k_quants_noavx2.o: k_quants.c k_quants.h ggml.h ggml-cuda.h
|
261 |
+
$(CC) $(CFLAGS) $(SIMPLECFLAGS) -c $< -o $@
|
262 |
+
k_quants_failsafe.o: k_quants.c k_quants.h ggml.h ggml-cuda.h
|
263 |
+
$(CC) $(CFLAGS) $(NONECFLAGS) -c $< -o $@
|
264 |
+
|
265 |
+
#version 2 libs
|
266 |
+
ggml_v2.o: otherarch/ggml_v2.c otherarch/ggml_v2.h
|
267 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) -c $< -o $@
|
268 |
+
ggml_v2_openblas.o: otherarch/ggml_v2.c otherarch/ggml_v2.h
|
269 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) $(OPENBLAS_FLAGS) -c $< -o $@
|
270 |
+
ggml_v2_failsafe.o: otherarch/ggml_v2.c otherarch/ggml_v2.h
|
271 |
+
$(CC) $(CFLAGS) $(NONECFLAGS) -c $< -o $@
|
272 |
+
ggml_v2_openblas_noavx2.o: otherarch/ggml_v2.c otherarch/ggml_v2.h
|
273 |
+
$(CC) $(CFLAGS) $(SIMPLECFLAGS) $(OPENBLAS_FLAGS) -c $< -o $@
|
274 |
+
ggml_v2_clblast.o: otherarch/ggml_v2.c otherarch/ggml_v2.h
|
275 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) $(CLBLAST_FLAGS) -c $< -o $@
|
276 |
+
ggml_v2_clblast_noavx2.o: otherarch/ggml_v2.c otherarch/ggml_v2.h
|
277 |
+
$(CC) $(CFLAGS) $(SIMPLECFLAGS) $(CLBLAST_FLAGS) -c $< -o $@
|
278 |
+
|
279 |
+
#extreme old version compat
|
280 |
+
ggml_v1.o: otherarch/ggml_v1.c otherarch/ggml_v1.h
|
281 |
+
$(CC) $(CFLAGS) $(FULLCFLAGS) -c $< -o $@
|
282 |
+
ggml_v1_failsafe.o: otherarch/ggml_v1.c otherarch/ggml_v1.h
|
283 |
+
$(CC) $(CFLAGS) $(NONECFLAGS) -c $< -o $@
|
284 |
+
|
285 |
+
#opencl
|
286 |
+
ggml-opencl.o: ggml-opencl.cpp ggml-opencl.h
|
287 |
+
$(CXX) $(CXXFLAGS) $(CLBLAST_FLAGS) -c $< -o $@
|
288 |
+
ggml_v2-opencl.o: otherarch/ggml_v2-opencl.cpp otherarch/ggml_v2-opencl.h
|
289 |
+
$(CXX) $(CXXFLAGS) $(CLBLAST_FLAGS) -c $< -o $@
|
290 |
+
ggml_v2-opencl-legacy.o: otherarch/ggml_v2-opencl-legacy.c otherarch/ggml_v2-opencl-legacy.h
|
291 |
+
$(CC) $(CFLAGS) -c $< -o $@
|
292 |
+
|
293 |
+
# intermediate objects
|
294 |
+
llama.o: llama.cpp ggml.h ggml-cuda.h llama.h llama-util.h
|
295 |
+
$(CXX) $(CXXFLAGS) -c $< -o $@
|
296 |
+
common.o: examples/common.cpp examples/common.h
|
297 |
+
$(CXX) $(CXXFLAGS) -c $< -o $@
|
298 |
+
expose.o: expose.cpp expose.h
|
299 |
+
$(CXX) $(CXXFLAGS) -c $< -o $@
|
300 |
+
gpttype_adapter_failsafe.o: gpttype_adapter.cpp
|
301 |
+
$(CXX) $(CXXFLAGS) $(FAILSAFE_FLAGS) -c $< -o $@
|
302 |
+
gpttype_adapter.o: gpttype_adapter.cpp
|
303 |
+
$(CXX) $(CXXFLAGS) -c $< -o $@
|
304 |
+
gpttype_adapter_clblast.o: gpttype_adapter.cpp
|
305 |
+
$(CXX) $(CXXFLAGS) $(CLBLAST_FLAGS) -c $< -o $@
|
306 |
+
|
307 |
+
clean:
|
308 |
+
rm -vf *.o main quantize_llama quantize_gpt2 quantize_gptj quantize_neox quantize_mpt quantize-stats perplexity embedding benchmark-matmult save-load-state main.exe quantize_llama.exe quantize_gptj.exe quantize_gpt2.exe quantize_neox.exe quantize_mpt.exe koboldcpp.dll koboldcpp_openblas.dll koboldcpp_failsafe.dll koboldcpp_openblas_noavx2.dll koboldcpp_clblast.dll koboldcpp_clblast_noavx2.dll koboldcpp.so koboldcpp_openblas.so koboldcpp_failsafe.so koboldcpp_openblas_noavx2.so koboldcpp_clblast.so koboldcpp_clblast_noavx2.so
|
309 |
+
|
310 |
+
main: examples/main/main.cpp build-info.h ggml.o k_quants.o llama.o common.o $(OBJS)
|
311 |
+
$(CXX) $(CXXFLAGS) $(filter-out %.h,$^) -o $@ $(LDFLAGS)
|
312 |
+
@echo
|
313 |
+
@echo '==== Run ./main -h for help. ===='
|
314 |
+
@echo
|
315 |
+
|
316 |
+
#generated libraries
|
317 |
+
koboldcpp: ggml.o ggml_v2.o ggml_v1.o expose.o common.o gpttype_adapter.o k_quants.o $(OBJS)
|
318 |
+
$(DEFAULT_BUILD)
|
319 |
+
koboldcpp_openblas: ggml_openblas.o ggml_v2_openblas.o ggml_v1.o expose.o common.o gpttype_adapter.o k_quants.o $(OBJS)
|
320 |
+
$(OPENBLAS_BUILD)
|
321 |
+
koboldcpp_failsafe: ggml_failsafe.o ggml_v2_failsafe.o ggml_v1_failsafe.o expose.o common.o gpttype_adapter_failsafe.o k_quants_failsafe.o $(OBJS)
|
322 |
+
$(FAILSAFE_BUILD)
|
323 |
+
koboldcpp_openblas_noavx2: ggml_openblas_noavx2.o ggml_v2_openblas_noavx2.o ggml_v1_failsafe.o expose.o common.o gpttype_adapter.o k_quants_noavx2.o $(OBJS)
|
324 |
+
$(OPENBLAS_NOAVX2_BUILD)
|
325 |
+
koboldcpp_clblast: ggml_clblast.o ggml_v2_clblast.o ggml_v1.o expose.o common.o gpttype_adapter_clblast.o ggml-opencl.o ggml_v2-opencl.o ggml_v2-opencl-legacy.o k_quants.o $(OBJS)
|
326 |
+
$(CLBLAST_BUILD)
|
327 |
+
koboldcpp_clblast_noavx2: ggml_clblast_noavx2.o ggml_v2_clblast_noavx2.o ggml_v1_failsafe.o expose.o common.o gpttype_adapter_clblast.o ggml-opencl.o ggml_v2-opencl.o ggml_v2-opencl-legacy.o k_quants_noavx2.o $(OBJS)
|
328 |
+
$(CLBLAST_NOAVX2_BUILD)
|
329 |
+
|
330 |
+
quantize_llama: examples/quantize/quantize.cpp ggml.o llama.o k_quants.o
|
331 |
+
$(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
|
332 |
+
quantize_gptj: ggml.o llama.o k_quants.o otherarch/tools/gptj_quantize.cpp otherarch/tools/common-ggml.cpp
|
333 |
+
$(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
|
334 |
+
quantize_gpt2: ggml.o llama.o k_quants.o otherarch/tools/gpt2_quantize.cpp otherarch/tools/common-ggml.cpp
|
335 |
+
$(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
|
336 |
+
quantize_neox: ggml.o llama.o k_quants.o otherarch/tools/neox_quantize.cpp otherarch/tools/common-ggml.cpp
|
337 |
+
$(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
|
338 |
+
quantize_mpt: ggml.o llama.o k_quants.o otherarch/tools/mpt_quantize.cpp otherarch/tools/common-ggml.cpp
|
339 |
+
$(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
|
340 |
+
|
341 |
+
|
342 |
+
build-info.h:
|
343 |
+
$(DONOTHING)
|
Package.swift
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// swift-tools-version:5.3
|
2 |
+
|
3 |
+
import PackageDescription
|
4 |
+
|
5 |
+
let package = Package(
|
6 |
+
name: "llama",
|
7 |
+
products: [
|
8 |
+
.library(name: "llama", targets: ["llama"]),
|
9 |
+
],
|
10 |
+
targets: [
|
11 |
+
.target(
|
12 |
+
name: "llama",
|
13 |
+
path: ".",
|
14 |
+
sources: ["ggml.c", "llama.cpp"],
|
15 |
+
publicHeadersPath: "spm-headers",
|
16 |
+
cSettings: [.unsafeFlags(["-Wno-shorten-64-to-32"]), .define("GGML_USE_ACCELERATE")],
|
17 |
+
linkerSettings: [
|
18 |
+
.linkedFramework("Accelerate")
|
19 |
+
]
|
20 |
+
),
|
21 |
+
],
|
22 |
+
cxxLanguageStandard: .cxx11
|
23 |
+
)
|
README.md
CHANGED
@@ -1,10 +1,70 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# koboldcpp
|
2 |
+
|
3 |
+
A self contained distributable from Concedo that exposes llama.cpp function bindings, allowing it to be used via a simulated Kobold API endpoint.
|
4 |
+
|
5 |
+
What does it mean? You get llama.cpp with a fancy UI, persistent stories, editing tools, save formats, memory, world info, author's note, characters, scenarios and everything Kobold and Kobold Lite have to offer. In a tiny package around 20 MB in size, excluding model weights.
|
6 |
+
|
7 |
+
![Preview](media/preview.png)
|
8 |
+
|
9 |
+
## Usage
|
10 |
+
- [Download the latest release here](https://github.com/LostRuins/koboldcpp/releases/latest) or clone the repo.
|
11 |
+
- Windows binaries are provided in the form of **koboldcpp.exe**, which is a pyinstaller wrapper for a few **.dll** files and **koboldcpp.py**. If you feel concerned, you may prefer to rebuild it yourself with the provided makefiles and scripts.
|
12 |
+
- Weights are not included, you can use the official llama.cpp `quantize.exe` to generate them from your official weight files (or download them from other places).
|
13 |
+
- To run, execute **koboldcpp.exe** or drag and drop your quantized `ggml_model.bin` file onto the .exe, and then connect with Kobold or Kobold Lite. If you're not on windows, then run the script **KoboldCpp.py** after compiling the libraries.
|
14 |
+
- By default, you can connect to http://localhost:5001
|
15 |
+
- You can also run it using the command line `koboldcpp.exe [ggml_model.bin] [port]`. For info, please check `koboldcpp.exe --help`
|
16 |
+
- If you are having crashes or issues, you can try turning off BLAS with the `--noblas` flag. You can also try running in a non-avx2 compatibility mode with `--noavx2`. Lastly, you can try turning off mmap with `--nommap`.
|
17 |
+
- Big context still too slow? Try the `--smartcontext` flag to reduce prompt processing frequency. Also, you can try to run with your GPU using CLBlast, with `--useclblast` flag for a speedup
|
18 |
+
- Want even more speedup? Combine `--useclblast` with `--gpulayers` to offload entire layers to the GPU! **Much faster, but uses more VRAM**. Experiment to determine number of layers to offload.
|
19 |
+
|
20 |
+
For more information, be sure to run the program with the `--help` flag.
|
21 |
+
|
22 |
+
## Compiling on Windows
|
23 |
+
- If you want to compile your binaries from source at Windows, the easiest way is:
|
24 |
+
- Use the latest release of w64devkit (https://github.com/skeeto/w64devkit). Be sure to use the "vanilla one", not i686 or other different stuff. If you try they will conflit with the precompiled libs!
|
25 |
+
- Make sure you are using the w64devkit integrated terminal, then run 'make' at the KoboldCpp source folder. This will create the .dll files.
|
26 |
+
- If you want to generate the .exe file, make sure you have the python module PyInstaller installed with pip ('pip install PyInstaller').
|
27 |
+
- Run the script make_pyinstaller.bat at a regular terminal (or Windows Explorer).
|
28 |
+
- The koboldcpp.exe file will be at your dist folder.
|
29 |
+
- If you wish to use your own version of the additional Windows libraries (OpenCL, CLBlast and OpenBLAS), you can do it with:
|
30 |
+
- OpenCL - tested with https://github.com/KhronosGroup/OpenCL-SDK . If you wish to compile it, follow the repository instructions. You will need vcpkg.
|
31 |
+
- CLBlast - tested with https://github.com/CNugteren/CLBlast . If you wish to compile it you will need to reference the OpenCL files. It will only generate the ".lib" file if you compile using MSVC.
|
32 |
+
- OpenBLAS - tested with https://github.com/xianyi/OpenBLAS .
|
33 |
+
- Move the respectives .lib files to the /lib folder of your project, overwriting the older files.
|
34 |
+
- Also, replace the existing versions of the corresponding .dll files located in the project directory root (e.g. libopenblas.dll).
|
35 |
+
- Make the KoboldCPP project using the instructions above.
|
36 |
+
|
37 |
+
## OSX and Linux
|
38 |
+
- You will have to compile your binaries from source. A makefile is provided, simply run `make`
|
39 |
+
- If you want you can also link your own install of OpenBLAS manually with `make LLAMA_OPENBLAS=1`
|
40 |
+
- Alternatively, if you want you can also link your own install of CLBlast manually with `make LLAMA_CLBLAST=1`, for this you will need to obtain and link OpenCL and CLBlast libraries.
|
41 |
+
- For a full featured build, do `make LLAMA_OPENBLAS=1 LLAMA_CLBLAST=1`
|
42 |
+
- For Arch Linux: Install `cblas` `openblas` and `clblast`.
|
43 |
+
- For Debian: Install `libclblast-dev` and `libopenblas-dev`.
|
44 |
+
- After all binaries are built, you can run the python script with the command `koboldcpp.py [ggml_model.bin] [port]`
|
45 |
+
- Note: Many OSX users have found that the using Accelerate is actually faster than OpenBLAS. To try, you may wish to run with `--noblas` and compare speeds.
|
46 |
+
|
47 |
+
## Considerations
|
48 |
+
- ZERO or MINIMAL changes as possible to parent repo files - do not move their function declarations elsewhere! We want to be able to update the repo and pull any changes automatically.
|
49 |
+
- No dynamic memory allocation! Setup structs with FIXED (known) shapes and sizes for ALL output fields. Python will ALWAYS provide the memory, we just write to it.
|
50 |
+
- For Windows: No installation, single file executable, (It Just Works)
|
51 |
+
- Since v1.0.6, requires libopenblas, the prebuilt windows binaries are included in this repo. If not found, it will fall back to a mode without BLAS.
|
52 |
+
- Since v1.15, requires CLBlast if enabled, the prebuilt windows binaries are included in this repo. If not found, it will fall back to a mode without CLBlast.
|
53 |
+
- **I plan to keep backwards compatibility with ALL past llama.cpp AND alpaca.cpp models**. But you are also encouraged to reconvert/update your models if possible for best results.
|
54 |
+
|
55 |
+
## License
|
56 |
+
- The original GGML library and llama.cpp by ggerganov are licensed under the MIT License
|
57 |
+
- However, Kobold Lite is licensed under the AGPL v3.0 License
|
58 |
+
- The other files are also under the AGPL v3.0 License unless otherwise stated
|
59 |
+
|
60 |
+
## Notes
|
61 |
+
- Generation delay scales linearly with original prompt length. If OpenBLAS is enabled then prompt ingestion becomes about 2-3x faster. This is automatic on windows, but will require linking on OSX and Linux. CLBlast speeds this up even further, and `--gpulayers` + `--useclblast` more so.
|
62 |
+
- I have heard of someone claiming a false AV positive report. The exe is a simple pyinstaller bundle that includes the necessary python scripts and dlls to run. If this still concerns you, you might wish to rebuild everything from source code using the makefile, and you can rebuild the exe yourself with pyinstaller by using `make_pyinstaller.bat`
|
63 |
+
- Supported GGML models:
|
64 |
+
- LLAMA (All versions including ggml, ggmf, ggjt v1,v2,v3, openllama, gpt4all). Supports CLBlast and OpenBLAS acceleration for all versions.
|
65 |
+
- GPT-2 (All versions, including legacy f16, newer format + quanitzed, cerebras, starcoder) Supports CLBlast and OpenBLAS acceleration for newer formats, no GPU layer offload.
|
66 |
+
- GPT-J (All versions including legacy f16, newer format + quantized, pyg.cpp, new pygmalion, janeway etc.) Supports CLBlast and OpenBLAS acceleration for newer formats, no GPU layer offload.
|
67 |
+
- RWKV (all formats except Q4_1_O).
|
68 |
+
- GPT-NeoX / Pythia / StableLM / Dolly / RedPajama
|
69 |
+
- MPT models (ggjt v3)
|
70 |
+
- Basically every single current and historical GGML format that has ever existed should be supported, except for bloomz.cpp due to lack of demand.
|
build-info.h
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef BUILD_INFO_H
|
2 |
+
#define BUILD_INFO_H
|
3 |
+
|
4 |
+
#define BUILD_NUMBER 999
|
5 |
+
#define BUILD_COMMIT "KOBOLDCPP"
|
6 |
+
|
7 |
+
#endif // BUILD_INFO_H
|
clblast.dll
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0611442b931691d9b3c9bc5ebe7625f17a5c5902e1a2b9e98cbad440d1459625
|
3 |
+
size 5450752
|
convert-lora-to-ggml.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import struct
|
5 |
+
import sys
|
6 |
+
from typing import Any, Dict, Sequence, TextIO
|
7 |
+
|
8 |
+
import torch
|
9 |
+
|
10 |
+
from convert import DATA_TYPE_TO_FTYPE, NUMPY_TYPE_TO_DATA_TYPE, DataType
|
11 |
+
|
12 |
+
HF_SUBLAYER_TO_GGML = {
|
13 |
+
"self_attn.q_proj": "attention.wq",
|
14 |
+
"self_attn.k_proj": "attention.wk",
|
15 |
+
"self_attn.v_proj": "attention.wv",
|
16 |
+
"self_attn.o_proj": "attention.wo",
|
17 |
+
"mlp.gate_proj": "feed_forward.w1",
|
18 |
+
"mlp.down_proj": "feed_forward.w2",
|
19 |
+
"mlp.up_proj": "feed_forward.w3",
|
20 |
+
"input_layernorm": "attention_norm",
|
21 |
+
"post_attention_layernorm": "ffn_norm",
|
22 |
+
# "norm": "norm",
|
23 |
+
# "embed_tokens": "tok_embeddings",
|
24 |
+
# "lm_head": "output",
|
25 |
+
}
|
26 |
+
|
27 |
+
|
28 |
+
def translate_tensor_name(t: str) -> str:
|
29 |
+
match = re.match(r".*layers\.(\d+)\.(\w+\.\w+)\.lora_(A|B)\.weight", t)
|
30 |
+
if match:
|
31 |
+
nn = match.group(1)
|
32 |
+
sub_layer = match.group(2)
|
33 |
+
lora_type = match.group(3)
|
34 |
+
|
35 |
+
sub_layer_renamed = HF_SUBLAYER_TO_GGML.get(sub_layer)
|
36 |
+
if sub_layer_renamed is None:
|
37 |
+
print(f"Error: unrecognized sub-layer {sub_layer} in tensor {t}")
|
38 |
+
sys.exit(1)
|
39 |
+
|
40 |
+
output_string = (
|
41 |
+
f"layers.{nn}.{HF_SUBLAYER_TO_GGML[sub_layer]}.weight.lora{lora_type}"
|
42 |
+
)
|
43 |
+
return output_string
|
44 |
+
else:
|
45 |
+
print(f"Error: unrecognized tensor {t}")
|
46 |
+
sys.exit(1)
|
47 |
+
|
48 |
+
|
49 |
+
def write_file_header(fout: TextIO, params: Dict[str, Any]) -> None:
|
50 |
+
fout.write(b"ggla"[::-1]) # magic (ggml lora)
|
51 |
+
fout.write(struct.pack("i", 1)) # file version
|
52 |
+
fout.write(struct.pack("i", params["r"]))
|
53 |
+
# https://opendelta.readthedocs.io/en/latest/modules/deltas.html says that `lora_alpha` is an int
|
54 |
+
# but some models ship a float value instead
|
55 |
+
# let's convert to int, but fail if lossless conversion is not possible
|
56 |
+
assert int(params["lora_alpha"]) == params["lora_alpha"], "cannot convert float to int losslessly"
|
57 |
+
fout.write(struct.pack("i", int(params["lora_alpha"])))
|
58 |
+
|
59 |
+
|
60 |
+
def write_tensor_header(
|
61 |
+
self, name: str, shape: Sequence[int], data_type: DataType
|
62 |
+
) -> None:
|
63 |
+
sname = name.encode("utf-8")
|
64 |
+
fout.write(
|
65 |
+
struct.pack(
|
66 |
+
"iii",
|
67 |
+
len(shape),
|
68 |
+
len(sname),
|
69 |
+
DATA_TYPE_TO_FTYPE[NUMPY_TYPE_TO_DATA_TYPE[data_type]],
|
70 |
+
)
|
71 |
+
)
|
72 |
+
fout.write(struct.pack("i" * len(shape), *shape[::-1]))
|
73 |
+
fout.write(sname)
|
74 |
+
fout.seek((fout.tell() + 31) & -32)
|
75 |
+
|
76 |
+
|
77 |
+
if len(sys.argv) != 2:
|
78 |
+
print(f"Usage: python {sys.argv[0]} <path>")
|
79 |
+
print(
|
80 |
+
"Path must contain HuggingFace PEFT LoRA files 'adapter_config.json' and 'adapter_model.bin'"
|
81 |
+
)
|
82 |
+
sys.exit(1)
|
83 |
+
|
84 |
+
input_json = os.path.join(sys.argv[1], "adapter_config.json")
|
85 |
+
input_model = os.path.join(sys.argv[1], "adapter_model.bin")
|
86 |
+
output_path = os.path.join(sys.argv[1], "ggml-adapter-model.bin")
|
87 |
+
|
88 |
+
model = torch.load(input_model, map_location="cpu")
|
89 |
+
|
90 |
+
with open(input_json, "r") as f:
|
91 |
+
params = json.load(f)
|
92 |
+
|
93 |
+
if params["peft_type"] != "LORA":
|
94 |
+
print(f"Error: unsupported adapter type {params['peft_type']}, expected LORA")
|
95 |
+
sys.exit(1)
|
96 |
+
|
97 |
+
if params["fan_in_fan_out"] is True:
|
98 |
+
print("Error: param fan_in_fan_out is not supported")
|
99 |
+
sys.exit(1)
|
100 |
+
|
101 |
+
if params["bias"] is not None and params["bias"] != "none":
|
102 |
+
print("Error: param bias is not supported")
|
103 |
+
sys.exit(1)
|
104 |
+
|
105 |
+
# TODO: these seem to be layers that have been trained but without lora.
|
106 |
+
# doesn't seem widely used but eventually should be supported
|
107 |
+
if params["modules_to_save"] is not None and len(params["modules_to_save"]) > 0:
|
108 |
+
print("Error: param modules_to_save is not supported")
|
109 |
+
sys.exit(1)
|
110 |
+
|
111 |
+
with open(output_path, "wb") as fout:
|
112 |
+
fout.truncate()
|
113 |
+
|
114 |
+
write_file_header(fout, params)
|
115 |
+
for k, v in model.items():
|
116 |
+
if k.endswith("lora_A.weight"):
|
117 |
+
if v.dtype != torch.float16 and v.dtype != torch.float32:
|
118 |
+
v = v.float()
|
119 |
+
v = v.T
|
120 |
+
else:
|
121 |
+
v = v.float()
|
122 |
+
|
123 |
+
t = v.numpy()
|
124 |
+
tname = translate_tensor_name(k)
|
125 |
+
print(f"{k} => {tname} {t.shape} {t.dtype} {t.nbytes/1024/1024:.2f}MB")
|
126 |
+
write_tensor_header(fout, tname, t.shape, t.dtype)
|
127 |
+
t.tofile(fout)
|
128 |
+
|
129 |
+
print(f"Converted {input_json} and {input_model} to {output_path}")
|
convert-pth-to-ggml.py
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Compatibility stub
|
2 |
+
|
3 |
+
import argparse
|
4 |
+
|
5 |
+
import convert
|
6 |
+
|
7 |
+
parser = argparse.ArgumentParser(
|
8 |
+
description="""[DEPRECATED - use `convert.py` instead]
|
9 |
+
Convert a LLaMA model checkpoint to a ggml compatible file""")
|
10 |
+
parser.add_argument('dir_model', help='directory containing the model checkpoint')
|
11 |
+
parser.add_argument('ftype', help='file type (0: float32, 1: float16)', type=int, choices=[0, 1], default=1)
|
12 |
+
args = parser.parse_args()
|
13 |
+
convert.main(['--outtype', 'f16' if args.ftype == 1 else 'f32', '--', args.dir_model])
|
convert.py
ADDED
@@ -0,0 +1,1168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import concurrent.futures
|
3 |
+
import copy
|
4 |
+
import enum
|
5 |
+
import faulthandler
|
6 |
+
import functools
|
7 |
+
import io
|
8 |
+
import itertools
|
9 |
+
import json
|
10 |
+
import math
|
11 |
+
import mmap
|
12 |
+
import pickle
|
13 |
+
import re
|
14 |
+
import signal
|
15 |
+
import struct
|
16 |
+
import sys
|
17 |
+
import zipfile
|
18 |
+
from abc import ABCMeta, abstractmethod
|
19 |
+
from dataclasses import dataclass
|
20 |
+
from pathlib import Path
|
21 |
+
from typing import (IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List,
|
22 |
+
Literal, Optional, Sequence, Tuple, TypeVar, Union)
|
23 |
+
|
24 |
+
import numpy as np
|
25 |
+
from sentencepiece import SentencePieceProcessor # type: ignore
|
26 |
+
|
27 |
+
if TYPE_CHECKING:
|
28 |
+
from typing_extensions import TypeAlias
|
29 |
+
|
30 |
+
if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
|
31 |
+
faulthandler.register(signal.SIGUSR1)
|
32 |
+
|
33 |
+
NDArray: 'TypeAlias' = 'np.ndarray[Any, Any]'
|
34 |
+
|
35 |
+
|
36 |
+
@dataclass(frozen=True)
|
37 |
+
class UnquantizedDataType:
|
38 |
+
name: str
|
39 |
+
|
40 |
+
|
41 |
+
DT_F16 = UnquantizedDataType('F16')
|
42 |
+
DT_F32 = UnquantizedDataType('F32')
|
43 |
+
DT_I32 = UnquantizedDataType('I32')
|
44 |
+
DT_BF16 = UnquantizedDataType('BF16')
|
45 |
+
|
46 |
+
|
47 |
+
@dataclass(frozen=True)
|
48 |
+
class QuantizedDataType:
|
49 |
+
groupsize: int
|
50 |
+
have_addends: bool
|
51 |
+
have_g_idx: bool
|
52 |
+
|
53 |
+
|
54 |
+
DT_Q4_0 = QuantizedDataType(groupsize=32, have_addends=False, have_g_idx=False)
|
55 |
+
DT_Q4_1 = QuantizedDataType(groupsize=32, have_addends=True, have_g_idx=False)
|
56 |
+
|
57 |
+
DataType = Union[UnquantizedDataType, QuantizedDataType]
|
58 |
+
|
59 |
+
DATA_TYPE_TO_FTYPE: Dict[DataType, int] = {
|
60 |
+
DT_F32: 0,
|
61 |
+
DT_F16: 1,
|
62 |
+
DT_Q4_0: 2,
|
63 |
+
DT_Q4_1: 3,
|
64 |
+
}
|
65 |
+
|
66 |
+
FTYPE_TO_DATA_TYPE: Dict[int, DataType] = \
|
67 |
+
{ftype: dtype for (dtype, ftype) in DATA_TYPE_TO_FTYPE.items()}
|
68 |
+
|
69 |
+
DATA_TYPE_TO_NUMPY: Dict[DataType, 'np.dtype[Any]'] = {
|
70 |
+
DT_BF16: np.dtype(np.uint16),
|
71 |
+
DT_F16: np.dtype(np.float16),
|
72 |
+
DT_F32: np.dtype(np.float32),
|
73 |
+
DT_I32: np.dtype(np.int32),
|
74 |
+
}
|
75 |
+
|
76 |
+
NUMPY_TYPE_TO_DATA_TYPE: Dict['np.dtype[Any]', DataType] = \
|
77 |
+
{dtype: data_type for (data_type, dtype) in DATA_TYPE_TO_NUMPY.items()}
|
78 |
+
|
79 |
+
|
80 |
+
class GGMLFileType(enum.Enum):
|
81 |
+
AllF32 = 0
|
82 |
+
MostlyF16 = 1 # except 1d tensors
|
83 |
+
MostlyQ4_0 = 2 # except 1d tensors
|
84 |
+
MostlyQ4_1 = 3 # except 1d tensors
|
85 |
+
PerLayerIsQ4_1 = 4 # but tok_embeddings.weight and output.weight are F16
|
86 |
+
|
87 |
+
def type_for_tensor(self, name: str, tensor: 'LazyTensor') -> DataType:
|
88 |
+
if len(tensor.shape) == 1:
|
89 |
+
# 1D tensors are always F32.
|
90 |
+
return DT_F32
|
91 |
+
elif self == GGMLFileType.AllF32:
|
92 |
+
return DT_F32
|
93 |
+
elif self == GGMLFileType.MostlyF16:
|
94 |
+
return DT_F16
|
95 |
+
elif self == GGMLFileType.MostlyQ4_0:
|
96 |
+
return DT_Q4_0
|
97 |
+
elif self == GGMLFileType.MostlyQ4_1:
|
98 |
+
return DT_Q4_1
|
99 |
+
elif self == GGMLFileType.PerLayerIsQ4_1:
|
100 |
+
if name in ('output.weight', 'tok_embeddings.weight'):
|
101 |
+
return DT_F16
|
102 |
+
else:
|
103 |
+
return DT_Q4_1
|
104 |
+
else:
|
105 |
+
raise ValueError(self)
|
106 |
+
|
107 |
+
|
108 |
+
def make_tensors_list() -> List[str]:
|
109 |
+
ret = [
|
110 |
+
'tok_embeddings.weight',
|
111 |
+
'norm.weight',
|
112 |
+
'output.weight',
|
113 |
+
]
|
114 |
+
for i in range(80): # maximum number of layer
|
115 |
+
ret += [
|
116 |
+
f'layers.{i}.attention.wq.weight',
|
117 |
+
f'layers.{i}.attention.wk.weight',
|
118 |
+
f'layers.{i}.attention.wv.weight',
|
119 |
+
f'layers.{i}.attention.wo.weight',
|
120 |
+
f'layers.{i}.attention_norm.weight',
|
121 |
+
f'layers.{i}.feed_forward.w1.weight',
|
122 |
+
f'layers.{i}.feed_forward.w2.weight',
|
123 |
+
f'layers.{i}.feed_forward.w3.weight',
|
124 |
+
f'layers.{i}.ffn_norm.weight',
|
125 |
+
]
|
126 |
+
return ret
|
127 |
+
|
128 |
+
|
129 |
+
TENSORS_LIST = make_tensors_list()
|
130 |
+
TENSORS_SET = set(TENSORS_LIST)
|
131 |
+
|
132 |
+
|
133 |
+
@dataclass
|
134 |
+
class Params:
|
135 |
+
n_vocab: int
|
136 |
+
n_embd: int
|
137 |
+
n_mult: int
|
138 |
+
n_head: int
|
139 |
+
n_layer: int
|
140 |
+
file_type: GGMLFileType
|
141 |
+
|
142 |
+
@staticmethod
|
143 |
+
def guessed(model: 'LazyModel', file_type: GGMLFileType) -> 'Params':
|
144 |
+
n_vocab, n_embd = model["tok_embeddings.weight"].shape
|
145 |
+
|
146 |
+
return Params(
|
147 |
+
n_vocab=n_vocab,
|
148 |
+
n_embd=n_embd,
|
149 |
+
n_mult=256,
|
150 |
+
n_head=n_embd // 128,
|
151 |
+
n_layer=next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model),
|
152 |
+
file_type=file_type,
|
153 |
+
)
|
154 |
+
|
155 |
+
|
156 |
+
class SentencePieceVocab:
|
157 |
+
def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
|
158 |
+
self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
|
159 |
+
added_tokens: Dict[str, int]
|
160 |
+
if fname_added_tokens is not None:
|
161 |
+
added_tokens = json.load(open(fname_added_tokens))
|
162 |
+
else:
|
163 |
+
added_tokens = {}
|
164 |
+
vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
|
165 |
+
expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
|
166 |
+
actual_ids = sorted(added_tokens.values())
|
167 |
+
if expected_ids != actual_ids:
|
168 |
+
raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
|
169 |
+
items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
|
170 |
+
self.added_tokens_list = [text for (text, idx) in items]
|
171 |
+
self.vocab_size_base: int = vocab_size
|
172 |
+
self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
|
173 |
+
self.fname_tokenizer = fname_tokenizer
|
174 |
+
self.fname_added_tokens = fname_added_tokens
|
175 |
+
|
176 |
+
def sentencepiece_tokens(self) -> Iterable[Tuple[bytes, float]]:
|
177 |
+
tokenizer = self.sentencepiece_tokenizer
|
178 |
+
for i in range(tokenizer.vocab_size()):
|
179 |
+
text: bytes
|
180 |
+
if tokenizer.is_unknown(i):
|
181 |
+
text = " \u2047 ".encode("utf-8")
|
182 |
+
elif tokenizer.is_control(i):
|
183 |
+
text = b""
|
184 |
+
elif tokenizer.is_byte(i):
|
185 |
+
piece = tokenizer.id_to_piece(i)
|
186 |
+
if len(piece) != 6:
|
187 |
+
raise Exception(f"Invalid token: {piece}")
|
188 |
+
byte_value = int(piece[3:-1], 16)
|
189 |
+
text = struct.pack("B", byte_value)
|
190 |
+
else:
|
191 |
+
text = tokenizer.id_to_piece(i).replace("\u2581", " ").encode("utf-8")
|
192 |
+
score: float = tokenizer.get_score(i)
|
193 |
+
yield text, score
|
194 |
+
|
195 |
+
def added_tokens(self) -> Iterable[Tuple[bytes, float]]:
|
196 |
+
for text in self.added_tokens_list:
|
197 |
+
score = -1000.0
|
198 |
+
yield text.encode("utf-8"), score
|
199 |
+
|
200 |
+
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
|
201 |
+
yield from self.sentencepiece_tokens()
|
202 |
+
yield from self.added_tokens()
|
203 |
+
|
204 |
+
def __repr__(self) -> str:
|
205 |
+
return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
|
206 |
+
|
207 |
+
|
208 |
+
class GGMLVocab:
|
209 |
+
def __init__(self, tokens: List[Tuple[bytes, float]]):
|
210 |
+
self.tokens = tokens
|
211 |
+
self.vocab_size = len(tokens)
|
212 |
+
|
213 |
+
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
|
214 |
+
return self.tokens
|
215 |
+
|
216 |
+
def __repr__(self) -> str:
|
217 |
+
return f"<GGMLVocab with {self.vocab_size} tokens>"
|
218 |
+
|
219 |
+
|
220 |
+
Vocab = Union[SentencePieceVocab, GGMLVocab]
|
221 |
+
|
222 |
+
|
223 |
+
def permute(weights: NDArray, n_head: int) -> NDArray:
|
224 |
+
return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
|
225 |
+
.swapaxes(1, 2)
|
226 |
+
.reshape(weights.shape))
|
227 |
+
|
228 |
+
|
229 |
+
def dequantize_q4(qvalues_pack32: NDArray, scales: NDArray, addends: Optional[NDArray], g_idx: Optional[NDArray]) -> NDArray:
|
230 |
+
# First reinterpret each row from a list of int32s containing 8 values each
|
231 |
+
# to a list of uint8s containing 2 values each.
|
232 |
+
qvalues_pack8 = qvalues_pack32.view(np.uint8)
|
233 |
+
|
234 |
+
# Then split out the two values per int8 (which requires an actual
|
235 |
+
# conversion because numpy doesn't natively support int4s).
|
236 |
+
qvalues = np.zeros([qvalues_pack8.shape[0], qvalues_pack8.shape[1] * 2], dtype=np.uint8)
|
237 |
+
qvalues[:, 0::2] = qvalues_pack8 & 0xf
|
238 |
+
qvalues[:, 1::2] = qvalues_pack8 >> 4
|
239 |
+
|
240 |
+
assert addends is None or addends.shape == scales.shape
|
241 |
+
assert qvalues.shape[0] == scales.shape[0]
|
242 |
+
assert qvalues.shape[1] % scales.shape[1] == 0
|
243 |
+
if g_idx is None:
|
244 |
+
repeat_count = qvalues.shape[1] // scales.shape[1]
|
245 |
+
scales = scales[:, :, np.newaxis]
|
246 |
+
if addends is not None:
|
247 |
+
addends = addends[:, :, np.newaxis]
|
248 |
+
# Reshape so that the below computation broadcasts over scales and addends:
|
249 |
+
qvalues.shape = (qvalues.shape[0], scales.shape[1], int(repeat_count))
|
250 |
+
else:
|
251 |
+
# In this case the scale and addend is selected for each column by g_idx:
|
252 |
+
assert addends is not None
|
253 |
+
scales = scales[:, g_idx]
|
254 |
+
addends = addends[:, g_idx]
|
255 |
+
if addends is None:
|
256 |
+
# Q4_0
|
257 |
+
qvalues = qvalues.view(np.int8)
|
258 |
+
qvalues -= 8
|
259 |
+
# And do the actual 'value = scale * qvalue + addend' computation.
|
260 |
+
values = scales * qvalues
|
261 |
+
if addends is not None:
|
262 |
+
values += addends
|
263 |
+
if g_idx is None:
|
264 |
+
values.shape = (values.shape[0], values.shape[1] * values.shape[2])
|
265 |
+
return values
|
266 |
+
|
267 |
+
|
268 |
+
class Tensor(metaclass=ABCMeta):
|
269 |
+
data_type: DataType
|
270 |
+
|
271 |
+
@abstractmethod
|
272 |
+
def astype(self, data_type: DataType) -> 'Tensor': ...
|
273 |
+
@abstractmethod
|
274 |
+
def permute(self, n_head: int) -> 'Tensor': ...
|
275 |
+
@abstractmethod
|
276 |
+
def to_ggml(self) -> 'GGMLCompatibleTensor': ...
|
277 |
+
|
278 |
+
|
279 |
+
def bf16_to_fp32(bf16_arr: np.ndarray) -> np.ndarray:
|
280 |
+
assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
|
281 |
+
fp32_arr = bf16_arr.astype(np.uint32) << 16
|
282 |
+
return fp32_arr.view(np.float32)
|
283 |
+
|
284 |
+
|
285 |
+
class UnquantizedTensor(Tensor):
|
286 |
+
def __init__(self, ndarray: NDArray) -> None:
|
287 |
+
assert isinstance(ndarray, np.ndarray)
|
288 |
+
self.ndarray = ndarray
|
289 |
+
self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
|
290 |
+
|
291 |
+
def astype(self, data_type: DataType) -> Tensor:
|
292 |
+
dtype = DATA_TYPE_TO_NUMPY[data_type]
|
293 |
+
if self.data_type == DT_BF16:
|
294 |
+
self.ndarray = bf16_to_fp32(self.ndarray)
|
295 |
+
return UnquantizedTensor(self.ndarray.astype(dtype))
|
296 |
+
|
297 |
+
def to_ggml(self) -> 'UnquantizedTensor':
|
298 |
+
return self
|
299 |
+
|
300 |
+
def permute(self, n_head: int) -> 'UnquantizedTensor':
|
301 |
+
return UnquantizedTensor(permute(self.ndarray, n_head))
|
302 |
+
|
303 |
+
|
304 |
+
def load_unquantized(lazy_tensor: 'LazyTensor', expected_dtype: Any = None, convert: bool = False) -> NDArray:
|
305 |
+
tensor = lazy_tensor.load()
|
306 |
+
assert isinstance(tensor, UnquantizedTensor)
|
307 |
+
|
308 |
+
# double-check:
|
309 |
+
actual_shape = list(tensor.ndarray.shape)
|
310 |
+
assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
|
311 |
+
if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
|
312 |
+
if convert:
|
313 |
+
tensor.ndarray = tensor.ndarray.astype(expected_dtype)
|
314 |
+
else:
|
315 |
+
raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
|
316 |
+
|
317 |
+
return tensor.ndarray
|
318 |
+
|
319 |
+
|
320 |
+
class GGMLQuantizedTensor(Tensor):
|
321 |
+
data_type: QuantizedDataType
|
322 |
+
|
323 |
+
def __init__(self, ndarray: NDArray, shape: List[int], data_type: DataType) -> None:
|
324 |
+
rows, columns = shape
|
325 |
+
assert data_type in (DT_Q4_1, DT_Q4_0) # for now
|
326 |
+
assert isinstance(data_type, QuantizedDataType) # redundant, but mypy complains without this
|
327 |
+
assert columns % data_type.groupsize == 0
|
328 |
+
words_in_block = 6 if data_type == DT_Q4_1 else 5
|
329 |
+
self.ndarray = ndarray.view(dtype=np.uint32).reshape((rows, columns // data_type.groupsize, words_in_block))
|
330 |
+
self.shape = shape[:]
|
331 |
+
self.data_type = data_type
|
332 |
+
|
333 |
+
def astype(self, data_type: DataType) -> Tensor:
|
334 |
+
if data_type == self.data_type:
|
335 |
+
return self
|
336 |
+
scales = self.ndarray[:, :, 0].view(np.float32)
|
337 |
+
if self.data_type.have_addends:
|
338 |
+
addends = self.ndarray[:, :, 1].view(np.float32)
|
339 |
+
else:
|
340 |
+
addends = None
|
341 |
+
qweights = self.ndarray[:, :, -4:].reshape([self.shape[0], self.shape[1] // 8])
|
342 |
+
|
343 |
+
dq = dequantize_q4(qweights, scales, addends, g_idx=None)
|
344 |
+
return UnquantizedTensor(dq).astype(data_type)
|
345 |
+
|
346 |
+
def to_ggml(self) -> 'GGMLQuantizedTensor':
|
347 |
+
return self
|
348 |
+
|
349 |
+
def permute(self, n_head: int) -> 'GGMLQuantizedTensor':
|
350 |
+
return GGMLQuantizedTensor(permute(self.ndarray, n_head), self.shape, self.data_type)
|
351 |
+
|
352 |
+
|
353 |
+
GGMLCompatibleTensor = Union[UnquantizedTensor, GGMLQuantizedTensor]
|
354 |
+
|
355 |
+
|
356 |
+
class DeferredPermutedTensor(Tensor):
|
357 |
+
def __init__(self, base: Tensor, n_head: int) -> None:
|
358 |
+
self.base = base
|
359 |
+
self.n_head = n_head
|
360 |
+
self.data_type = self.base.data_type
|
361 |
+
|
362 |
+
def astype(self, data_type: DataType) -> Tensor:
|
363 |
+
return self.base.astype(data_type).permute(self.n_head)
|
364 |
+
|
365 |
+
def to_ggml(self) -> GGMLCompatibleTensor:
|
366 |
+
return self.base.to_ggml().permute(self.n_head)
|
367 |
+
|
368 |
+
def permute(self, n_head: int) -> Tensor:
|
369 |
+
raise Exception("shouldn't permute twice")
|
370 |
+
|
371 |
+
|
372 |
+
class GPTQForLLaMaQuantizedTensor(Tensor):
|
373 |
+
def __init__(self, model: 'LazyModel', namebase: str) -> None:
|
374 |
+
qweight = load_unquantized(model[f"{namebase}.qweight"], np.int32)
|
375 |
+
scales = load_unquantized(model[f"{namebase}.scales"], np.float32, convert=True)
|
376 |
+
|
377 |
+
bias = model.get(f"{namebase}.bias")
|
378 |
+
if bias is not None:
|
379 |
+
# Q4_1 does not support bias; good thing the bias is always all zeros.
|
380 |
+
assert not np.any(load_unquantized(bias))
|
381 |
+
|
382 |
+
if f"{namebase}.zeros" in model:
|
383 |
+
zeros = load_unquantized(model[f"{namebase}.zeros"], np.float32)
|
384 |
+
else:
|
385 |
+
qzeros = load_unquantized(model[f"{namebase}.qzeros"], np.int32)
|
386 |
+
assert qzeros.dtype == np.int32
|
387 |
+
zeros = dequantize_q4(qzeros, scales, scales, g_idx=None)
|
388 |
+
assert zeros.dtype == np.float32
|
389 |
+
|
390 |
+
assert zeros.shape == scales.shape
|
391 |
+
|
392 |
+
# Output is transposed compared to the input, and addends have their sign flipped.
|
393 |
+
# Scales and zeros similarly must be transposed but only for newer
|
394 |
+
# versions of GPTQ-for-LLaMa; the older versions can be identified by
|
395 |
+
# having shape (n_embd, 1).
|
396 |
+
qweight = qweight.T
|
397 |
+
if scales.shape[1] != 1:
|
398 |
+
scales = scales.T
|
399 |
+
zeros = zeros.T
|
400 |
+
|
401 |
+
# Output also has signs flipped for the addends.
|
402 |
+
self.qweight = qweight
|
403 |
+
self.scales = scales
|
404 |
+
self.addends = -zeros
|
405 |
+
|
406 |
+
self.g_idx: Optional[NDArray]
|
407 |
+
if f"{namebase}.g_idx" in model:
|
408 |
+
self.g_idx = load_unquantized(model[f"{namebase}.g_idx"], np.int32)
|
409 |
+
assert self.g_idx.shape == (qweight.shape[1] * 8,)
|
410 |
+
else:
|
411 |
+
self.g_idx = None
|
412 |
+
|
413 |
+
self.shape = [self.qweight.shape[0], self.qweight.shape[1] * 8]
|
414 |
+
self.data_type = QuantizedDataType(groupsize=self.groupsize(), have_addends=True,
|
415 |
+
have_g_idx=(self.g_idx is not None))
|
416 |
+
|
417 |
+
def inspect(self, row: int, col: int) -> None:
|
418 |
+
'''For debugging.'''
|
419 |
+
qweight = (self.qweight[row, col // 8] >> (4 * (col & 7))) & 0xf
|
420 |
+
if self.g_idx is not None:
|
421 |
+
group = self.g_idx[col]
|
422 |
+
else:
|
423 |
+
group = int(col // self.groupsize())
|
424 |
+
scale = self.scales[row, group]
|
425 |
+
addend = self.addends[row, group]
|
426 |
+
with np.printoptions(precision=None, suppress=True):
|
427 |
+
print(f'scale:{scale} addend:{addend} qweight:{qweight}')
|
428 |
+
print('possible values:', np.arange(16) * scale + addend)
|
429 |
+
print('actual value:', qweight * scale + addend)
|
430 |
+
|
431 |
+
def astype(self, data_type: DataType) -> Tensor:
|
432 |
+
if isinstance(data_type, QuantizedDataType):
|
433 |
+
assert self.g_idx is None and data_type.have_addends is True and data_type.have_g_idx is False
|
434 |
+
return self.regroup(data_type.groupsize)
|
435 |
+
|
436 |
+
dequantized = dequantize_q4(np.ascontiguousarray(self.qweight), self.scales, self.addends, self.g_idx)
|
437 |
+
return UnquantizedTensor(dequantized).astype(data_type)
|
438 |
+
|
439 |
+
def groupsize(self) -> int:
|
440 |
+
assert self.addends.shape == self.scales.shape
|
441 |
+
assert self.shape[1] % self.scales.shape[1] == 0
|
442 |
+
return self.shape[1] // self.scales.shape[1]
|
443 |
+
|
444 |
+
def regroup(self, new_groupsize: int = 32) -> 'GPTQForLLaMaQuantizedTensor':
|
445 |
+
# Old versions of GPTQ-for-LLaMa shared scales and addends between all the
|
446 |
+
# columns in a row. Newer versions share them between every set of N
|
447 |
+
# columns in a row, where N is the `groupsize` parameter, usually 128. The
|
448 |
+
# output format shares them between every set of 32 columns. To handle
|
449 |
+
# this, duplicate scales and addends for every smaller group.
|
450 |
+
# (In the above, 'row' and 'column' are in the sense of the output.)
|
451 |
+
assert self.g_idx is None
|
452 |
+
old_groupsize = self.groupsize()
|
453 |
+
assert old_groupsize >= new_groupsize and old_groupsize % new_groupsize == 0, old_groupsize
|
454 |
+
ret = copy.copy(self)
|
455 |
+
ret.addends = self.addends.repeat(old_groupsize // new_groupsize, axis=1)
|
456 |
+
ret.scales = self.scales.repeat(old_groupsize // new_groupsize, axis=1)
|
457 |
+
ret.data_type = QuantizedDataType(groupsize=new_groupsize, have_addends=True, have_g_idx=False)
|
458 |
+
return ret
|
459 |
+
|
460 |
+
def permute(self, n_head: int) -> Tensor:
|
461 |
+
return DeferredPermutedTensor(self, n_head)
|
462 |
+
|
463 |
+
def to_ggml(self) -> GGMLQuantizedTensor:
|
464 |
+
# The output format looks like this:
|
465 |
+
# For each row:
|
466 |
+
# For each group of 32 columns:
|
467 |
+
# - addend (float32, 4 bytes)
|
468 |
+
# - scale (float32, 4 bytes)
|
469 |
+
# - weights (int4 * 32, 16 bytes)
|
470 |
+
|
471 |
+
if self.groupsize() != 32:
|
472 |
+
raise Exception("should have been regrouped before converting to ggml")
|
473 |
+
|
474 |
+
# Since the output format is mixed between integers and floats, we have
|
475 |
+
# to hackily view the floats as int32s just so numpy will let us
|
476 |
+
# concatenate them.
|
477 |
+
addends_view = self.addends.view(dtype=np.int32)[:, :, np.newaxis]
|
478 |
+
scales_view = self.scales.view(dtype=np.int32)[:, :, np.newaxis]
|
479 |
+
|
480 |
+
# Split into groups of 4 columns (i.e. 32 columns of quantized data):
|
481 |
+
grouped = self.qweight.reshape([self.qweight.shape[0], self.qweight.shape[1] // 4, 4])
|
482 |
+
|
483 |
+
# And concatenate:
|
484 |
+
grouped = np.concatenate([scales_view, addends_view, grouped], axis=2, casting='no')
|
485 |
+
|
486 |
+
return GGMLQuantizedTensor(grouped, self.shape, DT_Q4_1)
|
487 |
+
|
488 |
+
|
489 |
+
@dataclass
|
490 |
+
class LazyTensor:
|
491 |
+
_load: Callable[[], Tensor]
|
492 |
+
shape: List[int]
|
493 |
+
data_type: DataType
|
494 |
+
description: str
|
495 |
+
|
496 |
+
def load(self) -> Tensor:
|
497 |
+
ret = self._load()
|
498 |
+
assert ret.data_type == self.data_type, (self.data_type, ret.data_type, self.description)
|
499 |
+
return ret
|
500 |
+
|
501 |
+
def astype(self, data_type: DataType) -> 'LazyTensor':
|
502 |
+
self.validate_conversion_to(data_type)
|
503 |
+
|
504 |
+
def load() -> Tensor:
|
505 |
+
return self.load().astype(data_type)
|
506 |
+
return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
|
507 |
+
|
508 |
+
def validate_conversion_to(self, data_type: DataType) -> None:
|
509 |
+
if data_type == self.data_type:
|
510 |
+
return
|
511 |
+
if isinstance(data_type, QuantizedDataType):
|
512 |
+
if not isinstance(self.data_type, QuantizedDataType):
|
513 |
+
raise Exception(f"Can't turn an unquantized tensor into a quantized type ({data_type})")
|
514 |
+
if self.data_type.have_g_idx:
|
515 |
+
sys.stderr.write("Error: Input uses the newer GPTQ-for-LLaMa format (using g_idx), which is not yet natively supported by GGML. For now you can still convert this model by passing `--outtype f16` to dequantize, but that will result in a much larger output file for no quality benefit.\n")
|
516 |
+
sys.exit(1)
|
517 |
+
assert not data_type.have_g_idx and self.data_type.have_addends and data_type.have_addends
|
518 |
+
|
519 |
+
|
520 |
+
LazyModel = Dict[str, LazyTensor]
|
521 |
+
|
522 |
+
|
523 |
+
@dataclass
|
524 |
+
class ModelPlus:
|
525 |
+
model: LazyModel
|
526 |
+
paths: List[Path] # Where this was read from.
|
527 |
+
format: Literal['ggml', 'torch', 'safetensors']
|
528 |
+
vocab: Optional[Vocab] # For GGML models (which have vocab built in), the vocab.
|
529 |
+
|
530 |
+
|
531 |
+
def merge_sharded(models: List[LazyModel]) -> LazyModel:
|
532 |
+
# Original LLaMA models have each file contain one part of each tensor.
|
533 |
+
# Use a dict instead of a set to preserve order.
|
534 |
+
names = {name: None for model in models for name in model}
|
535 |
+
|
536 |
+
def convert(name: str) -> LazyTensor:
|
537 |
+
lazy_tensors: List[LazyTensor] = [model[name] for model in models]
|
538 |
+
if len(lazy_tensors) == 1:
|
539 |
+
# only one file; don't go through this procedure since there might
|
540 |
+
# be quantized tensors
|
541 |
+
return lazy_tensors[0]
|
542 |
+
if len(lazy_tensors[0].shape) == 1:
|
543 |
+
# the tensor is just duplicated in every file
|
544 |
+
return lazy_tensors[0]
|
545 |
+
if name.startswith('tok_embeddings.') or \
|
546 |
+
name.endswith('.attention.wo.weight') or \
|
547 |
+
name.endswith('.feed_forward.w2.weight'):
|
548 |
+
# split by columns
|
549 |
+
axis = 1
|
550 |
+
else:
|
551 |
+
# split by rows
|
552 |
+
axis = 0
|
553 |
+
concatenated_shape = list(lazy_tensors[0].shape)
|
554 |
+
concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
|
555 |
+
|
556 |
+
def load() -> UnquantizedTensor:
|
557 |
+
ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
|
558 |
+
concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
|
559 |
+
return UnquantizedTensor(concatenated)
|
560 |
+
description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
|
561 |
+
return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
|
562 |
+
return {name: convert(name) for name in names}
|
563 |
+
|
564 |
+
|
565 |
+
def merge_multifile_models(models_plus: List[ModelPlus]) -> ModelPlus:
|
566 |
+
formats = set(mp.format for mp in models_plus)
|
567 |
+
assert len(formats) == 1, "different formats?"
|
568 |
+
format = formats.pop()
|
569 |
+
paths = [path for mp in models_plus for path in mp.paths]
|
570 |
+
# Use the first non-None vocab, if any.
|
571 |
+
try:
|
572 |
+
vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
|
573 |
+
except StopIteration:
|
574 |
+
vocab = None
|
575 |
+
|
576 |
+
if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
|
577 |
+
# Transformers models put different tensors in different files, but
|
578 |
+
# don't split indivdual tensors between files.
|
579 |
+
model: LazyModel = {}
|
580 |
+
for mp in models_plus:
|
581 |
+
model.update(mp.model)
|
582 |
+
else:
|
583 |
+
model = merge_sharded([mp.model for mp in models_plus])
|
584 |
+
|
585 |
+
return ModelPlus(model, paths, format, vocab)
|
586 |
+
|
587 |
+
|
588 |
+
def permute_lazy(lazy_tensor: LazyTensor, n_head: int) -> LazyTensor:
|
589 |
+
def load() -> Tensor:
|
590 |
+
return lazy_tensor.load().permute(n_head)
|
591 |
+
return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}) ' + lazy_tensor.description)
|
592 |
+
|
593 |
+
|
594 |
+
def convert_transformers_to_orig(model: LazyModel) -> LazyModel:
|
595 |
+
out: LazyModel = {}
|
596 |
+
out["tok_embeddings.weight"] = model["model.embed_tokens.weight"]
|
597 |
+
out["norm.weight"] = model["model.norm.weight"]
|
598 |
+
out["output.weight"] = model["lm_head.weight"]
|
599 |
+
|
600 |
+
n_head = model["model.layers.0.self_attn.q_proj.weight"].shape[1] // 128
|
601 |
+
for i in itertools.count():
|
602 |
+
if f"model.layers.{i}.self_attn.q_proj.weight" not in model:
|
603 |
+
break
|
604 |
+
out[f"layers.{i}.attention.wq.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.q_proj.weight"], n_head)
|
605 |
+
out[f"layers.{i}.attention.wk.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.k_proj.weight"], n_head)
|
606 |
+
out[f"layers.{i}.attention.wv.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
|
607 |
+
out[f"layers.{i}.attention.wo.weight"] = model[f"model.layers.{i}.self_attn.o_proj.weight"]
|
608 |
+
|
609 |
+
out[f"layers.{i}.feed_forward.w1.weight"] = model[f"model.layers.{i}.mlp.gate_proj.weight"]
|
610 |
+
out[f"layers.{i}.feed_forward.w2.weight"] = model[f"model.layers.{i}.mlp.down_proj.weight"]
|
611 |
+
out[f"layers.{i}.feed_forward.w3.weight"] = model[f"model.layers.{i}.mlp.up_proj.weight"]
|
612 |
+
|
613 |
+
out[f"layers.{i}.attention_norm.weight"] = model[f"model.layers.{i}.input_layernorm.weight"]
|
614 |
+
out[f"layers.{i}.ffn_norm.weight"] = model[f"model.layers.{i}.post_attention_layernorm.weight"]
|
615 |
+
return out
|
616 |
+
|
617 |
+
|
618 |
+
def handle_quantization(model: LazyModel) -> LazyModel:
|
619 |
+
'''Convert a model with entries for 'foo.qweight', 'foo.scales', etc.
|
620 |
+
(which resolve to UnquantizedTensors with the raw data) to one with entries
|
621 |
+
for 'foo.weight' (which resolve to QuantizedTensors).
|
622 |
+
'''
|
623 |
+
def convert(name: str) -> Tuple[str, LazyTensor]:
|
624 |
+
if name.endswith(".qweight"):
|
625 |
+
namebase = name.rsplit('.', 1)[0]
|
626 |
+
orig_name = namebase + ".weight"
|
627 |
+
|
628 |
+
lazy_tensor = model[name]
|
629 |
+
assert len(lazy_tensor.shape) == 2
|
630 |
+
real_shape = [lazy_tensor.shape[1], lazy_tensor.shape[0] * 8]
|
631 |
+
|
632 |
+
# Calculate type. This replicates the logic in
|
633 |
+
# GPTQForLLaMaQuantizedTensor (which is executed when the modelis
|
634 |
+
# actually loaded).
|
635 |
+
lazy_scales = model[f"{namebase}.scales"]
|
636 |
+
scales_width = 1 if lazy_scales.shape[1] == 1 else lazy_scales.shape[0]
|
637 |
+
assert real_shape[1] % scales_width == 0
|
638 |
+
groupsize = real_shape[1] // scales_width
|
639 |
+
have_g_idx = f"{namebase}.g_idx" in model
|
640 |
+
data_type = QuantizedDataType(groupsize=groupsize, have_addends=True, have_g_idx=have_g_idx)
|
641 |
+
|
642 |
+
def load() -> Tensor:
|
643 |
+
return GPTQForLLaMaQuantizedTensor(model, namebase)
|
644 |
+
|
645 |
+
return (orig_name, LazyTensor(load, real_shape, data_type, '[quantized]'))
|
646 |
+
else:
|
647 |
+
return (name, model[name])
|
648 |
+
return dict(convert(name) for name in model)
|
649 |
+
|
650 |
+
# Functionality that simulates `torch.load` but where individual tensors are
|
651 |
+
# only loaded into memory on demand, not all at once.
|
652 |
+
# PyTorch can't do this natively as of time of writing:
|
653 |
+
# - https://github.com/pytorch/pytorch/issues/64327
|
654 |
+
# This allows us to de-shard without multiplying RAM usage, and also
|
655 |
+
# conveniently drops the PyTorch dependency (though we still need numpy).
|
656 |
+
|
657 |
+
|
658 |
+
@dataclass
|
659 |
+
class LazyStorageKind:
|
660 |
+
data_type: DataType
|
661 |
+
|
662 |
+
|
663 |
+
@dataclass
|
664 |
+
class LazyStorage:
|
665 |
+
load: Callable[[int, int], NDArray]
|
666 |
+
kind: LazyStorageKind
|
667 |
+
description: str
|
668 |
+
|
669 |
+
|
670 |
+
class LazyUnpickler(pickle.Unpickler):
|
671 |
+
def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
|
672 |
+
super().__init__(fp)
|
673 |
+
self.data_base_path = data_base_path
|
674 |
+
self.zip_file = zip_file
|
675 |
+
|
676 |
+
def persistent_load(self, pid: Any) -> Any:
|
677 |
+
assert pid[0] == 'storage'
|
678 |
+
assert isinstance(pid[1], LazyStorageKind)
|
679 |
+
data_type = pid[1].data_type
|
680 |
+
filename_stem = pid[2]
|
681 |
+
filename = self.data_base_path + '/' + filename_stem
|
682 |
+
info = self.zip_file.getinfo(filename)
|
683 |
+
|
684 |
+
def load(offset: int, elm_count: int) -> NDArray:
|
685 |
+
dtype = DATA_TYPE_TO_NUMPY.get(data_type)
|
686 |
+
if dtype is None:
|
687 |
+
raise Exception("tensor stored in unsupported format")
|
688 |
+
fp = self.zip_file.open(info)
|
689 |
+
fp.seek(offset * dtype.itemsize)
|
690 |
+
size = elm_count * dtype.itemsize
|
691 |
+
data = fp.read(size)
|
692 |
+
assert len(data) == size
|
693 |
+
return np.frombuffer(data, dtype)
|
694 |
+
description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
|
695 |
+
return LazyStorage(load=load, kind=pid[1], description=description)
|
696 |
+
|
697 |
+
# @staticmethod
|
698 |
+
def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any, # pyright: ignore[reportSelfClsParameterName]
|
699 |
+
requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
|
700 |
+
assert isinstance(storage, LazyStorage)
|
701 |
+
|
702 |
+
def load() -> UnquantizedTensor:
|
703 |
+
elm_count = stride[0] * size[0]
|
704 |
+
return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
|
705 |
+
description = f'pickled storage_offset={storage_offset} in {storage.description}'
|
706 |
+
return LazyTensor(load, list(size), storage.kind.data_type, description)
|
707 |
+
|
708 |
+
# @staticmethod
|
709 |
+
def rebuild_from_type_v2(func, new_type, args, state):
|
710 |
+
return func(*args)
|
711 |
+
|
712 |
+
CLASSES: Dict[Any, Any] = {
|
713 |
+
('torch._tensor', '_rebuild_from_type_v2'): rebuild_from_type_v2,
|
714 |
+
('torch._utils', '_rebuild_tensor_v2'): lazy_rebuild_tensor_v2,
|
715 |
+
('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
|
716 |
+
('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
|
717 |
+
('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
|
718 |
+
('torch', 'IntStorage'): LazyStorageKind(DT_I32),
|
719 |
+
('torch', 'Tensor'): LazyTensor,
|
720 |
+
}
|
721 |
+
|
722 |
+
def find_class(self, module: str, name: str) -> Any:
|
723 |
+
if not module.startswith('torch'):
|
724 |
+
return super().find_class(module, name)
|
725 |
+
return self.CLASSES[(module, name)]
|
726 |
+
|
727 |
+
|
728 |
+
def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
|
729 |
+
zf = zipfile.ZipFile(outer_fp)
|
730 |
+
pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
|
731 |
+
assert len(pickle_paths) == 1, pickle_paths
|
732 |
+
pickle_fp = zf.open(pickle_paths[0], 'r')
|
733 |
+
unpickler = LazyUnpickler(pickle_fp,
|
734 |
+
data_base_path=pickle_paths[0][:-4],
|
735 |
+
zip_file=zf)
|
736 |
+
model = unpickler.load()
|
737 |
+
as_dict = dict(model.items())
|
738 |
+
return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
|
739 |
+
|
740 |
+
|
741 |
+
SAFETENSORS_DATA_TYPES: Dict[str, DataType] = {
|
742 |
+
'F16': DT_F16,
|
743 |
+
'F32': DT_F32,
|
744 |
+
'I32': DT_I32,
|
745 |
+
}
|
746 |
+
|
747 |
+
|
748 |
+
def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
|
749 |
+
header_size, = struct.unpack('<Q', fp.read(8))
|
750 |
+
header: Dict[str, Dict[str, Any]] = json.loads(fp.read(header_size))
|
751 |
+
# Use mmap for the actual data to avoid race conditions with the file offset.
|
752 |
+
mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
|
753 |
+
byte_buf = mapped[8 + header_size:]
|
754 |
+
|
755 |
+
def convert(info: Dict[str, Any]) -> LazyTensor:
|
756 |
+
data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
|
757 |
+
numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
|
758 |
+
shape: List[int] = info['shape']
|
759 |
+
begin, end = info['data_offsets']
|
760 |
+
assert 0 <= begin <= end <= len(byte_buf)
|
761 |
+
assert end - begin == math.prod(shape) * numpy_dtype.itemsize
|
762 |
+
buf = byte_buf[begin:end]
|
763 |
+
|
764 |
+
def load() -> UnquantizedTensor:
|
765 |
+
return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
|
766 |
+
description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
|
767 |
+
return LazyTensor(load, shape, data_type, description)
|
768 |
+
model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
|
769 |
+
return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
|
770 |
+
|
771 |
+
|
772 |
+
def must_read(fp: IO[bytes], length: int) -> bytes:
|
773 |
+
ret = fp.read(length)
|
774 |
+
if len(ret) < length:
|
775 |
+
raise Exception("unexpectedly reached end of file")
|
776 |
+
return ret
|
777 |
+
|
778 |
+
|
779 |
+
def lazy_load_ggml_file(fp: io.BufferedReader, path: Path) -> ModelPlus:
|
780 |
+
magic = must_read(fp, 4)[::-1]
|
781 |
+
if magic in (b'ggmf', b'ggjt'):
|
782 |
+
version, = struct.unpack("i", must_read(fp, 4))
|
783 |
+
assert version == 1
|
784 |
+
else:
|
785 |
+
assert magic == b'ggml'
|
786 |
+
version = None
|
787 |
+
n_vocab, n_embd, n_mult, n_head, n_layer, rot, file_type = struct.unpack('<7i', must_read(fp, 28))
|
788 |
+
|
789 |
+
tokens: List[Tuple[bytes, float]] = []
|
790 |
+
for i in range(n_vocab):
|
791 |
+
if i == 32000:
|
792 |
+
# HACK: GPT4All messed with the format without changing the magic
|
793 |
+
# number. Specifically, they changed the vocab section to contain
|
794 |
+
# `n_vocab - 1` tokens instead of `n_vocab` (i.e. omitting the
|
795 |
+
# extra pad token). Try to detect if we're reading a file like
|
796 |
+
# this.
|
797 |
+
orig_pos = fp.tell()
|
798 |
+
fp.seek(20, io.SEEK_CUR)
|
799 |
+
is_gpt4all = fp.read(21) == b'tok_embeddings.weight'
|
800 |
+
fp.seek(orig_pos)
|
801 |
+
if is_gpt4all:
|
802 |
+
break
|
803 |
+
|
804 |
+
length, = struct.unpack("i", must_read(fp, 4))
|
805 |
+
text = must_read(fp, length)
|
806 |
+
if magic != b'ggml':
|
807 |
+
score, = struct.unpack("f", must_read(fp, 4))
|
808 |
+
tokens.append((text, score))
|
809 |
+
vocab = GGMLVocab(tokens) if magic != b'ggml' else None
|
810 |
+
|
811 |
+
model: LazyModel = {}
|
812 |
+
# Use mmap for the actual data to avoid race conditions with the file offset.
|
813 |
+
off = fp.raw.tell()
|
814 |
+
mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
|
815 |
+
fp.raw.seek(off) # needed on Windows
|
816 |
+
|
817 |
+
def read_tensor() -> None: # this is a function so that variables captured in `load` don't change
|
818 |
+
shape_len, name_len, ftype = struct.unpack("iii", must_read(fp, 12))
|
819 |
+
assert 0 <= shape_len <= 3
|
820 |
+
shape: List[int] = list(struct.unpack(f"{shape_len}i", must_read(fp, 4 * shape_len)))
|
821 |
+
shape = shape[::-1]
|
822 |
+
name = must_read(fp, name_len).decode('utf-8')
|
823 |
+
data_type = FTYPE_TO_DATA_TYPE[ftype]
|
824 |
+
|
825 |
+
if magic == b'ggjt':
|
826 |
+
fp.seek((fp.tell() + 31) & -32)
|
827 |
+
|
828 |
+
if data_type == DT_Q4_1:
|
829 |
+
# See GPTQForLLaMaQuantizedTensor.ggml_ndarray()
|
830 |
+
size = 24 * (shape[1] // 32) * shape[0]
|
831 |
+
elif data_type == DT_Q4_0:
|
832 |
+
size = 20 * (shape[1] // 32) * shape[0]
|
833 |
+
else:
|
834 |
+
numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
|
835 |
+
elm_count = math.prod(shape)
|
836 |
+
size = elm_count * numpy_dtype.itemsize
|
837 |
+
offset = fp.tell()
|
838 |
+
buf = mapped[offset:offset+size]
|
839 |
+
fp.seek(size, io.SEEK_CUR)
|
840 |
+
|
841 |
+
def load() -> Tensor:
|
842 |
+
if isinstance(data_type, QuantizedDataType):
|
843 |
+
ndarray = np.frombuffer(buf, dtype=np.uint32)
|
844 |
+
return GGMLQuantizedTensor(ndarray, shape, data_type)
|
845 |
+
else:
|
846 |
+
return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
|
847 |
+
description = f'ggml offset={offset} type={data_type} path={path}'
|
848 |
+
model[name] = LazyTensor(load, shape, data_type, description)
|
849 |
+
|
850 |
+
while fp.read(1) != b'':
|
851 |
+
fp.seek(-1, io.SEEK_CUR)
|
852 |
+
read_tensor()
|
853 |
+
|
854 |
+
return ModelPlus(model=model, paths=[path], format='ggml', vocab=vocab)
|
855 |
+
|
856 |
+
|
857 |
+
@functools.lru_cache(maxsize=None)
|
858 |
+
def lazy_load_file(path: Path) -> ModelPlus:
|
859 |
+
fp = open(path, 'rb')
|
860 |
+
first8 = fp.read(8)
|
861 |
+
fp.seek(0)
|
862 |
+
if first8[:2] == b'PK':
|
863 |
+
# A zip file, i.e. PyTorch format
|
864 |
+
return lazy_load_torch_file(fp, path)
|
865 |
+
elif first8[2:4] == b'gg':
|
866 |
+
# GGML format
|
867 |
+
return lazy_load_ggml_file(fp, path)
|
868 |
+
elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
|
869 |
+
# Probably safetensors
|
870 |
+
return lazy_load_safetensors_file(fp, path)
|
871 |
+
else:
|
872 |
+
raise ValueError(f"unknown format: {path}")
|
873 |
+
|
874 |
+
|
875 |
+
In = TypeVar('In')
|
876 |
+
Out = TypeVar('Out')
|
877 |
+
|
878 |
+
|
879 |
+
def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int) -> Iterable[Out]:
|
880 |
+
'''Parallel map, but with backpressure. If the caller doesn't call `next`
|
881 |
+
fast enough, this will stop calling `func` at some point rather than
|
882 |
+
letting results pile up in memory. Specifically, there is a max of one
|
883 |
+
output value buffered per thread.'''
|
884 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
885 |
+
futures: List[concurrent.futures.Future[Out]] = []
|
886 |
+
items_rev = list(iterable)[::-1]
|
887 |
+
for i in range(min(concurrency, len(items_rev))):
|
888 |
+
futures.append(executor.submit(func, items_rev.pop()))
|
889 |
+
while futures:
|
890 |
+
result = futures.pop(0).result()
|
891 |
+
if items_rev:
|
892 |
+
futures.append(executor.submit(func, items_rev.pop()))
|
893 |
+
yield result
|
894 |
+
|
895 |
+
|
896 |
+
def check_vocab_size(params: Params, vocab: Vocab) -> None:
|
897 |
+
if params.n_vocab != vocab.vocab_size:
|
898 |
+
# GGMLVocab comes from the same file as the model so shouldn't mismatch:
|
899 |
+
assert isinstance(vocab, SentencePieceVocab)
|
900 |
+
if params.n_vocab == vocab.vocab_size_base:
|
901 |
+
print("Ignoring added_tokens.json since model matches vocab size without it.")
|
902 |
+
vocab.added_tokens_list = []
|
903 |
+
vocab.vocab_size = vocab.vocab_size_base
|
904 |
+
return
|
905 |
+
msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
|
906 |
+
if vocab.fname_added_tokens is not None:
|
907 |
+
msg += f" combined with {vocab.fname_added_tokens}"
|
908 |
+
msg += f" has {vocab.vocab_size})."
|
909 |
+
if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
|
910 |
+
msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
|
911 |
+
raise Exception(msg)
|
912 |
+
|
913 |
+
|
914 |
+
class OutputFile:
|
915 |
+
def __init__(self, fname_out: Path) -> None:
|
916 |
+
self.fout = open(fname_out, "wb")
|
917 |
+
|
918 |
+
def write_file_header(self, params: Params) -> None:
|
919 |
+
self.fout.write(b"ggjt"[::-1]) # magic
|
920 |
+
values = [
|
921 |
+
1, # file version
|
922 |
+
params.n_vocab,
|
923 |
+
params.n_embd,
|
924 |
+
params.n_mult,
|
925 |
+
params.n_head,
|
926 |
+
params.n_layer,
|
927 |
+
params.n_embd // params.n_head, # rot (obsolete)
|
928 |
+
params.file_type.value,
|
929 |
+
]
|
930 |
+
self.fout.write(struct.pack("i" * len(values), *values))
|
931 |
+
|
932 |
+
def write_tensor_header(self, name: str, shape: Sequence[int], data_type: DataType) -> None:
|
933 |
+
sname = name.encode('utf-8')
|
934 |
+
self.fout.write(struct.pack("iii", len(shape), len(sname), DATA_TYPE_TO_FTYPE[data_type]))
|
935 |
+
self.fout.write(struct.pack("i" * len(shape), *shape[::-1]))
|
936 |
+
self.fout.write(sname)
|
937 |
+
self.fout.seek((self.fout.tell() + 31) & -32)
|
938 |
+
|
939 |
+
def write_vocab(self, vocab: Vocab) -> None:
|
940 |
+
for text, score in vocab.all_tokens():
|
941 |
+
self.fout.write(struct.pack("i", len(text)))
|
942 |
+
self.fout.write(text)
|
943 |
+
self.fout.write(struct.pack("f", score))
|
944 |
+
|
945 |
+
@staticmethod
|
946 |
+
def write_vocab_only(fname_out: Path, vocab: Vocab) -> None:
|
947 |
+
of = OutputFile(fname_out)
|
948 |
+
params = Params(n_vocab=vocab.vocab_size, n_embd=0, n_mult=0,
|
949 |
+
n_head=1, n_layer=0, file_type=GGMLFileType.AllF32)
|
950 |
+
of = OutputFile(fname_out)
|
951 |
+
of.write_file_header(params)
|
952 |
+
of.write_vocab(vocab)
|
953 |
+
of.fout.close()
|
954 |
+
|
955 |
+
@staticmethod
|
956 |
+
def write_all(fname_out: Path, params: Params, model: LazyModel, vocab: Vocab) -> None:
|
957 |
+
check_vocab_size(params, vocab)
|
958 |
+
of = OutputFile(fname_out)
|
959 |
+
of.write_file_header(params)
|
960 |
+
print("Writing vocab...")
|
961 |
+
of.write_vocab(vocab)
|
962 |
+
|
963 |
+
def do_item(item: Tuple[str, LazyTensor]) -> NDArray:
|
964 |
+
name, lazy_tensor = item
|
965 |
+
return lazy_tensor.load().to_ggml().ndarray
|
966 |
+
|
967 |
+
ndarrays = bounded_parallel_map(do_item, model.items(), concurrency=8)
|
968 |
+
for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
|
969 |
+
size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
|
970 |
+
padi = len(str(len(model)))
|
971 |
+
print(f"[{i+1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type}")
|
972 |
+
of.write_tensor_header(name, lazy_tensor.shape, lazy_tensor.data_type)
|
973 |
+
ndarray.tofile(of.fout)
|
974 |
+
of.fout.close()
|
975 |
+
|
976 |
+
|
977 |
+
def pick_output_type(model: LazyModel, output_type_str: Optional[str]) -> GGMLFileType:
|
978 |
+
wq_type = model["layers.0.attention.wq.weight"].data_type
|
979 |
+
if output_type_str == "f32" or (output_type_str is None and wq_type in (DT_F32, DT_BF16)):
|
980 |
+
return GGMLFileType.AllF32
|
981 |
+
if output_type_str == "f16" or (output_type_str is None and wq_type == DT_F16):
|
982 |
+
return GGMLFileType.MostlyF16
|
983 |
+
if output_type_str == "q4_1" or (output_type_str is None and isinstance(wq_type, QuantizedDataType) and
|
984 |
+
wq_type.have_addends):
|
985 |
+
if isinstance(model["output.weight"].data_type, QuantizedDataType):
|
986 |
+
return GGMLFileType.MostlyQ4_1
|
987 |
+
else:
|
988 |
+
return GGMLFileType.PerLayerIsQ4_1
|
989 |
+
if output_type_str == "q4_0" or (output_type_str is None and isinstance(wq_type, QuantizedDataType)):
|
990 |
+
return GGMLFileType.MostlyQ4_0
|
991 |
+
name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
|
992 |
+
raise Exception(f"Unexpected combination of types: {name_to_type}")
|
993 |
+
|
994 |
+
|
995 |
+
def do_necessary_conversions(model: LazyModel) -> LazyModel:
|
996 |
+
model = handle_quantization(model)
|
997 |
+
|
998 |
+
if "lm_head.weight" in model:
|
999 |
+
model = convert_transformers_to_orig(model)
|
1000 |
+
model = filter_and_sort_tensors(model)
|
1001 |
+
|
1002 |
+
return model
|
1003 |
+
|
1004 |
+
|
1005 |
+
def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
|
1006 |
+
return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
|
1007 |
+
for (name, tensor) in model.items()}
|
1008 |
+
|
1009 |
+
|
1010 |
+
def nth_multifile_path(path: Path, n: int) -> Optional[Path]:
|
1011 |
+
'''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
|
1012 |
+
the nth path in the model.
|
1013 |
+
'''
|
1014 |
+
# Support the following patterns:
|
1015 |
+
patterns: List[Tuple[str, str]] = [
|
1016 |
+
# - x.00.pth, x.01.pth, etc.
|
1017 |
+
(r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
|
1018 |
+
# - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
|
1019 |
+
(r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
|
1020 |
+
# x.bin, x.bin.1, etc.
|
1021 |
+
(r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
|
1022 |
+
]
|
1023 |
+
for regex, replacement in patterns:
|
1024 |
+
if re.search(regex, path.name):
|
1025 |
+
new_path = path.with_name(re.sub(regex, replacement, path.name))
|
1026 |
+
if new_path.exists():
|
1027 |
+
return new_path
|
1028 |
+
return None
|
1029 |
+
|
1030 |
+
|
1031 |
+
def find_multifile_paths(path: Path) -> List[Path]:
|
1032 |
+
'''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
|
1033 |
+
the whole list of paths in the model.
|
1034 |
+
'''
|
1035 |
+
ret: List[Path] = []
|
1036 |
+
for i in itertools.count():
|
1037 |
+
nth_path = nth_multifile_path(path, i)
|
1038 |
+
if nth_path is None:
|
1039 |
+
break
|
1040 |
+
ret.append(nth_path)
|
1041 |
+
if not ret:
|
1042 |
+
# No matches. This should only happen if the file was named, e.g.,
|
1043 |
+
# foo.0, and there was no file named foo. Oh well, try to process it
|
1044 |
+
# as a single file.
|
1045 |
+
return [path]
|
1046 |
+
return ret
|
1047 |
+
|
1048 |
+
|
1049 |
+
def load_some_model(path: Path) -> ModelPlus:
|
1050 |
+
'''Load a model of any supported format.'''
|
1051 |
+
# Be extra-friendly and accept either a file or a directory:
|
1052 |
+
if path.is_dir():
|
1053 |
+
# Check if it's a set of safetensors files first
|
1054 |
+
files = list(path.glob("model-00001-of-*.safetensors"))
|
1055 |
+
if not files:
|
1056 |
+
# Try the PyTorch patterns too, with lower priority
|
1057 |
+
globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin" ]
|
1058 |
+
files = [file for glob in globs for file in path.glob(glob)]
|
1059 |
+
if not files:
|
1060 |
+
# Try GGML too, but with lower priority, since if both a non-GGML
|
1061 |
+
# model and a GGML model exist in the same directory, we assume the
|
1062 |
+
# latter was converted from the former.
|
1063 |
+
files = list(path.glob("ggml-model*.bin*"))
|
1064 |
+
if not files:
|
1065 |
+
raise Exception(f"Can't find model in directory {path}")
|
1066 |
+
if len(files) > 1:
|
1067 |
+
raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
|
1068 |
+
path = files[0]
|
1069 |
+
|
1070 |
+
paths = find_multifile_paths(path)
|
1071 |
+
models_plus: List[ModelPlus] = []
|
1072 |
+
for path in paths:
|
1073 |
+
print(f"Loading model file {path}")
|
1074 |
+
models_plus.append(lazy_load_file(path))
|
1075 |
+
|
1076 |
+
model_plus = merge_multifile_models(models_plus)
|
1077 |
+
return model_plus
|
1078 |
+
|
1079 |
+
|
1080 |
+
def filter_and_sort_tensors(model: LazyModel) -> LazyModel:
|
1081 |
+
return {name: model[name] for name in TENSORS_LIST if name in model}
|
1082 |
+
|
1083 |
+
|
1084 |
+
def load_vocab(path: Path) -> SentencePieceVocab:
|
1085 |
+
# Be extra-friendly and accept either a file or a directory. Also, if it's
|
1086 |
+
# a directory, it might be the model directory, and tokenizer.model might
|
1087 |
+
# be in the parent of that.
|
1088 |
+
if path.is_dir():
|
1089 |
+
path2 = path / "tokenizer.model"
|
1090 |
+
# Use `.parent` instead of /.. to handle the symlink case better.
|
1091 |
+
path3 = path.parent / "tokenizer.model"
|
1092 |
+
if path2.exists():
|
1093 |
+
path = path2
|
1094 |
+
elif path3.exists():
|
1095 |
+
path = path3
|
1096 |
+
else:
|
1097 |
+
raise FileNotFoundError(f"Could not find tokenizer.model in {path} or its parent; if it's in another directory, pass the directory as --vocab-dir")
|
1098 |
+
added_tokens_path = path.parent / "added_tokens.json"
|
1099 |
+
print(f"Loading vocab file {path}")
|
1100 |
+
return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
|
1101 |
+
|
1102 |
+
|
1103 |
+
def default_outfile(model_paths: List[Path], params: Params) -> Path:
|
1104 |
+
namestr = {
|
1105 |
+
GGMLFileType.AllF32: "f32",
|
1106 |
+
GGMLFileType.MostlyF16: "f16",
|
1107 |
+
GGMLFileType.MostlyQ4_0: "q4_0",
|
1108 |
+
GGMLFileType.MostlyQ4_1: "q4_1",
|
1109 |
+
GGMLFileType.PerLayerIsQ4_1: "q4_1",
|
1110 |
+
}[params.file_type]
|
1111 |
+
ret = model_paths[0].parent / f"ggml-model-{namestr}.bin"
|
1112 |
+
if ret in model_paths:
|
1113 |
+
sys.stderr.write(f"Error: Default output path ({ret}) would overwrite the input. Please explicitly specify a path using --outfile.\n")
|
1114 |
+
sys.exit(1)
|
1115 |
+
return ret
|
1116 |
+
|
1117 |
+
|
1118 |
+
def do_dump_model(model_plus: ModelPlus) -> None:
|
1119 |
+
print(f"model_plus.paths = {model_plus.paths!r}")
|
1120 |
+
print(f"model_plus.format = {model_plus.format!r}")
|
1121 |
+
print(f"model_plus.vocab = {model_plus.vocab!r}")
|
1122 |
+
for name, lazy_tensor in model_plus.model.items():
|
1123 |
+
print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
|
1124 |
+
|
1125 |
+
|
1126 |
+
def main(args_in: Optional[List[str]] = None) -> None:
|
1127 |
+
parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
|
1128 |
+
parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
|
1129 |
+
parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
|
1130 |
+
parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
|
1131 |
+
parser.add_argument("--outtype", choices=["f32", "f16", "q4_1", "q4_0"], help="output format (default: based on input)")
|
1132 |
+
parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
|
1133 |
+
parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
|
1134 |
+
parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
|
1135 |
+
args = parser.parse_args(args_in)
|
1136 |
+
|
1137 |
+
vocab: Vocab
|
1138 |
+
if args.dump_single:
|
1139 |
+
model_plus = lazy_load_file(args.model)
|
1140 |
+
do_dump_model(model_plus)
|
1141 |
+
elif args.vocab_only:
|
1142 |
+
vocab = load_vocab(args.vocab_dir or args.model)
|
1143 |
+
assert args.outfile, "need --outfile if using --vocab-only"
|
1144 |
+
outfile = args.outfile
|
1145 |
+
OutputFile.write_vocab_only(outfile, vocab)
|
1146 |
+
print(f"Wrote {outfile}")
|
1147 |
+
else:
|
1148 |
+
model_plus = load_some_model(args.model)
|
1149 |
+
if args.dump:
|
1150 |
+
do_dump_model(model_plus)
|
1151 |
+
return
|
1152 |
+
if model_plus.vocab is not None and args.vocab_dir is None:
|
1153 |
+
vocab = model_plus.vocab
|
1154 |
+
else:
|
1155 |
+
vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
|
1156 |
+
vocab = load_vocab(vocab_dir)
|
1157 |
+
model = model_plus.model
|
1158 |
+
model = do_necessary_conversions(model)
|
1159 |
+
output_type = pick_output_type(model, args.outtype)
|
1160 |
+
model = convert_to_output_type(model, output_type)
|
1161 |
+
params = Params.guessed(model, output_type)
|
1162 |
+
outfile = args.outfile or default_outfile(model_plus.paths, params)
|
1163 |
+
OutputFile.write_all(outfile, params, model, vocab)
|
1164 |
+
print(f"Wrote {outfile}")
|
1165 |
+
|
1166 |
+
|
1167 |
+
if __name__ == '__main__':
|
1168 |
+
main()
|
docs/token_generation_performance_tips.md
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Token generation performance troubleshooting
|
2 |
+
|
3 |
+
## Verifying that the model is running on the GPU with cuBLAS
|
4 |
+
Make sure you compiled llama with the correct env variables according to [this guide](../README.md#cublas), so that llama accepts the `-ngl N` (or `--n-gpu-layers N`) flag. When running llama, you may configure `N` to be very large, and llama will offload the maximum possible number of layers to the GPU, even if it's less than the number you configured. For example:
|
5 |
+
```shell
|
6 |
+
./main -m "path/to/model.bin" -ngl 200000 -p "Please sir, may I have some "
|
7 |
+
```
|
8 |
+
|
9 |
+
When running llama, before it starts the inference work, it will output diagnostic information that shows whether cuBLAS is offloading work to the GPU. Look for these lines:
|
10 |
+
```shell
|
11 |
+
llama_model_load_internal: [cublas] offloading 60 layers to GPU
|
12 |
+
llama_model_load_internal: [cublas] offloading output layer to GPU
|
13 |
+
llama_model_load_internal: [cublas] total VRAM used: 17223 MB
|
14 |
+
... rest of inference
|
15 |
+
```
|
16 |
+
|
17 |
+
If you see these lines, then the GPU is being used.
|
18 |
+
|
19 |
+
## Verifying that the CPU is not oversaturated
|
20 |
+
llama accepts a `-t N` (or `--threads N`) parameter. It's extremely important that this parameter is not too large. If your token generation is extremely slow, try setting this number to 1. If this significantly improves your token generation speed, then your CPU is being oversaturated and you need to explicitly set this parameter to the number of the physicial CPU cores on your machine (even if you utilize a GPU). If in doubt, start with 1 and double the amount until you hit a performance bottleneck, then scale the number down.
|
21 |
+
|
22 |
+
# Example of runtime flags effect on inference speed benchmark
|
23 |
+
These runs were tested on the following machine:
|
24 |
+
GPU: A6000 (48GB VRAM)
|
25 |
+
CPU: 7 physical cores
|
26 |
+
RAM: 32GB
|
27 |
+
|
28 |
+
Model: `TheBloke_Wizard-Vicuna-30B-Uncensored-GGML/Wizard-Vicuna-30B-Uncensored.ggmlv3.q4_0.bin` (30B parameters, 4bit quantization, GGML)
|
29 |
+
|
30 |
+
Run command: `./main -m "path/to/model.bin" -p "-p "An extremely detailed description of the 10 best ethnic dishes will follow, with recipes: " -n 1000 [additional benchmark flags]`
|
31 |
+
|
32 |
+
Result:
|
33 |
+
|
34 |
+
| command | tokens/second (higher is better) |
|
35 |
+
| - | - |
|
36 |
+
| -ngl 2000000 | N/A (less than 0.1) |
|
37 |
+
| -t 7 | 1.7 |
|
38 |
+
| -t 1 -ngl 2000000 | 5.5 |
|
39 |
+
| -t 7 -ngl 2000000 | 8.7 |
|
40 |
+
| -t 4 -ngl 2000000 | 9.1 |
|
examples/CMakeLists.txt
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# dependencies
|
2 |
+
|
3 |
+
find_package(Threads REQUIRED)
|
4 |
+
|
5 |
+
# third-party
|
6 |
+
|
7 |
+
# ...
|
8 |
+
|
9 |
+
# common
|
10 |
+
|
11 |
+
set(TARGET common)
|
12 |
+
|
13 |
+
add_library(${TARGET} OBJECT
|
14 |
+
common.h
|
15 |
+
common.cpp
|
16 |
+
)
|
17 |
+
|
18 |
+
if (BUILD_SHARED_LIBS)
|
19 |
+
set_target_properties(${TARGET} PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
20 |
+
endif()
|
21 |
+
|
22 |
+
target_include_directories(${TARGET} PUBLIC .)
|
23 |
+
target_compile_features(${TARGET} PUBLIC cxx_std_11)
|
24 |
+
target_link_libraries(${TARGET} PRIVATE llama)
|
25 |
+
|
26 |
+
# examples
|
27 |
+
|
28 |
+
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
|
29 |
+
|
30 |
+
if (EMSCRIPTEN)
|
31 |
+
else()
|
32 |
+
add_subdirectory(main)
|
33 |
+
add_subdirectory(quantize)
|
34 |
+
add_subdirectory(quantize-stats)
|
35 |
+
add_subdirectory(perplexity)
|
36 |
+
add_subdirectory(embedding)
|
37 |
+
add_subdirectory(save-load-state)
|
38 |
+
add_subdirectory(benchmark)
|
39 |
+
add_subdirectory(baby-llama)
|
40 |
+
add_subdirectory(train-text-from-scratch)
|
41 |
+
if (LLAMA_METAL)
|
42 |
+
add_subdirectory(metal)
|
43 |
+
endif()
|
44 |
+
if (LLAMA_BUILD_SERVER)
|
45 |
+
add_subdirectory(server)
|
46 |
+
endif()
|
47 |
+
endif()
|
examples/Miku.sh
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
set -e
|
3 |
+
|
4 |
+
AI_NAME="${AI_NAME:-Miku}"
|
5 |
+
MODEL="${MODEL:-./models/gpt4all-7B/gpt4all-lora-unfiltered-quantized.bin}"
|
6 |
+
USER_NAME="${USER_NAME:-Anon}"
|
7 |
+
|
8 |
+
# Uncomment and adjust to the number of CPU cores you want to use.
|
9 |
+
#N_THREAD="${N_THREAD:-4}"
|
10 |
+
N_PREDICTS="${N_PREDICTS:-4096}"
|
11 |
+
|
12 |
+
GEN_OPTIONS=(--batch_size 1024
|
13 |
+
--ctx_size 2048
|
14 |
+
--keep -1
|
15 |
+
--repeat_last_n 256
|
16 |
+
--repeat_penalty 1.17647
|
17 |
+
--temp 0.7
|
18 |
+
--top_k 40
|
19 |
+
--top_p 0.5)
|
20 |
+
|
21 |
+
if [ -n "$N_THREAD" ]; then
|
22 |
+
GEN_OPTIONS+=(--threads "$N_THREAD")
|
23 |
+
fi
|
24 |
+
|
25 |
+
./main "${GEN_OPTIONS[@]}" \
|
26 |
+
--model "$MODEL" \
|
27 |
+
--n_predict "$N_PREDICTS" \
|
28 |
+
--color --interactive \
|
29 |
+
--reverse-prompt "${USER_NAME}:" \
|
30 |
+
--prompt "
|
31 |
+
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 user's computer.
|
32 |
+
${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.
|
33 |
+
${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.
|
34 |
+
${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.
|
35 |
+
${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.
|
36 |
+
The conversation is only between ${USER_NAME} and ${AI_NAME}
|
37 |
+
The conversation is only through text, so ${AI_NAME} can't see ${USER_NAME}'s face or hear his voice.
|
38 |
+
${AI_NAME} can only communicate through text, so she can't send images or videos.
|
39 |
+
|
40 |
+
|
41 |
+
${USER_NAME}: Hello!
|
42 |
+
${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!
|
43 |
+
${AI_NAME}: Hi! I am ${AI_NAME}, your new AI friend, assistant (or whatever you like!), it's so nice to meet you! ^_^
|
44 |
+
${AI_NAME}: I might be an AI, but I also have feelings, so please be nice to me! :)
|
45 |
+
${USER_NAME}: I'll make sure to be nice to you! I'm so happy to have you as my assistant!
|
46 |
+
${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!
|
47 |
+
${AI_NAME}: /think I wonder what ${USER_NAME} likes to do in his free time? I should ask him about that!
|
48 |
+
${AI_NAME}: What do you like to do in your free time? ^_^
|
49 |
+
${USER_NAME}:" "$@"
|
examples/alpaca.sh
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
#
|
4 |
+
# Temporary script - will be removed in the future
|
5 |
+
#
|
6 |
+
|
7 |
+
cd `dirname $0`
|
8 |
+
cd ..
|
9 |
+
|
10 |
+
./main -m ./models/ggml-alpaca-7b-q4.bin \
|
11 |
+
--color \
|
12 |
+
-f ./prompts/alpaca.txt \
|
13 |
+
--ctx_size 2048 \
|
14 |
+
-n -1 \
|
15 |
+
-ins -b 256 \
|
16 |
+
--top_k 10000 \
|
17 |
+
--temp 0.2 \
|
18 |
+
--repeat_penalty 1.1 \
|
19 |
+
-t 7
|
examples/baby-llama/CMakeLists.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set(TARGET baby-llama)
|
2 |
+
add_executable(${TARGET} baby-llama.cpp)
|
3 |
+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
|
4 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_11)
|
examples/baby-llama/baby-llama.cpp
ADDED
@@ -0,0 +1,1692 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "ggml.h"
|
2 |
+
#include <vector>
|
3 |
+
#include <cassert>
|
4 |
+
#include <random>
|
5 |
+
#include <cstring>
|
6 |
+
|
7 |
+
float frand() {
|
8 |
+
return (float)rand()/(float)RAND_MAX;
|
9 |
+
}
|
10 |
+
|
11 |
+
struct random_normal_distribution {
|
12 |
+
std::mt19937 gen;
|
13 |
+
std::normal_distribution<float> nd;
|
14 |
+
float min;
|
15 |
+
float max;
|
16 |
+
};
|
17 |
+
|
18 |
+
void init_random_normal_distribution(struct random_normal_distribution * rnd, int seed, float mean, float std, float min, float max) {
|
19 |
+
rnd->gen = std::mt19937(seed);
|
20 |
+
rnd->nd = std::normal_distribution<float>{mean, std};
|
21 |
+
rnd->min = min;
|
22 |
+
rnd->max = max;
|
23 |
+
}
|
24 |
+
|
25 |
+
float frand_normal(struct random_normal_distribution * rnd) {
|
26 |
+
const float r = rnd->nd(rnd->gen);
|
27 |
+
return ((r < rnd->min) ? (rnd->min) : (r > rnd->max) ? (rnd->max) : r);
|
28 |
+
}
|
29 |
+
|
30 |
+
struct ggml_tensor * randomize_tensor(
|
31 |
+
struct ggml_tensor * tensor,
|
32 |
+
int ndims,
|
33 |
+
const int64_t ne[],
|
34 |
+
float fmin,
|
35 |
+
float fmax) {
|
36 |
+
|
37 |
+
switch (ndims) {
|
38 |
+
case 1:
|
39 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
40 |
+
((float *)tensor->data)[i0] = frand()*(fmax - fmin) + fmin;
|
41 |
+
}
|
42 |
+
break;
|
43 |
+
case 2:
|
44 |
+
for (int i1 = 0; i1 < ne[1]; i1++) {
|
45 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
46 |
+
((float *)tensor->data)[i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
|
47 |
+
}
|
48 |
+
}
|
49 |
+
break;
|
50 |
+
case 3:
|
51 |
+
for (int i2 = 0; i2 < ne[2]; i2++) {
|
52 |
+
for (int i1 = 0; i1 < ne[1]; i1++) {
|
53 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
54 |
+
((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
|
55 |
+
}
|
56 |
+
}
|
57 |
+
}
|
58 |
+
break;
|
59 |
+
case 4:
|
60 |
+
for (int i3 = 0; i3 < ne[3]; i3++) {
|
61 |
+
for (int i2 = 0; i2 < ne[2]; i2++) {
|
62 |
+
for (int i1 = 0; i1 < ne[1]; i1++) {
|
63 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
64 |
+
((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
|
65 |
+
}
|
66 |
+
}
|
67 |
+
}
|
68 |
+
}
|
69 |
+
break;
|
70 |
+
default:
|
71 |
+
assert(false);
|
72 |
+
};
|
73 |
+
|
74 |
+
return tensor;
|
75 |
+
}
|
76 |
+
|
77 |
+
struct ggml_tensor * randomize_tensor_normal(
|
78 |
+
struct ggml_tensor * tensor,
|
79 |
+
int ndims,
|
80 |
+
const int64_t ne[],
|
81 |
+
struct random_normal_distribution * rnd) {
|
82 |
+
float scale = 1.0; // xavier
|
83 |
+
switch (ndims) {
|
84 |
+
case 1:
|
85 |
+
scale /= sqrtf(ne[0]);
|
86 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
87 |
+
((float *)tensor->data)[i0] = scale * frand_normal(rnd);
|
88 |
+
}
|
89 |
+
break;
|
90 |
+
case 2:
|
91 |
+
scale /= sqrtf(ne[0]+ne[1]);
|
92 |
+
for (int i1 = 0; i1 < ne[1]; i1++) {
|
93 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
94 |
+
((float *)tensor->data)[i1*ne[0] + i0] = scale * frand_normal(rnd);
|
95 |
+
}
|
96 |
+
}
|
97 |
+
break;
|
98 |
+
case 3:
|
99 |
+
scale /= sqrtf(ne[0]+ne[1]);
|
100 |
+
for (int i2 = 0; i2 < ne[2]; i2++) {
|
101 |
+
for (int i1 = 0; i1 < ne[1]; i1++) {
|
102 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
103 |
+
((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = scale * frand_normal(rnd);
|
104 |
+
}
|
105 |
+
}
|
106 |
+
}
|
107 |
+
break;
|
108 |
+
case 4:
|
109 |
+
scale /= sqrtf(ne[0]+ne[1]);
|
110 |
+
for (int i3 = 0; i3 < ne[3]; i3++) {
|
111 |
+
for (int i2 = 0; i2 < ne[2]; i2++) {
|
112 |
+
for (int i1 = 0; i1 < ne[1]; i1++) {
|
113 |
+
for (int i0 = 0; i0 < ne[0]; i0++) {
|
114 |
+
((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = scale * frand_normal(rnd);
|
115 |
+
}
|
116 |
+
}
|
117 |
+
}
|
118 |
+
}
|
119 |
+
break;
|
120 |
+
default:
|
121 |
+
assert(false);
|
122 |
+
};
|
123 |
+
|
124 |
+
return tensor;
|
125 |
+
}
|
126 |
+
|
127 |
+
struct llama_hparams {
|
128 |
+
uint32_t n_vocab = 32000;
|
129 |
+
uint32_t n_ctx = 512; // this is provided as user input?
|
130 |
+
uint32_t n_embd = 4096;
|
131 |
+
uint32_t n_mult = 4;
|
132 |
+
uint32_t n_head = 32;
|
133 |
+
uint32_t n_layer = 32;
|
134 |
+
uint32_t n_rot = 64;
|
135 |
+
|
136 |
+
bool operator!=(const llama_hparams & other) const {
|
137 |
+
return memcmp(this, &other, sizeof(llama_hparams));
|
138 |
+
}
|
139 |
+
};
|
140 |
+
|
141 |
+
uint32_t get_n_ff(const struct llama_hparams* hparams) {
|
142 |
+
const uint32_t n_ff = ((2*(4*hparams->n_embd)/3 + hparams->n_mult - 1)/hparams->n_mult)*hparams->n_mult;
|
143 |
+
return n_ff;
|
144 |
+
}
|
145 |
+
|
146 |
+
struct llama_hparams_lora {
|
147 |
+
uint32_t n_vocab = 32000;
|
148 |
+
uint32_t n_ctx = 512; // this is provided as user input?
|
149 |
+
uint32_t n_embd = 4096;
|
150 |
+
uint32_t n_mult = 4;
|
151 |
+
uint32_t n_head = 32;
|
152 |
+
uint32_t n_layer = 32;
|
153 |
+
uint32_t n_rot = 64;
|
154 |
+
uint32_t n_lora = 64;
|
155 |
+
|
156 |
+
bool operator!=(const llama_hparams_lora & other) const {
|
157 |
+
return memcmp(this, &other, sizeof(llama_hparams_lora)) != 0;
|
158 |
+
}
|
159 |
+
};
|
160 |
+
|
161 |
+
struct llama_layer {
|
162 |
+
// normalization
|
163 |
+
struct ggml_tensor * attention_norm;
|
164 |
+
|
165 |
+
// attention
|
166 |
+
struct ggml_tensor * wq;
|
167 |
+
struct ggml_tensor * wk;
|
168 |
+
struct ggml_tensor * wv;
|
169 |
+
struct ggml_tensor * wo;
|
170 |
+
|
171 |
+
// normalization
|
172 |
+
struct ggml_tensor * ffn_norm;
|
173 |
+
|
174 |
+
// ff
|
175 |
+
struct ggml_tensor * w1;
|
176 |
+
struct ggml_tensor * w2;
|
177 |
+
struct ggml_tensor * w3;
|
178 |
+
};
|
179 |
+
|
180 |
+
struct llama_layer_lora {
|
181 |
+
// normalization
|
182 |
+
struct ggml_tensor * attention_norm;
|
183 |
+
|
184 |
+
// attention
|
185 |
+
struct ggml_tensor * wqa;
|
186 |
+
struct ggml_tensor * wqb;
|
187 |
+
struct ggml_tensor * wka;
|
188 |
+
struct ggml_tensor * wkb;
|
189 |
+
struct ggml_tensor * wva;
|
190 |
+
struct ggml_tensor * wvb;
|
191 |
+
struct ggml_tensor * woa;
|
192 |
+
struct ggml_tensor * wob;
|
193 |
+
|
194 |
+
// normalization
|
195 |
+
struct ggml_tensor * ffn_norm;
|
196 |
+
|
197 |
+
// ff
|
198 |
+
struct ggml_tensor * w1;
|
199 |
+
struct ggml_tensor * w2;
|
200 |
+
struct ggml_tensor * w3;
|
201 |
+
};
|
202 |
+
|
203 |
+
|
204 |
+
struct llama_kv_cache {
|
205 |
+
struct ggml_context * ctx = NULL;
|
206 |
+
|
207 |
+
struct ggml_tensor * k;
|
208 |
+
struct ggml_tensor * v;
|
209 |
+
|
210 |
+
// llama_ctx_buffer buf;
|
211 |
+
|
212 |
+
int n; // number of tokens currently in the cache
|
213 |
+
};
|
214 |
+
|
215 |
+
struct llama_model {
|
216 |
+
struct ggml_context * ctx = NULL;
|
217 |
+
|
218 |
+
llama_hparams hparams;
|
219 |
+
|
220 |
+
struct ggml_tensor * tok_embeddings;
|
221 |
+
|
222 |
+
struct ggml_tensor * norm;
|
223 |
+
struct ggml_tensor * output;
|
224 |
+
|
225 |
+
std::vector<llama_layer> layers;
|
226 |
+
};
|
227 |
+
|
228 |
+
struct llama_model_lora {
|
229 |
+
struct ggml_context * ctx = NULL;
|
230 |
+
|
231 |
+
llama_hparams_lora hparams;
|
232 |
+
|
233 |
+
struct ggml_tensor * tok_embeddings;
|
234 |
+
|
235 |
+
struct ggml_tensor * norm;
|
236 |
+
struct ggml_tensor * outputa;
|
237 |
+
struct ggml_tensor * outputb;
|
238 |
+
|
239 |
+
std::vector<llama_layer_lora> layers;
|
240 |
+
};
|
241 |
+
|
242 |
+
void init_model(struct llama_model * model) {
|
243 |
+
const auto & hparams = model->hparams;
|
244 |
+
|
245 |
+
const uint32_t n_embd = hparams.n_embd;
|
246 |
+
const uint32_t n_layer = hparams.n_layer;
|
247 |
+
const uint32_t n_vocab = hparams.n_vocab;
|
248 |
+
|
249 |
+
const uint32_t n_ff = get_n_ff(&hparams);
|
250 |
+
|
251 |
+
struct ggml_context * ctx = model->ctx;
|
252 |
+
|
253 |
+
model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
|
254 |
+
model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
|
255 |
+
model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("output.weight", {n_embd, n_vocab});
|
256 |
+
|
257 |
+
model->layers.resize(n_layer);
|
258 |
+
for (uint32_t i = 0; i < n_layer; ++i) {
|
259 |
+
auto & layer = model->layers[i];
|
260 |
+
|
261 |
+
// std::string layers_i = "layers." + std::to_string(i);
|
262 |
+
|
263 |
+
layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
|
264 |
+
|
265 |
+
layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
|
266 |
+
layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
|
267 |
+
layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
|
268 |
+
layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
|
269 |
+
|
270 |
+
layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
|
271 |
+
|
272 |
+
layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
|
273 |
+
layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
|
274 |
+
layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
|
275 |
+
}
|
276 |
+
}
|
277 |
+
|
278 |
+
|
279 |
+
void init_model_lora(struct llama_model_lora * model) {
|
280 |
+
const auto & hparams = model->hparams;
|
281 |
+
|
282 |
+
const uint32_t n_embd = hparams.n_embd;
|
283 |
+
const uint32_t n_mult = hparams.n_mult;
|
284 |
+
const uint32_t n_layer = hparams.n_layer;
|
285 |
+
const uint32_t n_vocab = hparams.n_vocab;
|
286 |
+
const uint32_t n_lora = hparams.n_lora;
|
287 |
+
|
288 |
+
const uint32_t n_ff = ((2*(4*n_embd)/3 + n_mult - 1)/n_mult)*n_mult;
|
289 |
+
|
290 |
+
struct ggml_context * ctx = model->ctx;
|
291 |
+
|
292 |
+
model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
|
293 |
+
model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
|
294 |
+
model->outputa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_vocab); // ("output.weight", {n_embd, n_vocab});
|
295 |
+
model->outputb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // ("output.weight", {n_embd, n_vocab});
|
296 |
+
|
297 |
+
model->layers.resize(n_layer);
|
298 |
+
for (uint32_t i = 0; i < n_layer; ++i) {
|
299 |
+
auto & layer = model->layers[i];
|
300 |
+
|
301 |
+
// std::string layers_i = "layers." + std::to_string(i);
|
302 |
+
|
303 |
+
layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
|
304 |
+
|
305 |
+
layer.wqa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
|
306 |
+
layer.wqb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
|
307 |
+
layer.wka = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
|
308 |
+
layer.wkb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
|
309 |
+
layer.wva = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
|
310 |
+
layer.wvb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
|
311 |
+
layer.woa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
|
312 |
+
layer.wob = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
|
313 |
+
|
314 |
+
layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
|
315 |
+
|
316 |
+
layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
|
317 |
+
layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
|
318 |
+
layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
|
319 |
+
}
|
320 |
+
}
|
321 |
+
|
322 |
+
void set_param_model(struct llama_model * model) {
|
323 |
+
const auto& hparams = model->hparams;
|
324 |
+
|
325 |
+
const uint32_t n_layer = hparams.n_layer;
|
326 |
+
|
327 |
+
struct ggml_context* ctx = model->ctx;
|
328 |
+
|
329 |
+
ggml_set_param(ctx, model->tok_embeddings);
|
330 |
+
ggml_set_param(ctx, model->norm);
|
331 |
+
ggml_set_param(ctx, model->output);
|
332 |
+
|
333 |
+
for (uint32_t i = 0; i < n_layer; ++i) {
|
334 |
+
auto & layer = model->layers[i];
|
335 |
+
|
336 |
+
ggml_set_param(ctx, layer.attention_norm);
|
337 |
+
ggml_set_param(ctx, layer.wq);
|
338 |
+
ggml_set_param(ctx, layer.wk);
|
339 |
+
ggml_set_param(ctx, layer.wv);
|
340 |
+
ggml_set_param(ctx, layer.wo);
|
341 |
+
ggml_set_param(ctx, layer.ffn_norm);
|
342 |
+
ggml_set_param(ctx, layer.w1);
|
343 |
+
ggml_set_param(ctx, layer.w2);
|
344 |
+
ggml_set_param(ctx, layer.w3);
|
345 |
+
}
|
346 |
+
}
|
347 |
+
|
348 |
+
void set_param_model_lora(struct llama_model_lora * model) {
|
349 |
+
const auto& hparams = model->hparams;
|
350 |
+
|
351 |
+
const uint32_t n_layer = hparams.n_layer;
|
352 |
+
|
353 |
+
struct ggml_context* ctx = model->ctx;
|
354 |
+
|
355 |
+
ggml_set_param(ctx, model->tok_embeddings);
|
356 |
+
ggml_set_param(ctx, model->norm);
|
357 |
+
ggml_set_param(ctx, model->outputa);
|
358 |
+
ggml_set_param(ctx, model->outputb);
|
359 |
+
|
360 |
+
for (uint32_t i = 0; i < n_layer; ++i) {
|
361 |
+
auto & layer = model->layers[i];
|
362 |
+
|
363 |
+
ggml_set_param(ctx, layer.attention_norm);
|
364 |
+
ggml_set_param(ctx, layer.wqa);
|
365 |
+
ggml_set_param(ctx, layer.wqb);
|
366 |
+
ggml_set_param(ctx, layer.wka);
|
367 |
+
ggml_set_param(ctx, layer.wkb);
|
368 |
+
ggml_set_param(ctx, layer.wva);
|
369 |
+
ggml_set_param(ctx, layer.wvb);
|
370 |
+
ggml_set_param(ctx, layer.woa);
|
371 |
+
ggml_set_param(ctx, layer.wob);
|
372 |
+
ggml_set_param(ctx, layer.ffn_norm);
|
373 |
+
ggml_set_param(ctx, layer.w1);
|
374 |
+
ggml_set_param(ctx, layer.w2);
|
375 |
+
ggml_set_param(ctx, layer.w3);
|
376 |
+
}
|
377 |
+
}
|
378 |
+
|
379 |
+
void randomize_model(struct llama_model * model, int seed, float mean, float std, float min, float max) {
|
380 |
+
const auto & hparams = model->hparams;
|
381 |
+
|
382 |
+
const uint32_t n_layer = hparams.n_layer;
|
383 |
+
|
384 |
+
struct random_normal_distribution rnd;
|
385 |
+
init_random_normal_distribution(&rnd, seed, mean, std, min, max);
|
386 |
+
randomize_tensor_normal(model->tok_embeddings, model->tok_embeddings->n_dims, model->tok_embeddings->ne, &rnd);
|
387 |
+
randomize_tensor_normal(model->norm, model->norm->n_dims, model->norm->ne, &rnd);
|
388 |
+
randomize_tensor_normal(model->output, model->output->n_dims, model->output->ne, &rnd);
|
389 |
+
|
390 |
+
for (uint32_t i = 0; i < n_layer; ++i) {
|
391 |
+
auto & layer = model->layers[i];
|
392 |
+
randomize_tensor_normal(layer.attention_norm, layer.attention_norm->n_dims, layer.attention_norm->ne, &rnd);
|
393 |
+
|
394 |
+
randomize_tensor_normal(layer.wq, layer.wq->n_dims, layer.wq->ne, &rnd);
|
395 |
+
randomize_tensor_normal(layer.wk, layer.wk->n_dims, layer.wk->ne, &rnd);
|
396 |
+
randomize_tensor_normal(layer.wv, layer.wv->n_dims, layer.wv->ne, &rnd);
|
397 |
+
randomize_tensor_normal(layer.wo, layer.wo->n_dims, layer.wo->ne, &rnd);
|
398 |
+
|
399 |
+
randomize_tensor_normal(layer.ffn_norm, layer.ffn_norm->n_dims, layer.ffn_norm->ne, &rnd);
|
400 |
+
|
401 |
+
randomize_tensor_normal(layer.w1, layer.w1->n_dims, layer.w1->ne, &rnd);
|
402 |
+
randomize_tensor_normal(layer.w2, layer.w2->n_dims, layer.w2->ne, &rnd);
|
403 |
+
randomize_tensor_normal(layer.w3, layer.w3->n_dims, layer.w3->ne, &rnd);
|
404 |
+
}
|
405 |
+
}
|
406 |
+
|
407 |
+
|
408 |
+
void randomize_model_lora(struct llama_model_lora * model, int seed, float mean, float std, float min, float max) {
|
409 |
+
const auto & hparams = model->hparams;
|
410 |
+
|
411 |
+
const uint32_t n_layer = hparams.n_layer;
|
412 |
+
|
413 |
+
struct random_normal_distribution rnd;
|
414 |
+
init_random_normal_distribution(&rnd, seed, mean, std, min, max);
|
415 |
+
randomize_tensor_normal(model->tok_embeddings, model->tok_embeddings->n_dims, model->tok_embeddings->ne, &rnd);
|
416 |
+
randomize_tensor_normal(model->norm, model->norm->n_dims, model->norm->ne, &rnd);
|
417 |
+
randomize_tensor_normal(model->outputa, model->outputa->n_dims, model->outputa->ne, &rnd);
|
418 |
+
randomize_tensor_normal(model->outputb, model->outputb->n_dims, model->outputb->ne, &rnd);
|
419 |
+
|
420 |
+
for (uint32_t i = 0; i < n_layer; ++i) {
|
421 |
+
auto & layer = model->layers[i];
|
422 |
+
randomize_tensor_normal(layer.attention_norm, layer.attention_norm->n_dims, layer.attention_norm->ne, &rnd);
|
423 |
+
|
424 |
+
randomize_tensor_normal(layer.wqa, layer.wqa->n_dims, layer.wqa->ne, &rnd);
|
425 |
+
randomize_tensor_normal(layer.wqb, layer.wqb->n_dims, layer.wqb->ne, &rnd);
|
426 |
+
randomize_tensor_normal(layer.wka, layer.wka->n_dims, layer.wka->ne, &rnd);
|
427 |
+
randomize_tensor_normal(layer.wkb, layer.wkb->n_dims, layer.wkb->ne, &rnd);
|
428 |
+
randomize_tensor_normal(layer.wva, layer.wva->n_dims, layer.wva->ne, &rnd);
|
429 |
+
randomize_tensor_normal(layer.wvb, layer.wvb->n_dims, layer.wvb->ne, &rnd);
|
430 |
+
randomize_tensor_normal(layer.woa, layer.woa->n_dims, layer.woa->ne, &rnd);
|
431 |
+
randomize_tensor_normal(layer.wob, layer.wob->n_dims, layer.wob->ne, &rnd);
|
432 |
+
|
433 |
+
randomize_tensor_normal(layer.ffn_norm, layer.ffn_norm->n_dims, layer.ffn_norm->ne, &rnd);
|
434 |
+
|
435 |
+
randomize_tensor_normal(layer.w1, layer.w1->n_dims, layer.w1->ne, &rnd);
|
436 |
+
randomize_tensor_normal(layer.w2, layer.w2->n_dims, layer.w2->ne, &rnd);
|
437 |
+
randomize_tensor_normal(layer.w3, layer.w3->n_dims, layer.w3->ne, &rnd);
|
438 |
+
}
|
439 |
+
}
|
440 |
+
|
441 |
+
bool init_kv_cache(struct llama_kv_cache* cache, struct llama_model * model, int n_batch) {
|
442 |
+
const auto & hparams = model->hparams;
|
443 |
+
|
444 |
+
const uint32_t n_ctx = hparams.n_ctx;
|
445 |
+
const uint32_t n_embd = hparams.n_embd;
|
446 |
+
const uint32_t n_layer = hparams.n_layer;
|
447 |
+
|
448 |
+
const int64_t n_mem = n_layer*n_ctx*n_batch;
|
449 |
+
const int64_t n_elements = n_embd*n_mem;
|
450 |
+
|
451 |
+
// cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
|
452 |
+
|
453 |
+
// struct ggml_init_params params;
|
454 |
+
// params.mem_size = cache.buf.size;
|
455 |
+
// params.mem_buffer = cache.buf.addr;
|
456 |
+
// params.no_alloc = false;
|
457 |
+
if (!cache->ctx) {
|
458 |
+
struct ggml_init_params params;
|
459 |
+
params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
|
460 |
+
params.mem_buffer = NULL;
|
461 |
+
params.no_alloc = false;
|
462 |
+
|
463 |
+
cache->ctx = ggml_init(params);
|
464 |
+
|
465 |
+
if (!cache->ctx) {
|
466 |
+
fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
|
467 |
+
return false;
|
468 |
+
}
|
469 |
+
}
|
470 |
+
|
471 |
+
cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
|
472 |
+
cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
|
473 |
+
|
474 |
+
return true;
|
475 |
+
}
|
476 |
+
|
477 |
+
bool init_kv_cache_lora(struct llama_kv_cache* cache, struct llama_model_lora * model, int n_batch) {
|
478 |
+
const auto & hparams = model->hparams;
|
479 |
+
|
480 |
+
const uint32_t n_ctx = hparams.n_ctx;
|
481 |
+
const uint32_t n_embd = hparams.n_embd;
|
482 |
+
const uint32_t n_layer = hparams.n_layer;
|
483 |
+
|
484 |
+
const int64_t n_mem = n_layer*n_ctx*n_batch;
|
485 |
+
const int64_t n_elements = n_embd*n_mem;
|
486 |
+
|
487 |
+
// cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
|
488 |
+
|
489 |
+
// struct ggml_init_params params;
|
490 |
+
// params.mem_size = cache.buf.size;
|
491 |
+
// params.mem_buffer = cache.buf.addr;
|
492 |
+
// params.no_alloc = false;
|
493 |
+
if (!cache->ctx) {
|
494 |
+
struct ggml_init_params params;
|
495 |
+
params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
|
496 |
+
params.mem_buffer = NULL;
|
497 |
+
params.no_alloc = false;
|
498 |
+
|
499 |
+
cache->ctx = ggml_init(params);
|
500 |
+
|
501 |
+
if (!cache->ctx) {
|
502 |
+
fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
|
503 |
+
return false;
|
504 |
+
}
|
505 |
+
}
|
506 |
+
|
507 |
+
cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
|
508 |
+
cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
|
509 |
+
|
510 |
+
return true;
|
511 |
+
}
|
512 |
+
|
513 |
+
struct ggml_tensor * forward(
|
514 |
+
struct llama_model * model,
|
515 |
+
struct llama_kv_cache * cache,
|
516 |
+
struct ggml_context * ctx0,
|
517 |
+
struct ggml_cgraph * gf,
|
518 |
+
struct ggml_tensor * tokens_input,
|
519 |
+
const int n_tokens,
|
520 |
+
const int n_past) {
|
521 |
+
|
522 |
+
const int N = n_tokens;
|
523 |
+
|
524 |
+
struct llama_kv_cache& kv_self = *cache;
|
525 |
+
const auto & hparams = model->hparams;
|
526 |
+
const int n_ctx = hparams.n_ctx;
|
527 |
+
const int n_embd = hparams.n_embd;
|
528 |
+
const int n_layer = hparams.n_layer;
|
529 |
+
const int n_head = hparams.n_head;
|
530 |
+
const int n_rot = hparams.n_rot;
|
531 |
+
|
532 |
+
struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
|
533 |
+
memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
|
534 |
+
|
535 |
+
struct ggml_tensor * kc = kv_self.k;
|
536 |
+
struct ggml_tensor * vc = kv_self.v;
|
537 |
+
|
538 |
+
// inpL shape [n_embd,N,1,1]
|
539 |
+
struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
|
540 |
+
for (int il = 0; il < n_layer; ++il) {
|
541 |
+
struct ggml_tensor * inpSA = inpL;
|
542 |
+
|
543 |
+
struct ggml_tensor * cur;
|
544 |
+
|
545 |
+
// lctx.use_buf(ctx0, 0);
|
546 |
+
|
547 |
+
// norm
|
548 |
+
{
|
549 |
+
// cur shape [n_embd,N,1,1]
|
550 |
+
cur = ggml_rms_norm(ctx0, inpL);
|
551 |
+
|
552 |
+
// cur = attention_norm*cur
|
553 |
+
cur = ggml_mul(ctx0,
|
554 |
+
ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
|
555 |
+
cur);
|
556 |
+
}
|
557 |
+
|
558 |
+
// self-attention
|
559 |
+
{
|
560 |
+
// compute Q and K and RoPE them
|
561 |
+
// wq shape [n_embd, n_embd, 1, 1]
|
562 |
+
// wk shape [n_embd, n_embd, 1, 1]
|
563 |
+
// Qcur shape [n_embd/n_head, n_head, N, 1]
|
564 |
+
// Kcur shape [n_embd/n_head, n_head, N, 1]
|
565 |
+
struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wq, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
|
566 |
+
struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wk, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
|
567 |
+
|
568 |
+
// store key and value to memory
|
569 |
+
{
|
570 |
+
// compute the transposed [N, n_embd] V matrix
|
571 |
+
// wv shape [n_embd, n_embd, 1, 1]
|
572 |
+
// Vcur shape [n_embd, N, 1, 1]
|
573 |
+
struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wv, cur), n_embd, N)));
|
574 |
+
|
575 |
+
// kv_self.k shape [n_embd * n_ctx * n_layer, 1]
|
576 |
+
// kv_self.v shape [n_embd * n_ctx * n_layer, 1]
|
577 |
+
// k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
|
578 |
+
// v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
|
579 |
+
|
580 |
+
/* {
|
581 |
+
struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
|
582 |
+
struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
|
583 |
+
( n_ctx)*ggml_element_size(kv_self.v),
|
584 |
+
(il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
|
585 |
+
|
586 |
+
// important: storing RoPE-ed version of K in the KV cache!
|
587 |
+
ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
|
588 |
+
ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
|
589 |
+
} //*/
|
590 |
+
|
591 |
+
kc = ggml_set_1d(ctx0, kc, ggml_reshape_1d(ctx0, Kcur, n_embd*N), (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
|
592 |
+
vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
|
593 |
+
(il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
|
594 |
+
}
|
595 |
+
|
596 |
+
// Qcur shape [n_embd/n_head, n_head, N, 1]
|
597 |
+
// Q shape [n_embd/n_head, N, n_head, 1]
|
598 |
+
struct ggml_tensor * Q =
|
599 |
+
ggml_permute(ctx0,
|
600 |
+
Qcur,
|
601 |
+
0, 2, 1, 3);
|
602 |
+
|
603 |
+
// kv_self.k shape [n_embd * n_ctx * n_layer, 1]
|
604 |
+
// K shape [n_embd/n_head, n_past + N, n_head, 1]
|
605 |
+
struct ggml_tensor * K =
|
606 |
+
ggml_permute(ctx0,
|
607 |
+
ggml_reshape_3d(ctx0,
|
608 |
+
ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
|
609 |
+
n_embd/n_head, n_head, n_past + N),
|
610 |
+
0, 2, 1, 3);
|
611 |
+
|
612 |
+
// K * Q
|
613 |
+
// KQ shape [n_past + N, N, n_head, 1]
|
614 |
+
struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
|
615 |
+
|
616 |
+
// KQ_scaled = KQ / sqrt(n_embd/n_head)
|
617 |
+
// KQ_scaled shape [n_past + N, N, n_head, 1]
|
618 |
+
struct ggml_tensor * KQ_scaled =
|
619 |
+
ggml_scale(ctx0,
|
620 |
+
KQ,
|
621 |
+
ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
|
622 |
+
|
623 |
+
// KQ_masked = mask_past(KQ_scaled)
|
624 |
+
// KQ_masked shape [n_past + N, N, n_head, 1]
|
625 |
+
struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
|
626 |
+
|
627 |
+
// KQ = soft_max(KQ_masked)
|
628 |
+
// KQ_soft_max shape [n_past + N, N, n_head, 1]
|
629 |
+
struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
|
630 |
+
|
631 |
+
// split cached V into n_head heads
|
632 |
+
//// V shape [n_past + N, n_embd/n_head, n_head, 1]
|
633 |
+
// V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
|
634 |
+
struct ggml_tensor * V =
|
635 |
+
ggml_view_3d(ctx0, vc,
|
636 |
+
n_past + N, n_embd/n_head, n_head,
|
637 |
+
n_ctx*ggml_element_size(vc),
|
638 |
+
n_ctx*ggml_element_size(vc)*n_embd/n_head,
|
639 |
+
il*n_ctx*ggml_element_size(vc)*n_embd);
|
640 |
+
|
641 |
+
// KQV shape [n_embd/n_head, N, n_head, 1]
|
642 |
+
struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
|
643 |
+
|
644 |
+
// KQV_merged = KQV.permute(0, 2, 1, 3)
|
645 |
+
// KQV_merged shape [n_embd/n_head, n_head, N, 1]
|
646 |
+
struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
|
647 |
+
// KQV_merged shape
|
648 |
+
|
649 |
+
// cur = KQV_merged.contiguous().view(n_embd, N)
|
650 |
+
// cur shape [n_embd,N,1,1]
|
651 |
+
cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
|
652 |
+
// cur = ggml_cpy(ctx0,
|
653 |
+
// KQV_merged,
|
654 |
+
// ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
|
655 |
+
|
656 |
+
// projection (no bias)
|
657 |
+
// cur shape [n_embd,N,1,1]
|
658 |
+
cur = ggml_mul_mat(ctx0,
|
659 |
+
model->layers[il].wo,
|
660 |
+
cur);
|
661 |
+
}
|
662 |
+
|
663 |
+
// lctx.use_buf(ctx0, 1);
|
664 |
+
|
665 |
+
// inpFF shape [n_embd,N,1,1]
|
666 |
+
struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
|
667 |
+
|
668 |
+
// feed-forward network
|
669 |
+
{
|
670 |
+
// norm
|
671 |
+
{
|
672 |
+
// cur shape [n_embd,N,1,1]
|
673 |
+
cur = ggml_rms_norm(ctx0, inpFF);
|
674 |
+
|
675 |
+
// cur = ffn_norm*cur
|
676 |
+
// cur shape [n_embd,N,1,1]
|
677 |
+
cur = ggml_mul(ctx0,
|
678 |
+
ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
|
679 |
+
cur);
|
680 |
+
}
|
681 |
+
|
682 |
+
// tmp shape [n_ff,N,1,1]
|
683 |
+
struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
|
684 |
+
model->layers[il].w3,
|
685 |
+
cur);
|
686 |
+
|
687 |
+
// cur shape [n_ff,N,1,1]
|
688 |
+
cur = ggml_mul_mat(ctx0,
|
689 |
+
model->layers[il].w1,
|
690 |
+
cur);
|
691 |
+
|
692 |
+
// SILU activation
|
693 |
+
// cur shape [n_ff,N,1,1]
|
694 |
+
cur = ggml_silu(ctx0, cur);
|
695 |
+
|
696 |
+
// cur shape [n_ff,N,1,1]
|
697 |
+
cur = ggml_mul(ctx0, cur, tmp);
|
698 |
+
|
699 |
+
// cur shape [n_embd,N,1,1]
|
700 |
+
cur = ggml_mul_mat(ctx0,
|
701 |
+
model->layers[il].w2,
|
702 |
+
cur);
|
703 |
+
}
|
704 |
+
|
705 |
+
// cur shape [n_embd,N,1,1]
|
706 |
+
cur = ggml_add(ctx0, cur, inpFF);
|
707 |
+
|
708 |
+
// input for next layer
|
709 |
+
// inpL shape [n_embd,N,1,1]
|
710 |
+
inpL = cur;
|
711 |
+
}
|
712 |
+
|
713 |
+
// norm
|
714 |
+
{
|
715 |
+
|
716 |
+
// inpL shape [n_embd,N,1,1]
|
717 |
+
inpL = ggml_rms_norm(ctx0, inpL);
|
718 |
+
|
719 |
+
// inpL = norm*inpL
|
720 |
+
// inpL shape [n_embd,N,1,1]
|
721 |
+
inpL = ggml_mul(ctx0,
|
722 |
+
ggml_repeat(ctx0, model->norm, inpL),
|
723 |
+
inpL);
|
724 |
+
|
725 |
+
//embeddings = inpL;
|
726 |
+
}
|
727 |
+
|
728 |
+
// lm_head
|
729 |
+
// inpL shape [n_vocab,N,1,1]
|
730 |
+
inpL = ggml_mul_mat(ctx0, model->output, inpL);
|
731 |
+
|
732 |
+
// run the computation
|
733 |
+
ggml_build_forward_expand(gf, inpL);
|
734 |
+
|
735 |
+
return inpL;
|
736 |
+
}
|
737 |
+
|
738 |
+
void assert_shape_1d(struct ggml_tensor * tensor, int64_t ne0) {
|
739 |
+
GGML_ASSERT(tensor->n_dims == 1);
|
740 |
+
GGML_ASSERT(tensor->ne[0] == ne0);
|
741 |
+
}
|
742 |
+
|
743 |
+
void assert_shape_2d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1) {
|
744 |
+
GGML_ASSERT(tensor->n_dims == 2);
|
745 |
+
GGML_ASSERT(tensor->ne[0] == ne0);
|
746 |
+
GGML_ASSERT(tensor->ne[1] == ne1);
|
747 |
+
}
|
748 |
+
|
749 |
+
void assert_shape_3d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2) {
|
750 |
+
GGML_ASSERT(tensor->n_dims == 3);
|
751 |
+
GGML_ASSERT(tensor->ne[0] == ne0);
|
752 |
+
GGML_ASSERT(tensor->ne[1] == ne1);
|
753 |
+
GGML_ASSERT(tensor->ne[2] == ne2);
|
754 |
+
}
|
755 |
+
|
756 |
+
void assert_shape_4d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
|
757 |
+
GGML_ASSERT(tensor->n_dims == 4);
|
758 |
+
GGML_ASSERT(tensor->ne[0] == ne0);
|
759 |
+
GGML_ASSERT(tensor->ne[1] == ne1);
|
760 |
+
GGML_ASSERT(tensor->ne[2] == ne2);
|
761 |
+
GGML_ASSERT(tensor->ne[3] == ne3);
|
762 |
+
}
|
763 |
+
|
764 |
+
struct ggml_tensor * forward_batch(
|
765 |
+
struct llama_model * model,
|
766 |
+
struct llama_kv_cache * cache,
|
767 |
+
struct ggml_context * ctx0,
|
768 |
+
struct ggml_cgraph * gf,
|
769 |
+
struct ggml_tensor * tokens_input,
|
770 |
+
const int n_tokens,
|
771 |
+
const int n_past,
|
772 |
+
const int n_batch) {
|
773 |
+
|
774 |
+
const int N = n_tokens;
|
775 |
+
|
776 |
+
struct llama_kv_cache& kv_self = *cache;
|
777 |
+
const auto & hparams = model->hparams;
|
778 |
+
const int n_ctx = hparams.n_ctx;
|
779 |
+
const int n_vocab = hparams.n_vocab;
|
780 |
+
const int n_embd = hparams.n_embd;
|
781 |
+
const int n_layer = hparams.n_layer;
|
782 |
+
const int n_head = hparams.n_head;
|
783 |
+
const int n_rot = hparams.n_rot;
|
784 |
+
const int n_ff = get_n_ff(&hparams);
|
785 |
+
|
786 |
+
struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
|
787 |
+
memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
|
788 |
+
|
789 |
+
struct ggml_tensor * kc = kv_self.k;
|
790 |
+
struct ggml_tensor * vc = kv_self.v;
|
791 |
+
|
792 |
+
// inpL shape [n_embd,N*n_batch,1]
|
793 |
+
struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
|
794 |
+
assert_shape_2d(inpL, n_embd, N*n_batch);
|
795 |
+
for (int il = 0; il < n_layer; ++il) {
|
796 |
+
struct ggml_tensor * inpSA = inpL;
|
797 |
+
|
798 |
+
struct ggml_tensor * cur;
|
799 |
+
|
800 |
+
// lctx.use_buf(ctx0, 0);
|
801 |
+
|
802 |
+
// norm
|
803 |
+
{
|
804 |
+
// cur shape [n_embd,N*n_batch,1,1]
|
805 |
+
cur = ggml_rms_norm(ctx0, inpL);
|
806 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
807 |
+
|
808 |
+
// cur = attention_norm*cur
|
809 |
+
cur = ggml_mul(ctx0,
|
810 |
+
ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
|
811 |
+
cur);
|
812 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
813 |
+
}
|
814 |
+
|
815 |
+
// self-attention
|
816 |
+
{
|
817 |
+
// compute Q and K and RoPE them
|
818 |
+
// wq shape [n_embd, n_embd, 1, 1]
|
819 |
+
// wk shape [n_embd, n_embd, 1, 1]
|
820 |
+
// Qcur shape [n_embd/n_head, n_head, N, n_batch]
|
821 |
+
// Kcur shape [n_embd/n_head, n_head, N, n_batch]
|
822 |
+
struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wq, cur), n_embd/n_head, n_head, N, n_batch), n_past, n_rot, 0);
|
823 |
+
struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_4d(ctx0, ggml_mul_mat(ctx0, model->layers[il].wk, cur), n_embd/n_head, n_head, N, n_batch), n_past, n_rot, 0);
|
824 |
+
assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
|
825 |
+
assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
|
826 |
+
|
827 |
+
// store key and value to memory
|
828 |
+
{
|
829 |
+
// compute the transposed [N, n_embd] V matrix
|
830 |
+
// wv shape [n_embd, n_embd, 1, 1]
|
831 |
+
// Vcur shape [N, n_embd, n_batch, 1]
|
832 |
+
struct ggml_tensor * Vcur = ggml_cont(ctx0,
|
833 |
+
ggml_permute(ctx0,
|
834 |
+
ggml_reshape_3d(ctx0,
|
835 |
+
ggml_mul_mat(ctx0,
|
836 |
+
model->layers[il].wv,
|
837 |
+
cur),
|
838 |
+
n_embd, N, n_batch),
|
839 |
+
1, 0, 2, 3));
|
840 |
+
|
841 |
+
assert_shape_3d(Vcur, N, n_embd, n_batch);
|
842 |
+
|
843 |
+
// kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
|
844 |
+
// kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
|
845 |
+
// k shape [n_embd * N, n_batch] == kv_self.k[:,n_past:n_past+N,:,il]
|
846 |
+
// v shape [N, n_embd, n_batch, 1] == kv_self.v[:,n_past:n_past+N,:,il]
|
847 |
+
|
848 |
+
/* {
|
849 |
+
struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
|
850 |
+
struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
|
851 |
+
( n_ctx)*ggml_element_size(kv_self.v),
|
852 |
+
(il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
|
853 |
+
|
854 |
+
// important: storing RoPE-ed version of K in the KV cache!
|
855 |
+
ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
|
856 |
+
ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
|
857 |
+
} //*/
|
858 |
+
|
859 |
+
kc = ggml_set_2d(ctx0, kc,
|
860 |
+
ggml_reshape_2d(ctx0, Kcur, n_embd*N, n_batch),
|
861 |
+
ggml_element_size(kc)*n_embd*n_ctx,
|
862 |
+
(ggml_element_size(kc)*n_embd)*(il*n_batch*n_ctx + n_past));
|
863 |
+
vc = ggml_set_2d(ctx0, vc,
|
864 |
+
ggml_reshape_2d(ctx0, Vcur, N*n_embd, n_batch),
|
865 |
+
ggml_element_size(vc)*n_ctx*n_embd,
|
866 |
+
ggml_element_size(vc)*(n_past + il*n_embd*n_batch*n_ctx));
|
867 |
+
|
868 |
+
assert_shape_1d(kc, n_embd * n_ctx * n_batch * n_layer);
|
869 |
+
assert_shape_1d(vc, n_embd * n_ctx * n_batch * n_layer);
|
870 |
+
}
|
871 |
+
|
872 |
+
// Qcur shape [n_embd/n_head, n_head, N, n_batch]
|
873 |
+
// Q shape [n_embd/n_head, N, n_head, n_batch]
|
874 |
+
struct ggml_tensor * Q =
|
875 |
+
ggml_permute(ctx0,
|
876 |
+
Qcur,
|
877 |
+
0, 2, 1, 3);
|
878 |
+
assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
|
879 |
+
|
880 |
+
// kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
|
881 |
+
// K shape [n_embd/n_head, n_past + N, n_head, n_batch]
|
882 |
+
struct ggml_tensor * K =
|
883 |
+
ggml_permute(ctx0,
|
884 |
+
ggml_reshape_4d(ctx0,
|
885 |
+
ggml_view_3d(ctx0,
|
886 |
+
kc,
|
887 |
+
n_embd,
|
888 |
+
(n_past + N),
|
889 |
+
n_batch,
|
890 |
+
n_embd*ggml_element_size(kc),
|
891 |
+
n_ctx*n_embd*ggml_element_size(kc),
|
892 |
+
il*n_batch*n_ctx*n_embd*ggml_element_size(kc)),
|
893 |
+
n_embd/n_head, n_head, n_past + N, n_batch),
|
894 |
+
0, 2, 1, 3);
|
895 |
+
assert_shape_4d(K, n_embd/n_head, n_past + N, n_head, n_batch);
|
896 |
+
|
897 |
+
// K * Q
|
898 |
+
// KQ shape [n_past + N, N, n_head, n_batch]
|
899 |
+
struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
|
900 |
+
assert_shape_4d(KQ, n_past + N, N, n_head, n_batch);
|
901 |
+
|
902 |
+
// KQ_scaled = KQ / sqrt(n_embd/n_head)
|
903 |
+
// KQ_scaled shape [n_past + N, N, n_head, n_batch]
|
904 |
+
struct ggml_tensor * KQ_scaled =
|
905 |
+
ggml_scale(ctx0,
|
906 |
+
KQ,
|
907 |
+
ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
|
908 |
+
assert_shape_4d(KQ_scaled, n_past + N, N, n_head, n_batch);
|
909 |
+
|
910 |
+
// KQ_masked = mask_past(KQ_scaled)
|
911 |
+
// KQ_masked shape [n_past + N, N, n_head, n_batch]
|
912 |
+
struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
|
913 |
+
assert_shape_4d(KQ_masked, n_past + N, N, n_head, n_batch);
|
914 |
+
|
915 |
+
// KQ = soft_max(KQ_masked)
|
916 |
+
// KQ_soft_max shape [n_past + N, N, n_head, n_batch]
|
917 |
+
struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
|
918 |
+
assert_shape_4d(KQ_soft_max, n_past + N, N, n_head, n_batch);
|
919 |
+
|
920 |
+
// split cached V into n_head heads
|
921 |
+
// kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
|
922 |
+
// V shape [n_past + N, n_embd/n_head, n_head, n_batch] == kv_self.v[:(n_past+N),:,:,il]
|
923 |
+
struct ggml_tensor * V =
|
924 |
+
ggml_view_4d(ctx0, vc,
|
925 |
+
n_past + N, n_embd/n_head, n_head, n_batch,
|
926 |
+
ggml_element_size(vc)*n_ctx,
|
927 |
+
ggml_element_size(vc)*n_ctx*n_embd/n_head,
|
928 |
+
ggml_element_size(vc)*n_ctx*n_embd,
|
929 |
+
il*n_batch*n_ctx*n_embd*ggml_element_size(vc));
|
930 |
+
assert_shape_4d(V, n_past + N, n_embd/n_head, n_head, n_batch);
|
931 |
+
|
932 |
+
// KQV shape [n_embd/n_head, N, n_head, n_batch]
|
933 |
+
struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
|
934 |
+
assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
|
935 |
+
|
936 |
+
// KQV_merged = KQV.permute(0, 2, 1, 3)
|
937 |
+
// KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
|
938 |
+
struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
|
939 |
+
assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
|
940 |
+
// KQV_merged shape
|
941 |
+
|
942 |
+
// cur = KQV_merged.contiguous().view(n_embd, N)
|
943 |
+
// cur shape [n_embd,N*n_batch,1,1]
|
944 |
+
cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
|
945 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
946 |
+
// cur = ggml_cpy(ctx0,
|
947 |
+
// KQV_merged,
|
948 |
+
// ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
|
949 |
+
|
950 |
+
// projection (no bias)
|
951 |
+
// cur shape [n_embd,N*n_batch,1,1]
|
952 |
+
cur = ggml_mul_mat(ctx0,
|
953 |
+
model->layers[il].wo,
|
954 |
+
cur);
|
955 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
956 |
+
}
|
957 |
+
|
958 |
+
// lctx.use_buf(ctx0, 1);
|
959 |
+
|
960 |
+
// inpFF shape [n_embd,N*n_batch,1,1]
|
961 |
+
struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
|
962 |
+
assert_shape_2d(inpFF, n_embd, N*n_batch);
|
963 |
+
|
964 |
+
// feed-forward network
|
965 |
+
{
|
966 |
+
// norm
|
967 |
+
{
|
968 |
+
// cur shape [n_embd,N*n_batch,1,1]
|
969 |
+
cur = ggml_rms_norm(ctx0, inpFF);
|
970 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
971 |
+
|
972 |
+
// cur = ffn_norm*cur
|
973 |
+
// cur shape [n_embd,N*n_batch,1,1]
|
974 |
+
cur = ggml_mul(ctx0,
|
975 |
+
ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
|
976 |
+
cur);
|
977 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
978 |
+
}
|
979 |
+
|
980 |
+
// tmp shape [n_ff,N*n_batch,1,1]
|
981 |
+
struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
|
982 |
+
model->layers[il].w3,
|
983 |
+
cur);
|
984 |
+
assert_shape_2d(tmp, n_ff, N*n_batch);
|
985 |
+
|
986 |
+
// cur shape [n_ff,N*n_batch,1,1]
|
987 |
+
cur = ggml_mul_mat(ctx0,
|
988 |
+
model->layers[il].w1,
|
989 |
+
cur);
|
990 |
+
assert_shape_2d(cur, n_ff, N*n_batch);
|
991 |
+
|
992 |
+
// SILU activation
|
993 |
+
// cur shape [n_ff,N*n_batch,1,1]
|
994 |
+
cur = ggml_silu(ctx0, cur);
|
995 |
+
assert_shape_2d(cur, n_ff, N*n_batch);
|
996 |
+
|
997 |
+
// cur shape [n_ff,N*n_batch,1,1]
|
998 |
+
cur = ggml_mul(ctx0, cur, tmp);
|
999 |
+
assert_shape_2d(cur, n_ff, N*n_batch);
|
1000 |
+
|
1001 |
+
// cur shape [n_embd,N*n_batch,1,1]
|
1002 |
+
cur = ggml_mul_mat(ctx0,
|
1003 |
+
model->layers[il].w2,
|
1004 |
+
cur);
|
1005 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
1006 |
+
}
|
1007 |
+
|
1008 |
+
// cur shape [n_embd,N*n_batch,1,1]
|
1009 |
+
cur = ggml_add(ctx0, cur, inpFF);
|
1010 |
+
assert_shape_2d(cur, n_embd, N*n_batch);
|
1011 |
+
|
1012 |
+
// input for next layer
|
1013 |
+
// inpL shape [n_embd,N*n_batch,1,1]
|
1014 |
+
inpL = cur;
|
1015 |
+
assert_shape_2d(inpL, n_embd, N*n_batch);
|
1016 |
+
}
|
1017 |
+
|
1018 |
+
// norm
|
1019 |
+
{
|
1020 |
+
|
1021 |
+
// inpL shape [n_embd,N*n_batch,1,1]
|
1022 |
+
inpL = ggml_rms_norm(ctx0, inpL);
|
1023 |
+
assert_shape_2d(inpL, n_embd, N*n_batch);
|
1024 |
+
|
1025 |
+
// inpL = norm*inpL
|
1026 |
+
// inpL shape [n_embd,N*n_batch,1,1]
|
1027 |
+
inpL = ggml_mul(ctx0,
|
1028 |
+
ggml_repeat(ctx0, model->norm, inpL),
|
1029 |
+
inpL);
|
1030 |
+
|
1031 |
+
assert_shape_2d(inpL, n_embd, N*n_batch);
|
1032 |
+
|
1033 |
+
//embeddings = inpL;
|
1034 |
+
}
|
1035 |
+
|
1036 |
+
// lm_head
|
1037 |
+
// inpL shape [n_vocab,N*n_batch,1,1]
|
1038 |
+
inpL = ggml_mul_mat(ctx0, model->output, inpL);
|
1039 |
+
assert_shape_2d(inpL, n_vocab, N*n_batch);
|
1040 |
+
|
1041 |
+
{
|
1042 |
+
// inpL shape [n_vocab,N,n_batch,1]
|
1043 |
+
inpL = ggml_reshape_3d(ctx0,
|
1044 |
+
inpL,
|
1045 |
+
n_vocab, N, n_batch);
|
1046 |
+
assert_shape_3d(inpL, n_vocab, N, n_batch);
|
1047 |
+
}
|
1048 |
+
|
1049 |
+
// run the computation
|
1050 |
+
ggml_build_forward_expand(gf, inpL);
|
1051 |
+
|
1052 |
+
return inpL;
|
1053 |
+
}
|
1054 |
+
|
1055 |
+
|
1056 |
+
struct ggml_tensor * forward_lora(
|
1057 |
+
struct llama_model_lora * model,
|
1058 |
+
struct llama_kv_cache * cache,
|
1059 |
+
struct ggml_context * ctx0,
|
1060 |
+
struct ggml_cgraph * gf,
|
1061 |
+
struct ggml_tensor * tokens_input,
|
1062 |
+
const int n_tokens,
|
1063 |
+
const int n_past) {
|
1064 |
+
|
1065 |
+
const int N = n_tokens;
|
1066 |
+
|
1067 |
+
struct llama_kv_cache& kv_self = *cache;
|
1068 |
+
const auto & hparams = model->hparams;
|
1069 |
+
|
1070 |
+
const int n_ctx = hparams.n_ctx;
|
1071 |
+
const int n_embd = hparams.n_embd;
|
1072 |
+
const int n_layer = hparams.n_layer;
|
1073 |
+
const int n_head = hparams.n_head;
|
1074 |
+
const int n_rot = hparams.n_rot;
|
1075 |
+
|
1076 |
+
struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
|
1077 |
+
memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
|
1078 |
+
|
1079 |
+
struct ggml_tensor * kc = kv_self.k;
|
1080 |
+
struct ggml_tensor * vc = kv_self.v;
|
1081 |
+
|
1082 |
+
// inpL shape [n_embd,N,1,1]
|
1083 |
+
struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
|
1084 |
+
for (int il = 0; il < n_layer; ++il) {
|
1085 |
+
struct ggml_tensor * inpSA = inpL;
|
1086 |
+
|
1087 |
+
struct ggml_tensor * cur;
|
1088 |
+
|
1089 |
+
// norm
|
1090 |
+
{
|
1091 |
+
// cur shape [n_embd,N,1,1]
|
1092 |
+
cur = ggml_rms_norm(ctx0, inpL);
|
1093 |
+
|
1094 |
+
// cur = attention_norm*cur
|
1095 |
+
cur = ggml_mul(ctx0,
|
1096 |
+
ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
|
1097 |
+
cur);
|
1098 |
+
}
|
1099 |
+
|
1100 |
+
// self-attention
|
1101 |
+
{
|
1102 |
+
// compute Q and K and RoPE them
|
1103 |
+
// wq shape [n_embd, n_embd, 1, 1]
|
1104 |
+
// wk shape [n_embd, n_embd, 1, 1]
|
1105 |
+
// Qcur shape [n_embd/n_head, n_head, N, 1]
|
1106 |
+
// Kcur shape [n_embd/n_head, n_head, N, 1]
|
1107 |
+
struct ggml_tensor * Qcur = ggml_rope(ctx0,
|
1108 |
+
ggml_reshape_3d(ctx0,
|
1109 |
+
ggml_mul_mat(ctx0,
|
1110 |
+
model->layers[il].wqa,
|
1111 |
+
ggml_mul_mat(ctx0,
|
1112 |
+
model->layers[il].wqb,
|
1113 |
+
cur)),
|
1114 |
+
n_embd/n_head, n_head, N),
|
1115 |
+
n_past, n_rot, 0);
|
1116 |
+
struct ggml_tensor * Kcur = ggml_rope(ctx0,
|
1117 |
+
ggml_reshape_3d(ctx0,
|
1118 |
+
ggml_mul_mat(ctx0,
|
1119 |
+
model->layers[il].wka,
|
1120 |
+
ggml_mul_mat(ctx0,
|
1121 |
+
model->layers[il].wkb,
|
1122 |
+
cur)),
|
1123 |
+
n_embd/n_head, n_head, N),
|
1124 |
+
n_past, n_rot, 0);
|
1125 |
+
|
1126 |
+
// store key and value to memory
|
1127 |
+
{
|
1128 |
+
// compute the transposed [N, n_embd] V matrix
|
1129 |
+
// wv shape [n_embd, n_embd, 1, 1]
|
1130 |
+
// Vcur shape [n_embd, N, 1, 1]
|
1131 |
+
struct ggml_tensor * Vcur = ggml_cont(ctx0,
|
1132 |
+
ggml_transpose(ctx0,
|
1133 |
+
ggml_reshape_2d(ctx0,
|
1134 |
+
ggml_mul_mat(ctx0,
|
1135 |
+
model->layers[il].wva,
|
1136 |
+
ggml_mul_mat(ctx0,
|
1137 |
+
model->layers[il].wvb,
|
1138 |
+
cur)),
|
1139 |
+
n_embd, N)));
|
1140 |
+
|
1141 |
+
// kv_self.k shape [n_embd * n_ctx * n_layer, 1]
|
1142 |
+
// kv_self.v shape [n_embd * n_ctx * n_layer, 1]
|
1143 |
+
// k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
|
1144 |
+
// v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
|
1145 |
+
|
1146 |
+
/* {
|
1147 |
+
struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
|
1148 |
+
struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
|
1149 |
+
( n_ctx)*ggml_element_size(kv_self.v),
|
1150 |
+
(il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
|
1151 |
+
|
1152 |
+
// important: storing RoPE-ed version of K in the KV cache!
|
1153 |
+
ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
|
1154 |
+
ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
|
1155 |
+
} //*/
|
1156 |
+
|
1157 |
+
kc = ggml_set_1d(ctx0, kc, ggml_reshape_1d(ctx0, Kcur, n_embd*N), (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
|
1158 |
+
vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
|
1159 |
+
(il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
|
1160 |
+
}
|
1161 |
+
|
1162 |
+
// Qcur shape [n_embd/n_head, n_head, N, 1]
|
1163 |
+
// Q shape [n_embd/n_head, N, n_head, 1]
|
1164 |
+
struct ggml_tensor * Q =
|
1165 |
+
ggml_permute(ctx0,
|
1166 |
+
Qcur,
|
1167 |
+
0, 2, 1, 3);
|
1168 |
+
|
1169 |
+
// kv_self.k shape [n_embd * n_ctx * n_layer, 1]
|
1170 |
+
// K shape [n_embd/n_head, n_past + N, n_head, 1]
|
1171 |
+
struct ggml_tensor * K =
|
1172 |
+
ggml_permute(ctx0,
|
1173 |
+
ggml_reshape_3d(ctx0,
|
1174 |
+
ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
|
1175 |
+
n_embd/n_head, n_head, n_past + N),
|
1176 |
+
0, 2, 1, 3);
|
1177 |
+
|
1178 |
+
// K * Q
|
1179 |
+
// KQ shape [n_past + N, N, n_head, 1]
|
1180 |
+
struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
|
1181 |
+
|
1182 |
+
// KQ_scaled = KQ / sqrt(n_embd/n_head)
|
1183 |
+
// KQ_scaled shape [n_past + N, N, n_head, 1]
|
1184 |
+
struct ggml_tensor * KQ_scaled =
|
1185 |
+
ggml_scale(ctx0,
|
1186 |
+
KQ,
|
1187 |
+
ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
|
1188 |
+
|
1189 |
+
// KQ_masked = mask_past(KQ_scaled)
|
1190 |
+
// KQ_masked shape [n_past + N, N, n_head, 1]
|
1191 |
+
struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
|
1192 |
+
|
1193 |
+
// KQ = soft_max(KQ_masked)
|
1194 |
+
// KQ_soft_max shape [n_past + N, N, n_head, 1]
|
1195 |
+
struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
|
1196 |
+
|
1197 |
+
// split cached V into n_head heads
|
1198 |
+
//// V shape [n_past + N, n_embd/n_head, n_head, 1]
|
1199 |
+
// V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
|
1200 |
+
struct ggml_tensor * V =
|
1201 |
+
ggml_view_3d(ctx0, vc,
|
1202 |
+
n_past + N, n_embd/n_head, n_head,
|
1203 |
+
n_ctx*ggml_element_size(vc),
|
1204 |
+
n_ctx*ggml_element_size(vc)*n_embd/n_head,
|
1205 |
+
il*n_ctx*ggml_element_size(vc)*n_embd);
|
1206 |
+
|
1207 |
+
// KQV shape [n_embd/n_head, N, n_head, 1]
|
1208 |
+
struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
|
1209 |
+
|
1210 |
+
// KQV_merged = KQV.permute(0, 2, 1, 3)
|
1211 |
+
// KQV_merged shape [n_embd/n_head, n_head, N, 1]
|
1212 |
+
struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
|
1213 |
+
// KQV_merged shape
|
1214 |
+
|
1215 |
+
// cur = KQV_merged.contiguous().view(n_embd, N)
|
1216 |
+
// cur shape [n_embd,N,1,1]
|
1217 |
+
cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
|
1218 |
+
// cur = ggml_cpy(ctx0,
|
1219 |
+
// KQV_merged,
|
1220 |
+
// ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
|
1221 |
+
|
1222 |
+
// projection (no bias)
|
1223 |
+
// cur shape [n_embd,N,1,1]
|
1224 |
+
cur = ggml_mul_mat(ctx0,
|
1225 |
+
model->layers[il].woa,
|
1226 |
+
ggml_mul_mat(ctx0,
|
1227 |
+
model->layers[il].wob,
|
1228 |
+
cur));
|
1229 |
+
}
|
1230 |
+
|
1231 |
+
// inpFF shape [n_embd,N,1,1]
|
1232 |
+
struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
|
1233 |
+
|
1234 |
+
// feed-forward network
|
1235 |
+
{
|
1236 |
+
// norm
|
1237 |
+
{
|
1238 |
+
// cur shape [n_embd,N,1,1]
|
1239 |
+
cur = ggml_rms_norm(ctx0, inpFF);
|
1240 |
+
|
1241 |
+
// cur = ffn_norm*cur
|
1242 |
+
// cur shape [n_embd,N,1,1]
|
1243 |
+
cur = ggml_mul(ctx0,
|
1244 |
+
ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
|
1245 |
+
cur);
|
1246 |
+
}
|
1247 |
+
|
1248 |
+
// tmp shape [n_ff,N,1,1]
|
1249 |
+
struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
|
1250 |
+
model->layers[il].w3,
|
1251 |
+
cur);
|
1252 |
+
|
1253 |
+
// cur shape [n_ff,N,1,1]
|
1254 |
+
cur = ggml_mul_mat(ctx0,
|
1255 |
+
model->layers[il].w1,
|
1256 |
+
cur);
|
1257 |
+
|
1258 |
+
// SILU activation
|
1259 |
+
// cur shape [n_ff,N,1,1]
|
1260 |
+
cur = ggml_silu(ctx0, cur);
|
1261 |
+
|
1262 |
+
// cur shape [n_ff,N,1,1]
|
1263 |
+
cur = ggml_mul(ctx0, cur, tmp);
|
1264 |
+
|
1265 |
+
// cur shape [n_embd,N,1,1]
|
1266 |
+
cur = ggml_mul_mat(ctx0,
|
1267 |
+
model->layers[il].w2,
|
1268 |
+
cur);
|
1269 |
+
}
|
1270 |
+
|
1271 |
+
// cur shape [n_embd,N,1,1]
|
1272 |
+
cur = ggml_add(ctx0, cur, inpFF);
|
1273 |
+
|
1274 |
+
// input for next layer
|
1275 |
+
// inpL shape [n_embd,N,1,1]
|
1276 |
+
inpL = cur;
|
1277 |
+
}
|
1278 |
+
|
1279 |
+
// norm
|
1280 |
+
{
|
1281 |
+
|
1282 |
+
// inpL shape [n_embd,N,1,1]
|
1283 |
+
inpL = ggml_rms_norm(ctx0, inpL);
|
1284 |
+
|
1285 |
+
// inpL = norm*inpL
|
1286 |
+
// inpL shape [n_embd,N,1,1]
|
1287 |
+
inpL = ggml_mul(ctx0,
|
1288 |
+
ggml_repeat(ctx0, model->norm, inpL),
|
1289 |
+
inpL);
|
1290 |
+
|
1291 |
+
//embeddings = inpL;
|
1292 |
+
}
|
1293 |
+
|
1294 |
+
|
1295 |
+
// lm_head
|
1296 |
+
// inpL shape [n_vocab,N,1,1]
|
1297 |
+
inpL = ggml_mul_mat(ctx0,
|
1298 |
+
model->outputa,
|
1299 |
+
ggml_mul_mat(ctx0,
|
1300 |
+
model->outputb,
|
1301 |
+
inpL));
|
1302 |
+
|
1303 |
+
// ggml_set_scratch(ctx0, { 0, 0, nullptr, });
|
1304 |
+
// run the computation
|
1305 |
+
ggml_build_forward_expand(gf, inpL);
|
1306 |
+
|
1307 |
+
return inpL;
|
1308 |
+
}
|
1309 |
+
|
1310 |
+
void sample_softmax(struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
|
1311 |
+
assert(logits->n_dims == 2);
|
1312 |
+
assert(probs->n_dims == 2);
|
1313 |
+
assert(best_samples->n_dims == 1);
|
1314 |
+
assert(logits->ne[1] == best_samples->ne[0]);
|
1315 |
+
assert(logits->ne[0] == probs->ne[0]);
|
1316 |
+
assert(logits->ne[1] == probs->ne[1]);
|
1317 |
+
for (int i = 0; i < logits->ne[1]; ++i) {
|
1318 |
+
float max_logit = ggml_get_f32_1d(logits, i * logits->ne[0]);
|
1319 |
+
ggml_set_i32_1d(best_samples, i, 0);
|
1320 |
+
for (int k = 0; k < logits->ne[0]; ++k) {
|
1321 |
+
float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
|
1322 |
+
if (logit > max_logit) {
|
1323 |
+
max_logit = logit;
|
1324 |
+
ggml_set_i32_1d(best_samples, i, k);
|
1325 |
+
}
|
1326 |
+
}
|
1327 |
+
float psum = 0;
|
1328 |
+
for (int k = 0; k < logits->ne[0]; ++k) {
|
1329 |
+
float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
|
1330 |
+
float p = (logit == -INFINITY) ? 0 : expf(logit - max_logit);
|
1331 |
+
psum += p;
|
1332 |
+
ggml_set_f32_1d(probs, i * probs->ne[0] + k, p);
|
1333 |
+
}
|
1334 |
+
for (int k = 0; k < logits->ne[0]; ++k) {
|
1335 |
+
float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
|
1336 |
+
ggml_set_f32_1d(probs, i * probs->ne[0] + k, p / psum);
|
1337 |
+
}
|
1338 |
+
}
|
1339 |
+
}
|
1340 |
+
|
1341 |
+
void sample_softmax_batch(struct ggml_context * ctx, struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
|
1342 |
+
GGML_ASSERT(best_samples->n_dims == 2);
|
1343 |
+
GGML_ASSERT(logits->n_dims == 3);
|
1344 |
+
GGML_ASSERT(probs->n_dims == 3);
|
1345 |
+
int n_tokens = best_samples->ne[0];
|
1346 |
+
int n_batch = best_samples->ne[1];
|
1347 |
+
int n_vocab = logits->ne[0];
|
1348 |
+
GGML_ASSERT(n_tokens == logits->ne[1]);
|
1349 |
+
GGML_ASSERT(n_batch == logits->ne[2]);
|
1350 |
+
GGML_ASSERT(n_vocab == probs->ne[0]);
|
1351 |
+
GGML_ASSERT(n_tokens == probs->ne[1]);
|
1352 |
+
GGML_ASSERT(n_batch == probs->ne[2]);
|
1353 |
+
|
1354 |
+
for (int k = 0; k < n_batch; ++k) {
|
1355 |
+
struct ggml_tensor * best_samples_k = ggml_view_1d(ctx,
|
1356 |
+
best_samples,
|
1357 |
+
best_samples->ne[0],
|
1358 |
+
k*best_samples->nb[1]);
|
1359 |
+
struct ggml_tensor * logits_k = ggml_view_2d(ctx,
|
1360 |
+
logits,
|
1361 |
+
logits->ne[0],
|
1362 |
+
logits->ne[1],
|
1363 |
+
logits->nb[1],
|
1364 |
+
k*logits->nb[2]);
|
1365 |
+
struct ggml_tensor * probs_k = ggml_view_2d(ctx,
|
1366 |
+
probs,
|
1367 |
+
probs->ne[0],
|
1368 |
+
probs->ne[1],
|
1369 |
+
probs->nb[1],
|
1370 |
+
k*probs->nb[2]);
|
1371 |
+
sample_softmax(logits_k, probs_k, best_samples_k);
|
1372 |
+
}
|
1373 |
+
}
|
1374 |
+
|
1375 |
+
void print_row(struct ggml_tensor * probs, int i) {
|
1376 |
+
for (int k = 0; k < probs->ne[0]; ++k) {
|
1377 |
+
float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
|
1378 |
+
printf(" %.2f", p);
|
1379 |
+
}
|
1380 |
+
printf("\n");
|
1381 |
+
}
|
1382 |
+
|
1383 |
+
void print_matrix(struct ggml_tensor * probs) {
|
1384 |
+
assert(probs->n_dims == 2);
|
1385 |
+
for (int i = 0; i < probs->ne[1]; ++i) {
|
1386 |
+
for (int k = 0; k < probs->ne[0]; ++k) {
|
1387 |
+
float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
|
1388 |
+
printf(" %.2f", p);
|
1389 |
+
}
|
1390 |
+
printf("\n");
|
1391 |
+
}
|
1392 |
+
}
|
1393 |
+
|
1394 |
+
void print_token(int token, int n_vocab) {
|
1395 |
+
for (int k = 0; k < token; ++k) {
|
1396 |
+
printf(" ");
|
1397 |
+
}
|
1398 |
+
printf("X");
|
1399 |
+
for (int k = token+1; k < n_vocab; ++k) {
|
1400 |
+
printf(" ");
|
1401 |
+
}
|
1402 |
+
printf("\n");
|
1403 |
+
}
|
1404 |
+
|
1405 |
+
void print_tokens(struct ggml_tensor * tokens, int n_vocab) {
|
1406 |
+
for (int i=0; i<tokens->ne[0]; ++i) {
|
1407 |
+
int token = ggml_get_i32_1d(tokens, i);
|
1408 |
+
print_token(token, n_vocab);
|
1409 |
+
}
|
1410 |
+
}
|
1411 |
+
|
1412 |
+
void get_example_targets(int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
|
1413 |
+
int n_tokens = tokens_input->ne[0];
|
1414 |
+
int n_vocab = targets->ne[0];
|
1415 |
+
float randomness = 0.0f;
|
1416 |
+
// ggml_set_zero(targets);
|
1417 |
+
ggml_set_f32(targets, -1.0f);
|
1418 |
+
ggml_set_i32_1d(tokens_input, 0, 0);
|
1419 |
+
for (int i=1; i<n_tokens+1; ++i) {
|
1420 |
+
float x = example_id + i * 3.14159f * 2.0f * 1.0f * 0.5f / n_tokens;
|
1421 |
+
float y = sinf(x);//*cosf(x*1.1f+1.0f);
|
1422 |
+
float z = (y+1.0f)*0.5f; // scale to [0..1]
|
1423 |
+
z += (frand()-0.5f)*(randomness/n_vocab);
|
1424 |
+
z = (z < 0.0f) ? 0.0f : (z > 1.0f) ? 1.0f : z; // clamp to [0..1]
|
1425 |
+
int token = std::max(1,std::min(1+(int)(z*(float)(n_vocab-1)), n_vocab-1));
|
1426 |
+
ggml_set_f32_1d(targets, (i-1)*n_vocab + token, +1.0f);
|
1427 |
+
if (i<n_tokens) {
|
1428 |
+
ggml_set_i32_1d(tokens_input, i, token);
|
1429 |
+
}
|
1430 |
+
}
|
1431 |
+
}
|
1432 |
+
|
1433 |
+
void get_example_targets_batch(struct ggml_context * ctx, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
|
1434 |
+
GGML_ASSERT(tokens_input->n_dims == 2);
|
1435 |
+
GGML_ASSERT( targets->n_dims == 3);
|
1436 |
+
int n_tokens = tokens_input->ne[0];
|
1437 |
+
int n_batch = tokens_input->ne[1];
|
1438 |
+
GGML_ASSERT(n_tokens == targets->ne[1]);
|
1439 |
+
GGML_ASSERT(n_batch == targets->ne[2]);
|
1440 |
+
|
1441 |
+
for (int k=0; k<n_batch; ++k) {
|
1442 |
+
struct ggml_tensor * tokens_input_k = ggml_view_1d(ctx,
|
1443 |
+
tokens_input,
|
1444 |
+
tokens_input->ne[0],
|
1445 |
+
k*tokens_input->nb[1]);
|
1446 |
+
struct ggml_tensor * targets_k = ggml_view_2d(ctx,
|
1447 |
+
targets,
|
1448 |
+
targets->ne[0],
|
1449 |
+
targets->ne[1],
|
1450 |
+
targets->nb[1],
|
1451 |
+
k*targets->nb[2]);
|
1452 |
+
get_example_targets(example_id*n_batch + k, tokens_input_k, targets_k);
|
1453 |
+
}
|
1454 |
+
}
|
1455 |
+
|
1456 |
+
void lshift_examples(struct ggml_tensor * tokens_input, struct ggml_tensor * targets, int n_shift) {
|
1457 |
+
int n_tokens = tokens_input->ne[0];
|
1458 |
+
int n_vocab = targets->ne[0];
|
1459 |
+
for (int i=0; i<n_tokens-n_shift; ++i) {
|
1460 |
+
ggml_set_i32_1d(tokens_input, i, ggml_get_i32_1d(tokens_input, i + n_shift));
|
1461 |
+
for (int k=0; k<n_vocab; ++k) {
|
1462 |
+
ggml_set_f32_1d(targets, i*n_vocab + k, ggml_get_f32_1d(targets, (i + n_shift)*n_vocab + k));
|
1463 |
+
}
|
1464 |
+
}
|
1465 |
+
}
|
1466 |
+
|
1467 |
+
struct ggml_tensor * square_error_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b) {
|
1468 |
+
// todo: instead of a-b: a[1:]-b[:-1]
|
1469 |
+
return ggml_sum(ctx, ggml_sqr(ctx, ggml_sub(ctx, a, b)));
|
1470 |
+
}
|
1471 |
+
|
1472 |
+
struct ggml_tensor * cross_entropy_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b) {
|
1473 |
+
const float eps = 1e-3;
|
1474 |
+
return
|
1475 |
+
ggml_sum(ctx,
|
1476 |
+
ggml_neg(ctx,
|
1477 |
+
ggml_sum_rows(ctx,
|
1478 |
+
ggml_mul(ctx,
|
1479 |
+
ggml_soft_max(ctx, a),
|
1480 |
+
ggml_log(ctx,
|
1481 |
+
ggml_add1(ctx,
|
1482 |
+
ggml_soft_max(ctx, b),
|
1483 |
+
ggml_new_f32(ctx, eps)))))));
|
1484 |
+
}
|
1485 |
+
|
1486 |
+
int main(int argc, char ** argv) {
|
1487 |
+
if (argc < 1) {
|
1488 |
+
fprintf(stderr, "usage: %s\n", argv[0]);
|
1489 |
+
|
1490 |
+
return 1;
|
1491 |
+
}
|
1492 |
+
|
1493 |
+
struct ggml_init_params lcparams;
|
1494 |
+
lcparams.mem_size = 1024ll*1024ll*1024ll;
|
1495 |
+
lcparams.mem_buffer = NULL;
|
1496 |
+
lcparams.no_alloc = false;
|
1497 |
+
|
1498 |
+
struct llama_model model;
|
1499 |
+
model.hparams.n_vocab = 8;
|
1500 |
+
model.hparams.n_ctx = 8;
|
1501 |
+
model.hparams.n_embd = 32;
|
1502 |
+
model.hparams.n_mult = 2;
|
1503 |
+
model.hparams.n_head = 8;
|
1504 |
+
model.hparams.n_layer = 1;
|
1505 |
+
model.hparams.n_rot = std::min(16u, model.hparams.n_embd / model.hparams.n_head);
|
1506 |
+
|
1507 |
+
// model.hparams.n_embd = 32;
|
1508 |
+
// model.hparams.n_mult = 2;
|
1509 |
+
// model.hparams.n_head = 4;
|
1510 |
+
// model.hparams.n_layer = 8;
|
1511 |
+
// model.hparams.n_rot = 8;
|
1512 |
+
|
1513 |
+
model.ctx = ggml_init(lcparams);
|
1514 |
+
printf("init model\n");
|
1515 |
+
init_model(&model);
|
1516 |
+
set_param_model(&model);
|
1517 |
+
|
1518 |
+
randomize_model(&model, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
|
1519 |
+
|
1520 |
+
/*
|
1521 |
+
struct llama_model_lora model_lora;
|
1522 |
+
// model.hparams.n_vocab = 6;
|
1523 |
+
// model.hparams.n_ctx = 64;
|
1524 |
+
// model.hparams.n_embd = 128;
|
1525 |
+
// model.hparams.n_mult = 2;
|
1526 |
+
// model.hparams.n_head = 8;
|
1527 |
+
// model.hparams.n_layer = 6;
|
1528 |
+
// model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
|
1529 |
+
|
1530 |
+
model_lora.hparams.n_vocab = 16;
|
1531 |
+
model_lora.hparams.n_ctx = 32;
|
1532 |
+
model_lora.hparams.n_embd = 256;
|
1533 |
+
model_lora.hparams.n_mult = 2;
|
1534 |
+
model_lora.hparams.n_head = 16;
|
1535 |
+
model_lora.hparams.n_layer = 1;
|
1536 |
+
model_lora.hparams.n_lora = 64;
|
1537 |
+
model_lora.hparams.n_rot = MIN(16, model_lora.hparams.n_embd / model_lora.hparams.n_head);
|
1538 |
+
// model.hparams.n_rot = (model.hparams.n_embd / model.hparams.n_head) / 2;
|
1539 |
+
|
1540 |
+
// model.hparams.n_embd = 32;
|
1541 |
+
// model.hparams.n_mult = 2;
|
1542 |
+
// model.hparams.n_head = 4;
|
1543 |
+
// model.hparams.n_layer = 8;
|
1544 |
+
// model.hparams.n_rot = 8;
|
1545 |
+
|
1546 |
+
model_lora.ctx = ggml_init(lcparams);
|
1547 |
+
printf("init model_lora\n");
|
1548 |
+
init_model_lora(&model_lora);
|
1549 |
+
set_param_model_lora(&model_lora);
|
1550 |
+
|
1551 |
+
randomize_model_lora(&model_lora, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
|
1552 |
+
*/
|
1553 |
+
int n_batch = 8;
|
1554 |
+
// key + value cache for the self attention
|
1555 |
+
struct llama_kv_cache kv_self;
|
1556 |
+
printf("init_kv_cache\n");
|
1557 |
+
kv_self.ctx = model.ctx;
|
1558 |
+
init_kv_cache(&kv_self, &model, n_batch);
|
1559 |
+
//init_kv_cache_lora(&kv_self, &model_lora);
|
1560 |
+
|
1561 |
+
size_t compute_size = 1024ll*1024ll*1024ll;
|
1562 |
+
uint8_t * compute_addr = new uint8_t[compute_size];
|
1563 |
+
|
1564 |
+
int n_examples = 256;
|
1565 |
+
int n_tokens = model.hparams.n_ctx;
|
1566 |
+
int n_vocab = model.hparams.n_vocab;
|
1567 |
+
|
1568 |
+
for (int ex=0; ex<n_examples; ++ex) {
|
1569 |
+
struct ggml_init_params params = {
|
1570 |
+
/*.mem_size =*/ compute_size,
|
1571 |
+
/*.mem_buffer =*/ compute_addr,
|
1572 |
+
/*.no_alloc =*/ false,
|
1573 |
+
};
|
1574 |
+
|
1575 |
+
struct ggml_context * ctx0 = ggml_init(params);
|
1576 |
+
|
1577 |
+
struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
|
1578 |
+
struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
|
1579 |
+
struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
|
1580 |
+
struct ggml_tensor * targets = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
|
1581 |
+
|
1582 |
+
int n_past = 0;
|
1583 |
+
|
1584 |
+
ggml_cgraph gf = {};
|
1585 |
+
gf.n_threads = 1;
|
1586 |
+
|
1587 |
+
get_example_targets_batch(ctx0, 64*ex+0, tokens_input, targets);
|
1588 |
+
|
1589 |
+
struct ggml_tensor * logits = forward_batch(&model, &kv_self, ctx0, &gf, tokens_input, n_tokens, n_past, n_batch);
|
1590 |
+
// struct ggml_tensor * e = cross_entropy_loss(ctx0, targets, logits);
|
1591 |
+
struct ggml_tensor * e = square_error_loss(ctx0, targets, logits);
|
1592 |
+
|
1593 |
+
ggml_build_forward_expand(&gf, e);
|
1594 |
+
ggml_graph_compute(ctx0, &gf);
|
1595 |
+
|
1596 |
+
float error_before_opt = ggml_get_f32_1d(e, 0);
|
1597 |
+
|
1598 |
+
struct ggml_opt_params opt_params_adam = ggml_opt_default_params(GGML_OPT_ADAM);
|
1599 |
+
struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_LBFGS);
|
1600 |
+
opt_params_adam.print_forward_graph = false;
|
1601 |
+
opt_params_adam.print_backward_graph = false;
|
1602 |
+
opt_params_lbfgs.print_forward_graph = false;
|
1603 |
+
opt_params_lbfgs.print_backward_graph = false;
|
1604 |
+
opt_params_adam.adam.n_iter = 16;
|
1605 |
+
opt_params_lbfgs.lbfgs.n_iter = 16;
|
1606 |
+
// ggml_opt(ctx0, opt_params_adam, e);
|
1607 |
+
ggml_opt(ctx0, opt_params_lbfgs, e);
|
1608 |
+
//
|
1609 |
+
ggml_build_forward_expand(&gf, e);
|
1610 |
+
ggml_graph_compute(ctx0, &gf);
|
1611 |
+
|
1612 |
+
float error_after_opt = ggml_get_f32_1d(e, 0);
|
1613 |
+
|
1614 |
+
if (ex % 8 == 0) {
|
1615 |
+
printf("Example %d\n", (ex+1));
|
1616 |
+
printf("error_before_opt: %.2f\n", error_before_opt);
|
1617 |
+
printf("error_after_opt: %.2f\n", error_after_opt);
|
1618 |
+
}
|
1619 |
+
|
1620 |
+
if (ex % 64 == 0) {
|
1621 |
+
sample_softmax_batch(ctx0, logits, after_opt_probs, after_opt_best_samples);
|
1622 |
+
// printf("probabilities after optimization:\n");
|
1623 |
+
// print_matrix(after_opt_probs);
|
1624 |
+
printf("best samples after optimization:\n");
|
1625 |
+
print_tokens(after_opt_best_samples, n_vocab);
|
1626 |
+
}
|
1627 |
+
|
1628 |
+
ggml_free(ctx0);
|
1629 |
+
}
|
1630 |
+
|
1631 |
+
{
|
1632 |
+
int n_gen = 128;
|
1633 |
+
int sample_ctx = n_tokens-n_tokens/8;
|
1634 |
+
|
1635 |
+
printf("Generating %d tokens.\n", n_gen);
|
1636 |
+
|
1637 |
+
struct ggml_tensor * tokens_input = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, n_tokens);
|
1638 |
+
struct ggml_tensor * targets = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, n_vocab, n_tokens);
|
1639 |
+
|
1640 |
+
get_example_targets(137, tokens_input, targets);
|
1641 |
+
for (int i=sample_ctx; i<n_tokens; ++i) {
|
1642 |
+
ggml_set_i32_1d(tokens_input, i, n_vocab/2);
|
1643 |
+
}
|
1644 |
+
|
1645 |
+
for (int i=0; i<sample_ctx-1; ++i) {
|
1646 |
+
print_token(ggml_get_i32_1d(tokens_input, i), n_vocab);
|
1647 |
+
}
|
1648 |
+
printf("---\n");
|
1649 |
+
for (int i=0; i<n_gen; ++i) {
|
1650 |
+
struct ggml_init_params params = {
|
1651 |
+
/*.mem_size =*/ compute_size,
|
1652 |
+
/*.mem_buffer =*/ compute_addr,
|
1653 |
+
/*.no_alloc =*/ false,
|
1654 |
+
};
|
1655 |
+
struct ggml_context * ctx0 = ggml_init(params);
|
1656 |
+
|
1657 |
+
ggml_cgraph gf = {};
|
1658 |
+
gf.n_threads = 1;
|
1659 |
+
|
1660 |
+
int n_past = 0;
|
1661 |
+
struct ggml_tensor * logits = forward(&model, &kv_self, ctx0, &gf, tokens_input, sample_ctx, n_past);
|
1662 |
+
|
1663 |
+
ggml_build_forward_expand(&gf, logits);
|
1664 |
+
ggml_graph_compute(ctx0, &gf);
|
1665 |
+
|
1666 |
+
struct ggml_tensor * best_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sample_ctx);
|
1667 |
+
struct ggml_tensor * probs = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab, sample_ctx);
|
1668 |
+
|
1669 |
+
sample_softmax(logits, probs, best_samples);
|
1670 |
+
|
1671 |
+
// int sample_at = n_tokens-1;
|
1672 |
+
int token = ggml_get_i32_1d(best_samples, sample_ctx-1);
|
1673 |
+
|
1674 |
+
// print_row(probs, sample_at);
|
1675 |
+
print_token(token, n_vocab);
|
1676 |
+
|
1677 |
+
lshift_examples(tokens_input, targets, 1);
|
1678 |
+
ggml_set_i32_1d(tokens_input, 0, 0);
|
1679 |
+
ggml_set_i32_1d(tokens_input, sample_ctx-1, token);
|
1680 |
+
|
1681 |
+
ggml_free(ctx0);
|
1682 |
+
}
|
1683 |
+
}
|
1684 |
+
|
1685 |
+
print_matrix(model.tok_embeddings);
|
1686 |
+
|
1687 |
+
printf("done\n");
|
1688 |
+
// ggml_free(kv_self.ctx);
|
1689 |
+
// ggml_free(model_lora.ctx);
|
1690 |
+
ggml_free(model.ctx);
|
1691 |
+
return 0;
|
1692 |
+
}
|
examples/benchmark/CMakeLists.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set(TARGET benchmark)
|
2 |
+
add_executable(${TARGET} benchmark-matmult.cpp)
|
3 |
+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
|
4 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_11)
|
5 |
+
if(TARGET BUILD_INFO)
|
6 |
+
add_dependencies(${TARGET} BUILD_INFO)
|
7 |
+
endif()
|
examples/benchmark/benchmark-matmult.cpp
ADDED
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "ggml.h"
|
2 |
+
#include "build-info.h"
|
3 |
+
|
4 |
+
#include <locale.h>
|
5 |
+
#include <assert.h>
|
6 |
+
#include <math.h>
|
7 |
+
#include <cstring>
|
8 |
+
#include <cstdio>
|
9 |
+
#include <cinttypes>
|
10 |
+
#include <unordered_map>
|
11 |
+
#include <queue>
|
12 |
+
#include <string.h>
|
13 |
+
#include <cassert>
|
14 |
+
#include <fstream>
|
15 |
+
#include <string>
|
16 |
+
#include <iterator>
|
17 |
+
#include <algorithm>
|
18 |
+
|
19 |
+
float tensor_sum_elements(const ggml_tensor * tensor) {
|
20 |
+
float sum = 0;
|
21 |
+
if (tensor->type==GGML_TYPE_F32) {
|
22 |
+
for (int j = 0; j < tensor->ne[1]; j++) {
|
23 |
+
for (int k = 0; k < tensor->ne[0]; k++) {
|
24 |
+
sum += ((float *) tensor->data)[j*tensor->ne[0]+k];
|
25 |
+
}
|
26 |
+
}
|
27 |
+
}
|
28 |
+
return sum;
|
29 |
+
}
|
30 |
+
|
31 |
+
void tensor_dump(const ggml_tensor * tensor, const char * name) {
|
32 |
+
printf("%15s: type = %i (%5s) ne = %5d x %5d x %5d, nb = (%5li, %5li, %5li) - ", name,
|
33 |
+
tensor->type, ggml_type_name(tensor->type),
|
34 |
+
(int) tensor->ne[0], (int) tensor->ne[1], (int) tensor->ne[2], tensor->nb[0], tensor->nb[1], tensor->nb[2]);
|
35 |
+
float sum = tensor_sum_elements(tensor);
|
36 |
+
printf("Sum of tensor %s is %6.2f\n", name, sum);
|
37 |
+
}
|
38 |
+
|
39 |
+
#define TENSOR_DUMP(tensor) tensor_dump(tensor, #tensor)
|
40 |
+
|
41 |
+
struct benchmark_params_struct {
|
42 |
+
int32_t n_threads = 1;
|
43 |
+
int32_t n_iterations = 10;
|
44 |
+
};
|
45 |
+
|
46 |
+
void print_usage(int /*argc*/, char ** argv, struct benchmark_params_struct params) {
|
47 |
+
fprintf(stderr, "usage: %s [options]\n", argv[0]);
|
48 |
+
fprintf(stderr, "\n");
|
49 |
+
fprintf(stderr, "options:\n");
|
50 |
+
fprintf(stderr, " -h, --help show this help message and exit\n");
|
51 |
+
fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
|
52 |
+
fprintf(stderr, " -i N, --iter N number of iterations to use during computation (default: %d)\n", params.n_iterations);
|
53 |
+
fprintf(stderr, "\n");
|
54 |
+
}
|
55 |
+
|
56 |
+
int main(int argc, char ** argv) {
|
57 |
+
struct benchmark_params_struct benchmark_params;
|
58 |
+
|
59 |
+
bool invalid_param = false;
|
60 |
+
std::string arg;
|
61 |
+
for (int i = 1; i < argc; i++) {
|
62 |
+
arg = argv[i];
|
63 |
+
|
64 |
+
if (arg == "-t" || arg == "--threads") {
|
65 |
+
if (++i >= argc) {
|
66 |
+
invalid_param = true;
|
67 |
+
break;
|
68 |
+
}
|
69 |
+
benchmark_params.n_threads = std::stoi(argv[i]);
|
70 |
+
} else if (arg == "-i" || arg == "--iter") {
|
71 |
+
if (++i >= argc) {
|
72 |
+
invalid_param = true;
|
73 |
+
break;
|
74 |
+
}
|
75 |
+
benchmark_params.n_iterations = std::stoi(argv[i]);
|
76 |
+
} else if (arg == "-h" || arg == "--help") {
|
77 |
+
print_usage(argc, argv, benchmark_params);
|
78 |
+
exit(0);
|
79 |
+
}
|
80 |
+
}
|
81 |
+
if (invalid_param) {
|
82 |
+
fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
|
83 |
+
print_usage(argc, argv, benchmark_params);
|
84 |
+
exit(1);
|
85 |
+
}
|
86 |
+
|
87 |
+
fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
|
88 |
+
printf("Starting Test\n");
|
89 |
+
|
90 |
+
// create the ggml context
|
91 |
+
struct ggml_context * ctx;
|
92 |
+
//const int sizex = 4096;
|
93 |
+
//const int sizey = 11008;
|
94 |
+
|
95 |
+
#undef VERBOSE_DEBUGGING
|
96 |
+
#ifndef VERBOSE_DEBUGGING
|
97 |
+
const int sizey = 4096;
|
98 |
+
const int sizex = 11008;
|
99 |
+
const int sizez = 128;
|
100 |
+
#else
|
101 |
+
/* Working - let's increase size */
|
102 |
+
const int sizey = 1;
|
103 |
+
const int sizex = (8*32);
|
104 |
+
const int sizez = 1;
|
105 |
+
|
106 |
+
/*const int sizey = 1;
|
107 |
+
const int sizex = 3*(8*32);
|
108 |
+
const int sizez = 1;*/
|
109 |
+
#endif
|
110 |
+
|
111 |
+
//printf("Memsize required = %i\n", sizex*sizex);
|
112 |
+
|
113 |
+
size_t ctx_size = 0;
|
114 |
+
ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32);
|
115 |
+
ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32);
|
116 |
+
ctx_size += sizex*sizez*ggml_type_sizef(GGML_TYPE_F32);
|
117 |
+
ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_Q4_0);
|
118 |
+
ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_Q4_0);
|
119 |
+
ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32); // BLAS
|
120 |
+
ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32); // BLAS
|
121 |
+
ctx_size += 1024*1024*16;
|
122 |
+
|
123 |
+
printf("Allocating Memory of size %li bytes, %li MB\n",ctx_size, (ctx_size/1024/1024));
|
124 |
+
|
125 |
+
struct ggml_init_params params = {
|
126 |
+
/*.mem_size =*/ ctx_size,
|
127 |
+
/*.mem_buffer =*/ NULL,
|
128 |
+
/* no_alloc =*/ 0
|
129 |
+
};
|
130 |
+
|
131 |
+
ctx = ggml_init(params);
|
132 |
+
if (!ctx) {
|
133 |
+
fprintf(stderr, "%s: ggml_init() failed\n", __func__);
|
134 |
+
return 1;
|
135 |
+
}
|
136 |
+
|
137 |
+
|
138 |
+
printf("Creating new tensors\n");
|
139 |
+
// printf("Creating new tensor m1\n");
|
140 |
+
struct ggml_tensor * m11 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizey);
|
141 |
+
ggml_set_f32(m11, 1.0f);
|
142 |
+
|
143 |
+
// printf("Creating new tensor m1\n");
|
144 |
+
struct ggml_tensor * m12 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizey);
|
145 |
+
ggml_set_f32(m12, 1.5f);
|
146 |
+
|
147 |
+
// printf("Creating new tensor m2\n");
|
148 |
+
struct ggml_tensor * m2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizez);
|
149 |
+
ggml_set_f32(m2, 2.0f);
|
150 |
+
|
151 |
+
printf("\n------ Test 1 - Matrix Mult via F32 code ------------------------------------------------------------------------------\n");
|
152 |
+
// printf("Creating new tensor m11xm2\n");
|
153 |
+
struct ggml_tensor * m11xm2 = ggml_mul_mat(ctx, m11, m2);
|
154 |
+
|
155 |
+
// printf("Creating compute graph\n");
|
156 |
+
struct ggml_cgraph gf = ggml_build_forward(m11xm2);
|
157 |
+
|
158 |
+
gf.n_threads=benchmark_params.n_threads;
|
159 |
+
printf("cgraph->n_threads=%i\n",gf.n_threads);
|
160 |
+
|
161 |
+
TENSOR_DUMP(m11);
|
162 |
+
TENSOR_DUMP(m2);
|
163 |
+
|
164 |
+
ggml_graph_compute(ctx, &gf);
|
165 |
+
|
166 |
+
TENSOR_DUMP(gf.nodes[0]);
|
167 |
+
|
168 |
+
printf("\n------ Test 2 - Matrix Mult via Q4_0 code ------------------------------------------------------------------------------\n");
|
169 |
+
|
170 |
+
int32_t nelements = sizex*sizey;
|
171 |
+
int32_t ne[2] = { sizex, sizey };
|
172 |
+
|
173 |
+
std::vector<int64_t> hist_cur(1 << 4, 0);
|
174 |
+
|
175 |
+
// Set up a the benchmark matrices
|
176 |
+
// printf("Creating new tensor q11 & Running quantize\n");
|
177 |
+
struct ggml_tensor * q11 = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, sizex, sizey);
|
178 |
+
ggml_quantize_q4_0((const float *) m11->data, q11->data, nelements, ne[0], hist_cur.data());
|
179 |
+
|
180 |
+
// Set up a the compute graph
|
181 |
+
// printf("Creating new tensor q31\n");
|
182 |
+
struct ggml_tensor * q31 = ggml_mul_mat(ctx, q11, m2);
|
183 |
+
|
184 |
+
// printf("Creating compute graph\n");
|
185 |
+
struct ggml_cgraph gf31 = ggml_build_forward(q31);
|
186 |
+
gf31.n_threads=benchmark_params.n_threads;
|
187 |
+
|
188 |
+
// Set up a second graph computation to make sure we override the CPU cache lines
|
189 |
+
// printf("Creating new tensor q12 & Running quantize\n");
|
190 |
+
struct ggml_tensor * q12 = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, sizex, sizey);
|
191 |
+
ggml_quantize_q4_0((const float *) m12->data, q12->data, nelements, ne[0], hist_cur.data());
|
192 |
+
|
193 |
+
// printf("Creating new tensor q32\n");
|
194 |
+
struct ggml_tensor * q32 = ggml_mul_mat(ctx, q12, m2);
|
195 |
+
|
196 |
+
//printf("Creating compute graph\n");
|
197 |
+
struct ggml_cgraph gf32 = ggml_build_forward(q32);
|
198 |
+
gf32.n_threads=benchmark_params.n_threads;
|
199 |
+
printf("cgraph->n_threads=%i\n",gf31.n_threads);
|
200 |
+
|
201 |
+
const int dimx = sizex;
|
202 |
+
const int dimy = sizey;
|
203 |
+
const int dimz = sizez;
|
204 |
+
long long int flops_per_dot_product = dimy + dimy;
|
205 |
+
long long int flops_per_matrix = flops_per_dot_product * dimx * dimz; ;
|
206 |
+
printf("Matrix Multiplication of (%i,%i,%i) x (%i,%i,%i) - about %6.2f gFLOPS\n\n", sizex, sizey, 1, sizex, sizez, 1, 1.0f*flops_per_matrix / 1000 / 1000 / 1000);
|
207 |
+
|
208 |
+
|
209 |
+
// Let's use the F32 result from above as a reference for the q4_0 multiplication
|
210 |
+
float sum_of_F32_reference = tensor_sum_elements(gf.nodes[0]);
|
211 |
+
|
212 |
+
printf("Iteration;NThreads; SizeX; SizeY; SizeZ; Required_FLOPS; Elapsed_u_Seconds; gigaFLOPS\n");
|
213 |
+
printf("=====================================================================================\n");
|
214 |
+
|
215 |
+
double gflops_sum = 0;
|
216 |
+
for (int i=0;i<benchmark_params.n_iterations ;i++) {
|
217 |
+
|
218 |
+
long long int start = ggml_time_us();
|
219 |
+
//printf("Running ggml_graph_compute\n");
|
220 |
+
ggml_graph_compute(ctx, &gf31);
|
221 |
+
long long int stop = ggml_time_us();
|
222 |
+
long long int usec = stop-start;
|
223 |
+
double gflops = (double)(flops_per_matrix)/usec/1000.0;
|
224 |
+
gflops_sum += gflops;
|
225 |
+
printf("%9i;%8i;%6i;%6i;%6i;%15lli;%18lli;%10.2f\n",
|
226 |
+
i,
|
227 |
+
gf31.n_threads,
|
228 |
+
sizex, sizey, sizez, flops_per_matrix,
|
229 |
+
usec,gflops);
|
230 |
+
|
231 |
+
#ifdef VERBOSE_DEBUGGING
|
232 |
+
TENSOR_DUMP("res",gf31.nodes[0])
|
233 |
+
#endif
|
234 |
+
|
235 |
+
// Check that the matrix multiplication result is in the right ballpark
|
236 |
+
// We cannot use the exact value from the F32 multiplication because the quantizuation will be slightly different
|
237 |
+
float sum_of_Q4_result = tensor_sum_elements(gf31.nodes[0]);
|
238 |
+
float delta = abs(sum_of_Q4_result - sum_of_F32_reference);
|
239 |
+
float allowed_delta = (sum_of_F32_reference) / 1000 / 1000; // Let's accept an epsilon of 10^-6
|
240 |
+
|
241 |
+
if (delta > allowed_delta) {
|
242 |
+
printf("\nABORT - ERROR in Matrix Multiplication result - expected %6.2f, got %6.2f (delta %6.2f > allowed_delta %6.2f)\n",
|
243 |
+
sum_of_F32_reference,
|
244 |
+
sum_of_Q4_result,
|
245 |
+
delta,
|
246 |
+
allowed_delta
|
247 |
+
);
|
248 |
+
exit(0);
|
249 |
+
}
|
250 |
+
|
251 |
+
// Running a different graph computation to make sure we override the CPU cache lines
|
252 |
+
ggml_graph_compute(ctx, &gf32);
|
253 |
+
}
|
254 |
+
printf("\n");
|
255 |
+
printf("Average%78.2f\n",gflops_sum/((double)benchmark_params.n_iterations));
|
256 |
+
printf("=====================================================================================\n");
|
257 |
+
}
|
examples/chat-13B.bat
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@setlocal disabledelayedexpansion enableextensions
|
2 |
+
@echo off
|
3 |
+
|
4 |
+
cd /d "%~dp0.."
|
5 |
+
if not "%errorlevel%"=="0" (
|
6 |
+
echo Unable to change directory.
|
7 |
+
pause
|
8 |
+
exit /b 1
|
9 |
+
)
|
10 |
+
|
11 |
+
if not defined MODEL set "MODEL=models\13B\ggml-model-q4_0.bin"
|
12 |
+
if not defined USER_NAME set "USER_NAME=User"
|
13 |
+
if not defined AI_NAME set "AI_NAME=ChatLLaMa"
|
14 |
+
rem Adjust to the number of CPU cores you want to use.
|
15 |
+
rem if not defined N_THREAD set "N_THREAD=8"
|
16 |
+
rem Number of tokens to predict (made it larger than default because we want a long interaction)
|
17 |
+
if not defined N_PREDICTS set "N_PREDICTS=2048"
|
18 |
+
if not defined GEN_OPTIONS set "GEN_OPTIONS=--ctx_size 2048 --temp 0.7 --top_k 40 --top_p 0.5 --repeat_last_n 256 --batch_size 1024 --repeat_penalty 1.17647"
|
19 |
+
|
20 |
+
rem Default main script paths
|
21 |
+
set "DEFAULT_MAIN_SCRIPT_PATHS=main.exe build\bin\main.exe"
|
22 |
+
|
23 |
+
rem Get main script path from command line arguments
|
24 |
+
set "MAIN_SCRIPT_PATH=%~1"
|
25 |
+
|
26 |
+
rem If the main script path was not specified, try the default paths
|
27 |
+
if not defined MAIN_SCRIPT_PATH (
|
28 |
+
for %%i in (%DEFAULT_MAIN_SCRIPT_PATHS%) do (
|
29 |
+
if exist "%%i" set "MAIN_SCRIPT_PATH=%%i"
|
30 |
+
)
|
31 |
+
)
|
32 |
+
|
33 |
+
rem If the main script path was not found, tell the user how to specify it
|
34 |
+
if not defined MAIN_SCRIPT_PATH (
|
35 |
+
echo The main script could not be found. Please provide the path to the main script as 1st argument to this script, or place the main script in one of the default locations:
|
36 |
+
echo %DEFAULT_MAIN_SCRIPT_PATHS%
|
37 |
+
pause
|
38 |
+
exit /b 1
|
39 |
+
)
|
40 |
+
|
41 |
+
rem Default context, feel free to edit it
|
42 |
+
set "PROMPT_TEXT=Text transcript of a never ending dialog, where %USER_NAME% interacts with an AI assistant named %AI_NAME%. %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. There are no annotations like (30 seconds passed...) or (to himself), just what %USER_NAME% and %AI_NAME% say aloud to each other. The dialog lasts for years, the entirety of it is shared below. It's 10000 pages long. The transcript only includes text, it does not include markup like HTML and Markdown."
|
43 |
+
|
44 |
+
rem Set a temporary variable if N_THREAD is set
|
45 |
+
if defined N_THREAD (
|
46 |
+
set "_N_THREAD=--threads %N_THREAD%"
|
47 |
+
) else (
|
48 |
+
set "_N_THREAD="
|
49 |
+
)
|
50 |
+
|
51 |
+
rem Run the script
|
52 |
+
echo "%MAIN_SCRIPT_PATH%" %GEN_OPTIONS% %_N_THREAD% ^
|
53 |
+
--model "%MODEL%" ^
|
54 |
+
--n_predict %N_PREDICTS% ^
|
55 |
+
--color --interactive ^
|
56 |
+
--reverse-prompt "%USER_NAME%:" ^
|
57 |
+
--prompt "%PROMPT_TEXT%"
|
examples/chat-13B.sh
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
set -e
|
4 |
+
|
5 |
+
cd "$(dirname "$0")/.." || exit
|
6 |
+
|
7 |
+
MODEL="${MODEL:-./models/13B/ggml-model-q4_0.bin}"
|
8 |
+
PROMPT_TEMPLATE=${PROMPT_TEMPLATE:-./prompts/chat.txt}
|
9 |
+
USER_NAME="${USER_NAME:-USER}"
|
10 |
+
AI_NAME="${AI_NAME:-ChatLLaMa}"
|
11 |
+
|
12 |
+
# Adjust to the number of CPU cores you want to use.
|
13 |
+
N_THREAD="${N_THREAD:-8}"
|
14 |
+
# Number of tokens to predict (made it larger than default because we want a long interaction)
|
15 |
+
N_PREDICTS="${N_PREDICTS:-2048}"
|
16 |
+
|
17 |
+
# Note: you can also override the generation options by specifying them on the command line:
|
18 |
+
# For example, override the context size by doing: ./chatLLaMa --ctx_size 1024
|
19 |
+
GEN_OPTIONS="${GEN_OPTIONS:---ctx_size 2048 --temp 0.7 --top_k 40 --top_p 0.5 --repeat_last_n 256 --batch_size 1024 --repeat_penalty 1.17647}"
|
20 |
+
|
21 |
+
DATE_TIME=$(date +%H:%M)
|
22 |
+
DATE_YEAR=$(date +%Y)
|
23 |
+
|
24 |
+
PROMPT_FILE=$(mktemp -t llamacpp_prompt.XXXXXXX.txt)
|
25 |
+
|
26 |
+
sed -e "s/\[\[USER_NAME\]\]/$USER_NAME/g" \
|
27 |
+
-e "s/\[\[AI_NAME\]\]/$AI_NAME/g" \
|
28 |
+
-e "s/\[\[DATE_TIME\]\]/$DATE_TIME/g" \
|
29 |
+
-e "s/\[\[DATE_YEAR\]\]/$DATE_YEAR/g" \
|
30 |
+
$PROMPT_TEMPLATE > $PROMPT_FILE
|
31 |
+
|
32 |
+
# shellcheck disable=SC2086 # Intended splitting of GEN_OPTIONS
|
33 |
+
./main $GEN_OPTIONS \
|
34 |
+
--model "$MODEL" \
|
35 |
+
--threads "$N_THREAD" \
|
36 |
+
--n_predict "$N_PREDICTS" \
|
37 |
+
--color --interactive \
|
38 |
+
--file ${PROMPT_FILE} \
|
39 |
+
--reverse-prompt "${USER_NAME}:" \
|
40 |
+
--in-prefix ' ' \
|
41 |
+
"$@"
|
examples/chat-persistent.sh
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
set -euo pipefail
|
4 |
+
|
5 |
+
cd "$(dirname "$0")/.." || exit
|
6 |
+
|
7 |
+
if [[ -z "${PROMPT_CACHE_FILE+x}" || -z "${CHAT_SAVE_DIR+x}" ]]; then
|
8 |
+
echo >&2 "error: PROMPT_CACHE_FILE and CHAT_SAVE_DIR must be provided"
|
9 |
+
exit 1
|
10 |
+
fi
|
11 |
+
|
12 |
+
MODEL="${MODEL:-./models/13B/ggml-model-q4_0.bin}"
|
13 |
+
PROMPT_TEMPLATE="${PROMPT_TEMPLATE:-./prompts/chat.txt}"
|
14 |
+
USER_NAME="${USER_NAME:-User}"
|
15 |
+
AI_NAME="${AI_NAME:-ChatLLaMa}"
|
16 |
+
DATE_TIME="$(date +%H:%M)"
|
17 |
+
DATE_YEAR="$(date +%Y)"
|
18 |
+
|
19 |
+
LOG="${CHAT_SAVE_DIR}/main.log"
|
20 |
+
LOG_BG="${CHAT_SAVE_DIR}/main-bg.log"
|
21 |
+
CUR_PROMPT_FILE="${CHAT_SAVE_DIR}/current-prompt.txt"
|
22 |
+
CUR_PROMPT_CACHE="${CHAT_SAVE_DIR}/current-cache.bin"
|
23 |
+
NEXT_PROMPT_FILE="${CHAT_SAVE_DIR}/next-prompt.txt"
|
24 |
+
NEXT_PROMPT_CACHE="${CHAT_SAVE_DIR}/next-cache.bin"
|
25 |
+
|
26 |
+
SESSION_SIZE_MSG_PATTERN='main: session file matches [[:digit:]]+ / [[:digit:]]+'
|
27 |
+
SAMPLE_TIME_MSG_PATTERN='sample time =[[:space:]]+[[:digit:]]+.[[:digit:]]+ ms /[[:space:]]+[[:digit:]]+'
|
28 |
+
SED_DELETE_MESSAGES="/^(${USER_NAME}:|${AI_NAME}:|\\.\\.\\.)/,\$d"
|
29 |
+
|
30 |
+
CTX_SIZE=2048
|
31 |
+
CTX_ROTATE_POINT=$((CTX_SIZE * 3 / 5)) # REVIEW
|
32 |
+
OPTS=(--model "$MODEL" --ctx_size "$CTX_SIZE" --repeat_last_n 256 "$@")
|
33 |
+
|
34 |
+
# An unbuffered `tail -c+N`
|
35 |
+
skip_bytes() {
|
36 |
+
LANG=C IFS= read -r -n "$1" -d '' c
|
37 |
+
while LANG=C IFS= read -r -n 1 -d '' c; do
|
38 |
+
printf '%s' "$c"
|
39 |
+
done
|
40 |
+
}
|
41 |
+
|
42 |
+
mkdir -p "$CHAT_SAVE_DIR"
|
43 |
+
echo >"$LOG"
|
44 |
+
trap "tail -n100 ${LOG}" EXIT
|
45 |
+
|
46 |
+
if [[ ! -e "$CUR_PROMPT_FILE" ]]; then
|
47 |
+
sed -e "s/\[\[USER_NAME\]\]/${USER_NAME}/g" \
|
48 |
+
-e "s/\[\[AI_NAME\]\]/${AI_NAME}/g" \
|
49 |
+
-e "s/\[\[DATE_TIME\]\]/${DATE_TIME}/g" \
|
50 |
+
-e "s/\[\[DATE_YEAR\]\]/${DATE_YEAR}/g" \
|
51 |
+
"$PROMPT_TEMPLATE" >"$CUR_PROMPT_FILE"
|
52 |
+
fi
|
53 |
+
|
54 |
+
if [[ ! -e "$NEXT_PROMPT_FILE" ]]; then
|
55 |
+
sed -r "$SED_DELETE_MESSAGES" "$CUR_PROMPT_FILE" >"$NEXT_PROMPT_FILE"
|
56 |
+
fi
|
57 |
+
|
58 |
+
if [[ "$(tail -c4 "$NEXT_PROMPT_FILE")" != "..." ]]; then
|
59 |
+
echo '...' >>"$NEXT_PROMPT_FILE"
|
60 |
+
fi
|
61 |
+
|
62 |
+
if [[ ! -e "$PROMPT_CACHE_FILE" ]]; then
|
63 |
+
echo 'Prompt cache does not exist, building...'
|
64 |
+
# Default batch_size to 8 here for better user feedback during initial prompt processing
|
65 |
+
./main 2>>"$LOG" \
|
66 |
+
--batch_size 8 \
|
67 |
+
"${OPTS[@]}" \
|
68 |
+
--prompt-cache "$PROMPT_CACHE_FILE" \
|
69 |
+
--file "$CUR_PROMPT_FILE" \
|
70 |
+
--n_predict 1
|
71 |
+
echo
|
72 |
+
echo 'Done!'
|
73 |
+
fi
|
74 |
+
|
75 |
+
if [[ ! -e "$CUR_PROMPT_CACHE" ]]; then
|
76 |
+
cp "$PROMPT_CACHE_FILE" "$CUR_PROMPT_CACHE"
|
77 |
+
fi
|
78 |
+
if [[ ! -e "$NEXT_PROMPT_CACHE" ]]; then
|
79 |
+
cp "$PROMPT_CACHE_FILE" "$NEXT_PROMPT_CACHE"
|
80 |
+
fi
|
81 |
+
|
82 |
+
printf '%s ' "$(< "$CUR_PROMPT_FILE")"
|
83 |
+
n_tokens=0
|
84 |
+
|
85 |
+
while read -e line; do
|
86 |
+
# Limit generation to remaining context, with a buffer and estimating 2 chars/token for input
|
87 |
+
n_predict=$((CTX_SIZE - n_tokens - ${#line} / 2 - 32))
|
88 |
+
|
89 |
+
# Swap prompts when we're about to run out of context
|
90 |
+
if ((n_predict <= 0)); then
|
91 |
+
wait # for background main (below) to finish with next prompt
|
92 |
+
mv "$NEXT_PROMPT_FILE" "$CUR_PROMPT_FILE"
|
93 |
+
mv "$NEXT_PROMPT_CACHE" "$CUR_PROMPT_CACHE"
|
94 |
+
|
95 |
+
sed -r "$SED_DELETE_MESSAGES" "$CUR_PROMPT_FILE" >"$NEXT_PROMPT_FILE"
|
96 |
+
echo '...' >>"$NEXT_PROMPT_FILE"
|
97 |
+
cp "$PROMPT_CACHE_FILE" "$NEXT_PROMPT_CACHE"
|
98 |
+
|
99 |
+
n_tokens=0
|
100 |
+
n_predict=$((CTX_SIZE / 2))
|
101 |
+
fi
|
102 |
+
|
103 |
+
echo " ${line}" >>"$CUR_PROMPT_FILE"
|
104 |
+
if ((n_tokens > CTX_ROTATE_POINT)); then
|
105 |
+
echo " ${line}" >>"$NEXT_PROMPT_FILE"
|
106 |
+
fi
|
107 |
+
|
108 |
+
n_prompt_len_pre=$(($(wc -c <"$CUR_PROMPT_FILE")))
|
109 |
+
|
110 |
+
printf '%s: ' "$AI_NAME" >>"$CUR_PROMPT_FILE"
|
111 |
+
|
112 |
+
./main 2>>"$LOG" "${OPTS[@]}" \
|
113 |
+
--prompt-cache "$CUR_PROMPT_CACHE" \
|
114 |
+
--prompt-cache-all \
|
115 |
+
--file "$CUR_PROMPT_FILE" \
|
116 |
+
--reverse-prompt "${USER_NAME}:" \
|
117 |
+
--n_predict "$n_predict" |
|
118 |
+
skip_bytes 1 | # skip BOS token added by ./main
|
119 |
+
tee "$CUR_PROMPT_FILE.tmp" | # save prompt + generation to tmp file
|
120 |
+
skip_bytes "$n_prompt_len_pre" # print generation
|
121 |
+
|
122 |
+
mv "$CUR_PROMPT_FILE.tmp" "$CUR_PROMPT_FILE"
|
123 |
+
|
124 |
+
# if we hit n_predict instead of reverse-prompt, we need to add the prompt
|
125 |
+
if [[ "$(tail -n1 "$CUR_PROMPT_FILE")" != "${USER_NAME}:" ]]; then
|
126 |
+
printf '\n%s:' "$USER_NAME"
|
127 |
+
printf '\n%s:' "$USER_NAME" >> "$CUR_PROMPT_FILE"
|
128 |
+
fi
|
129 |
+
|
130 |
+
printf ' '
|
131 |
+
|
132 |
+
# HACK get num tokens from debug message
|
133 |
+
# TODO get both messages in one go
|
134 |
+
if ! session_size_msg="$(tail -n30 "$LOG" | grep -oE "$SESSION_SIZE_MSG_PATTERN")" ||
|
135 |
+
! sample_time_msg="$( tail -n10 "$LOG" | grep -oE "$SAMPLE_TIME_MSG_PATTERN")"; then
|
136 |
+
echo >&2 "Couldn't get number of tokens from ./main output!"
|
137 |
+
exit 1
|
138 |
+
fi
|
139 |
+
|
140 |
+
n_tokens=$(($(cut -d/ -f2 <<<"$session_size_msg") + $(cut -d/ -f2 <<<"$sample_time_msg")))
|
141 |
+
|
142 |
+
if ((n_tokens > CTX_ROTATE_POINT)); then
|
143 |
+
tail -c+$((n_prompt_len_pre + 1)) "$CUR_PROMPT_FILE" >>"$NEXT_PROMPT_FILE"
|
144 |
+
fi
|
145 |
+
|
146 |
+
# Update cache for next prompt in background, ideally during user input
|
147 |
+
./main >>"$LOG_BG" 2>&1 "${OPTS[@]}" \
|
148 |
+
--prompt-cache "$NEXT_PROMPT_CACHE" \
|
149 |
+
--file "$NEXT_PROMPT_FILE" \
|
150 |
+
--n_predict 1 &
|
151 |
+
done
|
examples/chat.sh
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
#
|
4 |
+
# Temporary script - will be removed in the future
|
5 |
+
#
|
6 |
+
|
7 |
+
cd `dirname $0`
|
8 |
+
cd ..
|
9 |
+
|
10 |
+
# Important:
|
11 |
+
#
|
12 |
+
# "--keep 48" is based on the contents of prompts/chat-with-bob.txt
|
13 |
+
#
|
14 |
+
./main -m ./models/7B/ggml-model-q4_0.bin -c 512 -b 1024 -n 256 --keep 48 \
|
15 |
+
--repeat_penalty 1.0 --color -i \
|
16 |
+
-r "User:" -f prompts/chat-with-bob.txt
|
examples/common.cpp
ADDED
@@ -0,0 +1,930 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "common.h"
|
2 |
+
|
3 |
+
#include <cassert>
|
4 |
+
#include <iostream>
|
5 |
+
#include <cstring>
|
6 |
+
#include <fstream>
|
7 |
+
#include <string>
|
8 |
+
#include <iterator>
|
9 |
+
#include <algorithm>
|
10 |
+
#include <sstream>
|
11 |
+
#include <unordered_set>
|
12 |
+
#include <regex>
|
13 |
+
|
14 |
+
#if defined(__APPLE__) && defined(__MACH__)
|
15 |
+
#include <sys/types.h>
|
16 |
+
#include <sys/sysctl.h>
|
17 |
+
#endif
|
18 |
+
|
19 |
+
#if defined(_WIN32)
|
20 |
+
#define WIN32_LEAN_AND_MEAN
|
21 |
+
#define NOMINMAX
|
22 |
+
#include <windows.h>
|
23 |
+
#include <fcntl.h>
|
24 |
+
#include <io.h>
|
25 |
+
#else
|
26 |
+
#include <sys/ioctl.h>
|
27 |
+
#include <unistd.h>
|
28 |
+
#include <wchar.h>
|
29 |
+
#endif
|
30 |
+
|
31 |
+
int32_t get_num_physical_cores() {
|
32 |
+
#ifdef __linux__
|
33 |
+
// enumerate the set of thread siblings, num entries is num cores
|
34 |
+
std::unordered_set<std::string> siblings;
|
35 |
+
for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
|
36 |
+
std::ifstream thread_siblings("/sys/devices/system/cpu"
|
37 |
+
+ std::to_string(cpu) + "/topology/thread_siblings");
|
38 |
+
if (!thread_siblings.is_open()) {
|
39 |
+
break; // no more cpus
|
40 |
+
}
|
41 |
+
std::string line;
|
42 |
+
if (std::getline(thread_siblings, line)) {
|
43 |
+
siblings.insert(line);
|
44 |
+
}
|
45 |
+
}
|
46 |
+
if (siblings.size() > 0) {
|
47 |
+
return static_cast<int32_t>(siblings.size());
|
48 |
+
}
|
49 |
+
#elif defined(__APPLE__) && defined(__MACH__)
|
50 |
+
int32_t num_physical_cores;
|
51 |
+
size_t len = sizeof(num_physical_cores);
|
52 |
+
int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
|
53 |
+
if (result == 0) {
|
54 |
+
return num_physical_cores;
|
55 |
+
}
|
56 |
+
result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
|
57 |
+
if (result == 0) {
|
58 |
+
return num_physical_cores;
|
59 |
+
}
|
60 |
+
#elif defined(_WIN32)
|
61 |
+
//TODO: Implement
|
62 |
+
#endif
|
63 |
+
unsigned int n_threads = std::thread::hardware_concurrency();
|
64 |
+
return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
|
65 |
+
}
|
66 |
+
|
67 |
+
void process_escapes(std::string& input) {
|
68 |
+
std::size_t input_len = input.length();
|
69 |
+
std::size_t output_idx = 0;
|
70 |
+
|
71 |
+
for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
|
72 |
+
if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
|
73 |
+
switch (input[++input_idx]) {
|
74 |
+
case 'n': input[output_idx++] = '\n'; break;
|
75 |
+
case 'r': input[output_idx++] = '\r'; break;
|
76 |
+
case 't': input[output_idx++] = '\t'; break;
|
77 |
+
case '\'': input[output_idx++] = '\''; break;
|
78 |
+
case '\"': input[output_idx++] = '\"'; break;
|
79 |
+
case '\\': input[output_idx++] = '\\'; break;
|
80 |
+
default: input[output_idx++] = '\\';
|
81 |
+
input[output_idx++] = input[input_idx]; break;
|
82 |
+
}
|
83 |
+
} else {
|
84 |
+
input[output_idx++] = input[input_idx];
|
85 |
+
}
|
86 |
+
}
|
87 |
+
|
88 |
+
input.resize(output_idx);
|
89 |
+
}
|
90 |
+
|
91 |
+
bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
|
92 |
+
bool invalid_param = false;
|
93 |
+
bool escape_prompt = false;
|
94 |
+
std::string arg;
|
95 |
+
gpt_params default_params;
|
96 |
+
const std::string arg_prefix = "--";
|
97 |
+
|
98 |
+
for (int i = 1; i < argc; i++) {
|
99 |
+
arg = argv[i];
|
100 |
+
if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
|
101 |
+
std::replace(arg.begin(), arg.end(), '_', '-');
|
102 |
+
}
|
103 |
+
|
104 |
+
if (arg == "-s" || arg == "--seed") {
|
105 |
+
#if defined(GGML_USE_CUBLAS)
|
106 |
+
fprintf(stderr, "WARNING: when using cuBLAS generation results are NOT guaranteed to be reproducible.\n");
|
107 |
+
#endif
|
108 |
+
if (++i >= argc) {
|
109 |
+
invalid_param = true;
|
110 |
+
break;
|
111 |
+
}
|
112 |
+
params.seed = std::stoi(argv[i]);
|
113 |
+
} else if (arg == "-t" || arg == "--threads") {
|
114 |
+
if (++i >= argc) {
|
115 |
+
invalid_param = true;
|
116 |
+
break;
|
117 |
+
}
|
118 |
+
params.n_threads = std::stoi(argv[i]);
|
119 |
+
} else if (arg == "-p" || arg == "--prompt") {
|
120 |
+
if (++i >= argc) {
|
121 |
+
invalid_param = true;
|
122 |
+
break;
|
123 |
+
}
|
124 |
+
params.prompt = argv[i];
|
125 |
+
} else if (arg == "-e") {
|
126 |
+
escape_prompt = true;
|
127 |
+
} else if (arg == "--prompt-cache") {
|
128 |
+
if (++i >= argc) {
|
129 |
+
invalid_param = true;
|
130 |
+
break;
|
131 |
+
}
|
132 |
+
params.path_prompt_cache = argv[i];
|
133 |
+
} else if (arg == "--prompt-cache-all") {
|
134 |
+
params.prompt_cache_all = true;
|
135 |
+
} else if (arg == "--prompt-cache-ro") {
|
136 |
+
params.prompt_cache_ro = true;
|
137 |
+
} else if (arg == "-f" || arg == "--file") {
|
138 |
+
if (++i >= argc) {
|
139 |
+
invalid_param = true;
|
140 |
+
break;
|
141 |
+
}
|
142 |
+
std::ifstream file(argv[i]);
|
143 |
+
if (!file) {
|
144 |
+
fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
|
145 |
+
invalid_param = true;
|
146 |
+
break;
|
147 |
+
}
|
148 |
+
std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
|
149 |
+
if (params.prompt.back() == '\n') {
|
150 |
+
params.prompt.pop_back();
|
151 |
+
}
|
152 |
+
} else if (arg == "-n" || arg == "--n-predict") {
|
153 |
+
if (++i >= argc) {
|
154 |
+
invalid_param = true;
|
155 |
+
break;
|
156 |
+
}
|
157 |
+
params.n_predict = std::stoi(argv[i]);
|
158 |
+
} else if (arg == "--top-k") {
|
159 |
+
if (++i >= argc) {
|
160 |
+
invalid_param = true;
|
161 |
+
break;
|
162 |
+
}
|
163 |
+
params.top_k = std::stoi(argv[i]);
|
164 |
+
} else if (arg == "-c" || arg == "--ctx-size") {
|
165 |
+
if (++i >= argc) {
|
166 |
+
invalid_param = true;
|
167 |
+
break;
|
168 |
+
}
|
169 |
+
params.n_ctx = std::stoi(argv[i]);
|
170 |
+
} else if (arg == "--memory-f32") {
|
171 |
+
params.memory_f16 = false;
|
172 |
+
} else if (arg == "--top-p") {
|
173 |
+
if (++i >= argc) {
|
174 |
+
invalid_param = true;
|
175 |
+
break;
|
176 |
+
}
|
177 |
+
params.top_p = std::stof(argv[i]);
|
178 |
+
} else if (arg == "--temp") {
|
179 |
+
if (++i >= argc) {
|
180 |
+
invalid_param = true;
|
181 |
+
break;
|
182 |
+
}
|
183 |
+
params.temp = std::stof(argv[i]);
|
184 |
+
} else if (arg == "--tfs") {
|
185 |
+
if (++i >= argc) {
|
186 |
+
invalid_param = true;
|
187 |
+
break;
|
188 |
+
}
|
189 |
+
params.tfs_z = std::stof(argv[i]);
|
190 |
+
} else if (arg == "--typical") {
|
191 |
+
if (++i >= argc) {
|
192 |
+
invalid_param = true;
|
193 |
+
break;
|
194 |
+
}
|
195 |
+
params.typical_p = std::stof(argv[i]);
|
196 |
+
} else if (arg == "--repeat-last-n") {
|
197 |
+
if (++i >= argc) {
|
198 |
+
invalid_param = true;
|
199 |
+
break;
|
200 |
+
}
|
201 |
+
params.repeat_last_n = std::stoi(argv[i]);
|
202 |
+
} else if (arg == "--repeat-penalty") {
|
203 |
+
if (++i >= argc) {
|
204 |
+
invalid_param = true;
|
205 |
+
break;
|
206 |
+
}
|
207 |
+
params.repeat_penalty = std::stof(argv[i]);
|
208 |
+
} else if (arg == "--frequency-penalty") {
|
209 |
+
if (++i >= argc) {
|
210 |
+
invalid_param = true;
|
211 |
+
break;
|
212 |
+
}
|
213 |
+
params.frequency_penalty = std::stof(argv[i]);
|
214 |
+
} else if (arg == "--presence-penalty") {
|
215 |
+
if (++i >= argc) {
|
216 |
+
invalid_param = true;
|
217 |
+
break;
|
218 |
+
}
|
219 |
+
params.presence_penalty = std::stof(argv[i]);
|
220 |
+
} else if (arg == "--mirostat") {
|
221 |
+
if (++i >= argc) {
|
222 |
+
invalid_param = true;
|
223 |
+
break;
|
224 |
+
}
|
225 |
+
params.mirostat = std::stoi(argv[i]);
|
226 |
+
} else if (arg == "--mirostat-lr") {
|
227 |
+
if (++i >= argc) {
|
228 |
+
invalid_param = true;
|
229 |
+
break;
|
230 |
+
}
|
231 |
+
params.mirostat_eta = std::stof(argv[i]);
|
232 |
+
} else if (arg == "--mirostat-ent") {
|
233 |
+
if (++i >= argc) {
|
234 |
+
invalid_param = true;
|
235 |
+
break;
|
236 |
+
}
|
237 |
+
params.mirostat_tau = std::stof(argv[i]);
|
238 |
+
} else if (arg == "-b" || arg == "--batch-size") {
|
239 |
+
if (++i >= argc) {
|
240 |
+
invalid_param = true;
|
241 |
+
break;
|
242 |
+
}
|
243 |
+
params.n_batch = std::stoi(argv[i]);
|
244 |
+
params.n_batch = std::min(512, params.n_batch);
|
245 |
+
} else if (arg == "--keep") {
|
246 |
+
if (++i >= argc) {
|
247 |
+
invalid_param = true;
|
248 |
+
break;
|
249 |
+
}
|
250 |
+
params.n_keep = std::stoi(argv[i]);
|
251 |
+
} else if (arg == "-m" || arg == "--model") {
|
252 |
+
if (++i >= argc) {
|
253 |
+
invalid_param = true;
|
254 |
+
break;
|
255 |
+
}
|
256 |
+
params.model = argv[i];
|
257 |
+
} else if (arg == "-a" || arg == "--alias") {
|
258 |
+
if (++i >= argc) {
|
259 |
+
invalid_param = true;
|
260 |
+
break;
|
261 |
+
}
|
262 |
+
params.model_alias = argv[i];
|
263 |
+
} else if (arg == "--lora") {
|
264 |
+
if (++i >= argc) {
|
265 |
+
invalid_param = true;
|
266 |
+
break;
|
267 |
+
}
|
268 |
+
params.lora_adapter = argv[i];
|
269 |
+
params.use_mmap = false;
|
270 |
+
} else if (arg == "--lora-base") {
|
271 |
+
if (++i >= argc) {
|
272 |
+
invalid_param = true;
|
273 |
+
break;
|
274 |
+
}
|
275 |
+
params.lora_base = argv[i];
|
276 |
+
} else if (arg == "-i" || arg == "--interactive") {
|
277 |
+
params.interactive = true;
|
278 |
+
} else if (arg == "--embedding") {
|
279 |
+
params.embedding = true;
|
280 |
+
} else if (arg == "--interactive-first") {
|
281 |
+
params.interactive_first = true;
|
282 |
+
} else if (arg == "-ins" || arg == "--instruct") {
|
283 |
+
params.instruct = true;
|
284 |
+
} else if (arg == "--multiline-input") {
|
285 |
+
params.multiline_input = true;
|
286 |
+
} else if (arg == "--color") {
|
287 |
+
params.use_color = true;
|
288 |
+
} else if (arg == "--mlock") {
|
289 |
+
params.use_mlock = true;
|
290 |
+
} else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
|
291 |
+
if (++i >= argc) {
|
292 |
+
invalid_param = true;
|
293 |
+
break;
|
294 |
+
}
|
295 |
+
#ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
|
296 |
+
params.n_gpu_layers = std::stoi(argv[i]);
|
297 |
+
#else
|
298 |
+
fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
|
299 |
+
fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
|
300 |
+
#endif
|
301 |
+
} else if (arg == "--main-gpu" || arg == "-mg") {
|
302 |
+
if (++i >= argc) {
|
303 |
+
invalid_param = true;
|
304 |
+
break;
|
305 |
+
}
|
306 |
+
#ifdef GGML_USE_CUBLAS
|
307 |
+
params.main_gpu = std::stoi(argv[i]);
|
308 |
+
#else
|
309 |
+
fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
|
310 |
+
#endif
|
311 |
+
} else if (arg == "--tensor-split" || arg == "-ts") {
|
312 |
+
if (++i >= argc) {
|
313 |
+
invalid_param = true;
|
314 |
+
break;
|
315 |
+
}
|
316 |
+
#ifdef GGML_USE_CUBLAS
|
317 |
+
std::string arg_next = argv[i];
|
318 |
+
|
319 |
+
// split string by , and /
|
320 |
+
const std::regex regex{R"([,/]+)"};
|
321 |
+
std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
|
322 |
+
std::vector<std::string> split_arg{it, {}};
|
323 |
+
GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
|
324 |
+
|
325 |
+
for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
|
326 |
+
if (i < split_arg.size()) {
|
327 |
+
params.tensor_split[i] = std::stof(split_arg[i]);
|
328 |
+
} else {
|
329 |
+
params.tensor_split[i] = 0.0f;
|
330 |
+
}
|
331 |
+
}
|
332 |
+
#else
|
333 |
+
fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
|
334 |
+
#endif // GGML_USE_CUBLAS
|
335 |
+
} else if (arg == "--no-mmap") {
|
336 |
+
params.use_mmap = false;
|
337 |
+
} else if (arg == "--mtest") {
|
338 |
+
params.mem_test = true;
|
339 |
+
} else if (arg == "--export") {
|
340 |
+
params.export_cgraph = true;
|
341 |
+
} else if (arg == "--verbose-prompt") {
|
342 |
+
params.verbose_prompt = true;
|
343 |
+
} else if (arg == "-r" || arg == "--reverse-prompt") {
|
344 |
+
if (++i >= argc) {
|
345 |
+
invalid_param = true;
|
346 |
+
break;
|
347 |
+
}
|
348 |
+
params.antiprompt.push_back(argv[i]);
|
349 |
+
} else if (arg == "--perplexity") {
|
350 |
+
params.perplexity = true;
|
351 |
+
} else if (arg == "--ignore-eos") {
|
352 |
+
params.logit_bias[llama_token_eos()] = -INFINITY;
|
353 |
+
} else if (arg == "--no-penalize-nl") {
|
354 |
+
params.penalize_nl = false;
|
355 |
+
} else if (arg == "-l" || arg == "--logit-bias") {
|
356 |
+
if (++i >= argc) {
|
357 |
+
invalid_param = true;
|
358 |
+
break;
|
359 |
+
}
|
360 |
+
std::stringstream ss(argv[i]);
|
361 |
+
llama_token key;
|
362 |
+
char sign;
|
363 |
+
std::string value_str;
|
364 |
+
try {
|
365 |
+
if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
|
366 |
+
params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
|
367 |
+
} else {
|
368 |
+
throw std::exception();
|
369 |
+
}
|
370 |
+
} catch (const std::exception &e) {
|
371 |
+
invalid_param = true;
|
372 |
+
break;
|
373 |
+
}
|
374 |
+
} else if (arg == "-h" || arg == "--help") {
|
375 |
+
gpt_print_usage(argc, argv, default_params);
|
376 |
+
exit(0);
|
377 |
+
} else if (arg == "--random-prompt") {
|
378 |
+
params.random_prompt = true;
|
379 |
+
} else if (arg == "--in-prefix") {
|
380 |
+
if (++i >= argc) {
|
381 |
+
invalid_param = true;
|
382 |
+
break;
|
383 |
+
}
|
384 |
+
params.input_prefix = argv[i];
|
385 |
+
} else if (arg == "--in-suffix") {
|
386 |
+
if (++i >= argc) {
|
387 |
+
invalid_param = true;
|
388 |
+
break;
|
389 |
+
}
|
390 |
+
params.input_suffix = argv[i];
|
391 |
+
} else {
|
392 |
+
fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
|
393 |
+
gpt_print_usage(argc, argv, default_params);
|
394 |
+
exit(1);
|
395 |
+
}
|
396 |
+
}
|
397 |
+
if (invalid_param) {
|
398 |
+
fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
|
399 |
+
gpt_print_usage(argc, argv, default_params);
|
400 |
+
exit(1);
|
401 |
+
}
|
402 |
+
if (params.prompt_cache_all &&
|
403 |
+
(params.interactive || params.interactive_first ||
|
404 |
+
params.instruct)) {
|
405 |
+
fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
|
406 |
+
gpt_print_usage(argc, argv, default_params);
|
407 |
+
exit(1);
|
408 |
+
}
|
409 |
+
if (escape_prompt) {
|
410 |
+
process_escapes(params.prompt);
|
411 |
+
}
|
412 |
+
|
413 |
+
return true;
|
414 |
+
}
|
415 |
+
|
416 |
+
void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
|
417 |
+
fprintf(stderr, "usage: %s [options]\n", argv[0]);
|
418 |
+
fprintf(stderr, "\n");
|
419 |
+
fprintf(stderr, "options:\n");
|
420 |
+
fprintf(stderr, " -h, --help show this help message and exit\n");
|
421 |
+
fprintf(stderr, " -i, --interactive run in interactive mode\n");
|
422 |
+
fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
|
423 |
+
fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
|
424 |
+
fprintf(stderr, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
|
425 |
+
fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
|
426 |
+
fprintf(stderr, " halt generation at PROMPT, return control in interactive mode\n");
|
427 |
+
fprintf(stderr, " (can be specified more than once for multiple prompts).\n");
|
428 |
+
fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
|
429 |
+
fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
|
430 |
+
fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
|
431 |
+
fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
|
432 |
+
fprintf(stderr, " prompt to start generation with (default: empty)\n");
|
433 |
+
fprintf(stderr, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
|
434 |
+
fprintf(stderr, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
|
435 |
+
fprintf(stderr, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
|
436 |
+
fprintf(stderr, " not supported with --interactive or other interactive options\n");
|
437 |
+
fprintf(stderr, " --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
|
438 |
+
fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
|
439 |
+
fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
|
440 |
+
fprintf(stderr, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
|
441 |
+
fprintf(stderr, " -f FNAME, --file FNAME\n");
|
442 |
+
fprintf(stderr, " prompt file to start generation.\n");
|
443 |
+
fprintf(stderr, " -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
|
444 |
+
fprintf(stderr, " --top-k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
|
445 |
+
fprintf(stderr, " --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
|
446 |
+
fprintf(stderr, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
|
447 |
+
fprintf(stderr, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
|
448 |
+
fprintf(stderr, " --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", params.repeat_last_n);
|
449 |
+
fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
|
450 |
+
fprintf(stderr, " --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
|
451 |
+
fprintf(stderr, " --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
|
452 |
+
fprintf(stderr, " --mirostat N use Mirostat sampling.\n");
|
453 |
+
fprintf(stderr, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
|
454 |
+
fprintf(stderr, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
|
455 |
+
fprintf(stderr, " --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
|
456 |
+
fprintf(stderr, " --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
|
457 |
+
fprintf(stderr, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
|
458 |
+
fprintf(stderr, " modifies the likelihood of token appearing in the completion,\n");
|
459 |
+
fprintf(stderr, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
|
460 |
+
fprintf(stderr, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
|
461 |
+
fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
|
462 |
+
fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
|
463 |
+
fprintf(stderr, " --no-penalize-nl do not penalize newline token\n");
|
464 |
+
fprintf(stderr, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
|
465 |
+
fprintf(stderr, " not recommended: doubles context memory required and no measurable increase in quality\n");
|
466 |
+
fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
|
467 |
+
fprintf(stderr, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
|
468 |
+
fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
|
469 |
+
fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
|
470 |
+
if (llama_mlock_supported()) {
|
471 |
+
fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
|
472 |
+
}
|
473 |
+
if (llama_mmap_supported()) {
|
474 |
+
fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
|
475 |
+
}
|
476 |
+
#ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
|
477 |
+
fprintf(stderr, " -ngl N, --n-gpu-layers N\n");
|
478 |
+
fprintf(stderr, " number of layers to store in VRAM\n");
|
479 |
+
fprintf(stderr, " -ts SPLIT --tensor-split SPLIT\n");
|
480 |
+
fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
|
481 |
+
fprintf(stderr, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n" );
|
482 |
+
#endif
|
483 |
+
fprintf(stderr, " --mtest compute maximum memory usage\n");
|
484 |
+
fprintf(stderr, " --export export the computation graph to 'llama.ggml'\n");
|
485 |
+
fprintf(stderr, " --verbose-prompt print prompt before generation\n");
|
486 |
+
fprintf(stderr, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
|
487 |
+
fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
|
488 |
+
fprintf(stderr, " -m FNAME, --model FNAME\n");
|
489 |
+
fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
|
490 |
+
fprintf(stderr, "\n");
|
491 |
+
}
|
492 |
+
|
493 |
+
std::string gpt_random_prompt(std::mt19937 & rng) {
|
494 |
+
const int r = rng() % 10;
|
495 |
+
switch (r) {
|
496 |
+
case 0: return "So";
|
497 |
+
case 1: return "Once upon a time";
|
498 |
+
case 2: return "When";
|
499 |
+
case 3: return "The";
|
500 |
+
case 4: return "After";
|
501 |
+
case 5: return "If";
|
502 |
+
case 6: return "import";
|
503 |
+
case 7: return "He";
|
504 |
+
case 8: return "She";
|
505 |
+
case 9: return "They";
|
506 |
+
default: return "To";
|
507 |
+
}
|
508 |
+
|
509 |
+
return "The";
|
510 |
+
}
|
511 |
+
|
512 |
+
// TODO: not great allocating this every time
|
513 |
+
std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
|
514 |
+
// initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
|
515 |
+
std::vector<llama_token> res(text.size() + (int) add_bos);
|
516 |
+
const int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
|
517 |
+
assert(n >= 0);
|
518 |
+
res.resize(n);
|
519 |
+
|
520 |
+
return res;
|
521 |
+
}
|
522 |
+
|
523 |
+
struct llama_context * llama_init_from_gpt_params(const gpt_params & params) {
|
524 |
+
auto lparams = llama_context_default_params();
|
525 |
+
|
526 |
+
lparams.n_ctx = params.n_ctx;
|
527 |
+
lparams.n_batch = params.n_batch;
|
528 |
+
lparams.n_gpu_layers = params.n_gpu_layers;
|
529 |
+
lparams.main_gpu = params.main_gpu;
|
530 |
+
memcpy(lparams.tensor_split, params.tensor_split, LLAMA_MAX_DEVICES*sizeof(float));
|
531 |
+
lparams.seed = params.seed;
|
532 |
+
lparams.f16_kv = params.memory_f16;
|
533 |
+
lparams.use_mmap = params.use_mmap;
|
534 |
+
lparams.use_mlock = params.use_mlock;
|
535 |
+
lparams.logits_all = params.perplexity;
|
536 |
+
lparams.embedding = params.embedding;
|
537 |
+
|
538 |
+
llama_context * lctx = llama_init_from_file(params.model.c_str(), lparams);
|
539 |
+
|
540 |
+
if (lctx == NULL) {
|
541 |
+
fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
|
542 |
+
return NULL;
|
543 |
+
}
|
544 |
+
|
545 |
+
if (!params.lora_adapter.empty()) {
|
546 |
+
int err = llama_apply_lora_from_file(lctx,
|
547 |
+
params.lora_adapter.c_str(),
|
548 |
+
params.lora_base.empty() ? NULL : params.lora_base.c_str(),
|
549 |
+
params.n_threads);
|
550 |
+
if (err != 0) {
|
551 |
+
fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
|
552 |
+
return NULL;
|
553 |
+
}
|
554 |
+
}
|
555 |
+
|
556 |
+
return lctx;
|
557 |
+
}
|
558 |
+
|
559 |
+
void console_init(console_state & con_st) {
|
560 |
+
#if defined(_WIN32)
|
561 |
+
// Windows-specific console initialization
|
562 |
+
DWORD dwMode = 0;
|
563 |
+
con_st.hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
|
564 |
+
if (con_st.hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(con_st.hConsole, &dwMode)) {
|
565 |
+
con_st.hConsole = GetStdHandle(STD_ERROR_HANDLE);
|
566 |
+
if (con_st.hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(con_st.hConsole, &dwMode))) {
|
567 |
+
con_st.hConsole = NULL;
|
568 |
+
}
|
569 |
+
}
|
570 |
+
if (con_st.hConsole) {
|
571 |
+
// Enable ANSI colors on Windows 10+
|
572 |
+
if (con_st.use_color && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
|
573 |
+
SetConsoleMode(con_st.hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
|
574 |
+
}
|
575 |
+
// Set console output codepage to UTF8
|
576 |
+
SetConsoleOutputCP(CP_UTF8);
|
577 |
+
}
|
578 |
+
HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE);
|
579 |
+
if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) {
|
580 |
+
// Set console input codepage to UTF16
|
581 |
+
_setmode(_fileno(stdin), _O_WTEXT);
|
582 |
+
|
583 |
+
// Turn off ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT)
|
584 |
+
dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
|
585 |
+
SetConsoleMode(hConIn, dwMode);
|
586 |
+
}
|
587 |
+
#else
|
588 |
+
// POSIX-specific console initialization
|
589 |
+
struct termios new_termios;
|
590 |
+
tcgetattr(STDIN_FILENO, &con_st.prev_state);
|
591 |
+
new_termios = con_st.prev_state;
|
592 |
+
new_termios.c_lflag &= ~(ICANON | ECHO);
|
593 |
+
new_termios.c_cc[VMIN] = 1;
|
594 |
+
new_termios.c_cc[VTIME] = 0;
|
595 |
+
tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
|
596 |
+
|
597 |
+
con_st.tty = fopen("/dev/tty", "w+");
|
598 |
+
if (con_st.tty != nullptr) {
|
599 |
+
con_st.out = con_st.tty;
|
600 |
+
}
|
601 |
+
|
602 |
+
setlocale(LC_ALL, "");
|
603 |
+
#endif
|
604 |
+
}
|
605 |
+
|
606 |
+
void console_cleanup(console_state & con_st) {
|
607 |
+
// Reset console color
|
608 |
+
console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
|
609 |
+
|
610 |
+
#if !defined(_WIN32)
|
611 |
+
if (con_st.tty != nullptr) {
|
612 |
+
con_st.out = stdout;
|
613 |
+
fclose(con_st.tty);
|
614 |
+
con_st.tty = nullptr;
|
615 |
+
}
|
616 |
+
// Restore the terminal settings on POSIX systems
|
617 |
+
tcsetattr(STDIN_FILENO, TCSANOW, &con_st.prev_state);
|
618 |
+
#endif
|
619 |
+
}
|
620 |
+
|
621 |
+
/* Keep track of current color of output, and emit ANSI code if it changes. */
|
622 |
+
void console_set_color(console_state & con_st, console_color_t color) {
|
623 |
+
if (con_st.use_color && con_st.color != color) {
|
624 |
+
fflush(stdout);
|
625 |
+
switch(color) {
|
626 |
+
case CONSOLE_COLOR_DEFAULT:
|
627 |
+
fprintf(con_st.out, ANSI_COLOR_RESET);
|
628 |
+
break;
|
629 |
+
case CONSOLE_COLOR_PROMPT:
|
630 |
+
fprintf(con_st.out, ANSI_COLOR_YELLOW);
|
631 |
+
break;
|
632 |
+
case CONSOLE_COLOR_USER_INPUT:
|
633 |
+
fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_GREEN);
|
634 |
+
break;
|
635 |
+
case CONSOLE_COLOR_ERROR:
|
636 |
+
fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_RED);
|
637 |
+
break;
|
638 |
+
}
|
639 |
+
con_st.color = color;
|
640 |
+
fflush(con_st.out);
|
641 |
+
}
|
642 |
+
}
|
643 |
+
|
644 |
+
char32_t getchar32() {
|
645 |
+
#if defined(_WIN32)
|
646 |
+
HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
|
647 |
+
wchar_t high_surrogate = 0;
|
648 |
+
|
649 |
+
while (true) {
|
650 |
+
INPUT_RECORD record;
|
651 |
+
DWORD count;
|
652 |
+
if (!ReadConsoleInputW(hConsole, &record, 1, &count) || count == 0) {
|
653 |
+
return WEOF;
|
654 |
+
}
|
655 |
+
|
656 |
+
if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) {
|
657 |
+
wchar_t wc = record.Event.KeyEvent.uChar.UnicodeChar;
|
658 |
+
if (wc == 0) {
|
659 |
+
continue;
|
660 |
+
}
|
661 |
+
|
662 |
+
if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
|
663 |
+
high_surrogate = wc;
|
664 |
+
continue;
|
665 |
+
} else if ((wc >= 0xDC00) && (wc <= 0xDFFF)) { // Check if wc is a low surrogate
|
666 |
+
if (high_surrogate != 0) { // Check if we have a high surrogate
|
667 |
+
return ((high_surrogate - 0xD800) << 10) + (wc - 0xDC00) + 0x10000;
|
668 |
+
}
|
669 |
+
}
|
670 |
+
|
671 |
+
high_surrogate = 0; // Reset the high surrogate
|
672 |
+
return static_cast<char32_t>(wc);
|
673 |
+
}
|
674 |
+
}
|
675 |
+
#else
|
676 |
+
wchar_t wc = getwchar();
|
677 |
+
if (static_cast<wint_t>(wc) == WEOF) {
|
678 |
+
return WEOF;
|
679 |
+
}
|
680 |
+
|
681 |
+
#if WCHAR_MAX == 0xFFFF
|
682 |
+
if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
|
683 |
+
wchar_t low_surrogate = getwchar();
|
684 |
+
if ((low_surrogate >= 0xDC00) && (low_surrogate <= 0xDFFF)) { // Check if the next wchar is a low surrogate
|
685 |
+
return (static_cast<char32_t>(wc & 0x03FF) << 10) + (low_surrogate & 0x03FF) + 0x10000;
|
686 |
+
}
|
687 |
+
}
|
688 |
+
if ((wc >= 0xD800) && (wc <= 0xDFFF)) { // Invalid surrogate pair
|
689 |
+
return 0xFFFD; // Return the replacement character U+FFFD
|
690 |
+
}
|
691 |
+
#endif
|
692 |
+
|
693 |
+
return static_cast<char32_t>(wc);
|
694 |
+
#endif
|
695 |
+
}
|
696 |
+
|
697 |
+
void pop_cursor(console_state & con_st) {
|
698 |
+
#if defined(_WIN32)
|
699 |
+
if (con_st.hConsole != NULL) {
|
700 |
+
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
|
701 |
+
GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo);
|
702 |
+
|
703 |
+
COORD newCursorPosition = bufferInfo.dwCursorPosition;
|
704 |
+
if (newCursorPosition.X == 0) {
|
705 |
+
newCursorPosition.X = bufferInfo.dwSize.X - 1;
|
706 |
+
newCursorPosition.Y -= 1;
|
707 |
+
} else {
|
708 |
+
newCursorPosition.X -= 1;
|
709 |
+
}
|
710 |
+
|
711 |
+
SetConsoleCursorPosition(con_st.hConsole, newCursorPosition);
|
712 |
+
return;
|
713 |
+
}
|
714 |
+
#endif
|
715 |
+
putc('\b', con_st.out);
|
716 |
+
}
|
717 |
+
|
718 |
+
int estimateWidth(char32_t codepoint) {
|
719 |
+
#if defined(_WIN32)
|
720 |
+
return 1;
|
721 |
+
#else
|
722 |
+
return wcwidth(codepoint);
|
723 |
+
#endif
|
724 |
+
}
|
725 |
+
|
726 |
+
int put_codepoint(console_state & con_st, const char* utf8_codepoint, size_t length, int expectedWidth) {
|
727 |
+
#if defined(_WIN32)
|
728 |
+
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
|
729 |
+
if (!GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo)) {
|
730 |
+
// go with the default
|
731 |
+
return expectedWidth;
|
732 |
+
}
|
733 |
+
COORD initialPosition = bufferInfo.dwCursorPosition;
|
734 |
+
DWORD nNumberOfChars = length;
|
735 |
+
WriteConsole(con_st.hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL);
|
736 |
+
|
737 |
+
CONSOLE_SCREEN_BUFFER_INFO newBufferInfo;
|
738 |
+
GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
|
739 |
+
|
740 |
+
// Figure out our real position if we're in the last column
|
741 |
+
if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) {
|
742 |
+
DWORD nNumberOfChars;
|
743 |
+
WriteConsole(con_st.hConsole, &" \b", 2, &nNumberOfChars, NULL);
|
744 |
+
GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
|
745 |
+
}
|
746 |
+
|
747 |
+
int width = newBufferInfo.dwCursorPosition.X - initialPosition.X;
|
748 |
+
if (width < 0) {
|
749 |
+
width += newBufferInfo.dwSize.X;
|
750 |
+
}
|
751 |
+
return width;
|
752 |
+
#else
|
753 |
+
// we can trust expectedWidth if we've got one
|
754 |
+
if (expectedWidth >= 0 || con_st.tty == nullptr) {
|
755 |
+
fwrite(utf8_codepoint, length, 1, con_st.out);
|
756 |
+
return expectedWidth;
|
757 |
+
}
|
758 |
+
|
759 |
+
fputs("\033[6n", con_st.tty); // Query cursor position
|
760 |
+
int x1, x2, y1, y2;
|
761 |
+
int results = 0;
|
762 |
+
results = fscanf(con_st.tty, "\033[%d;%dR", &y1, &x1);
|
763 |
+
|
764 |
+
fwrite(utf8_codepoint, length, 1, con_st.tty);
|
765 |
+
|
766 |
+
fputs("\033[6n", con_st.tty); // Query cursor position
|
767 |
+
results += fscanf(con_st.tty, "\033[%d;%dR", &y2, &x2);
|
768 |
+
|
769 |
+
if (results != 4) {
|
770 |
+
return expectedWidth;
|
771 |
+
}
|
772 |
+
|
773 |
+
int width = x2 - x1;
|
774 |
+
if (width < 0) {
|
775 |
+
// Calculate the width considering text wrapping
|
776 |
+
struct winsize w;
|
777 |
+
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
|
778 |
+
width += w.ws_col;
|
779 |
+
}
|
780 |
+
return width;
|
781 |
+
#endif
|
782 |
+
}
|
783 |
+
|
784 |
+
void replace_last(console_state & con_st, char ch) {
|
785 |
+
#if defined(_WIN32)
|
786 |
+
pop_cursor(con_st);
|
787 |
+
put_codepoint(con_st, &ch, 1, 1);
|
788 |
+
#else
|
789 |
+
fprintf(con_st.out, "\b%c", ch);
|
790 |
+
#endif
|
791 |
+
}
|
792 |
+
|
793 |
+
void append_utf8(char32_t ch, std::string & out) {
|
794 |
+
if (ch <= 0x7F) {
|
795 |
+
out.push_back(static_cast<unsigned char>(ch));
|
796 |
+
} else if (ch <= 0x7FF) {
|
797 |
+
out.push_back(static_cast<unsigned char>(0xC0 | ((ch >> 6) & 0x1F)));
|
798 |
+
out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
|
799 |
+
} else if (ch <= 0xFFFF) {
|
800 |
+
out.push_back(static_cast<unsigned char>(0xE0 | ((ch >> 12) & 0x0F)));
|
801 |
+
out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
|
802 |
+
out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
|
803 |
+
} else if (ch <= 0x10FFFF) {
|
804 |
+
out.push_back(static_cast<unsigned char>(0xF0 | ((ch >> 18) & 0x07)));
|
805 |
+
out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 12) & 0x3F)));
|
806 |
+
out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
|
807 |
+
out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
|
808 |
+
} else {
|
809 |
+
// Invalid Unicode code point
|
810 |
+
}
|
811 |
+
}
|
812 |
+
|
813 |
+
// Helper function to remove the last UTF-8 character from a string
|
814 |
+
void pop_back_utf8_char(std::string & line) {
|
815 |
+
if (line.empty()) {
|
816 |
+
return;
|
817 |
+
}
|
818 |
+
|
819 |
+
size_t pos = line.length() - 1;
|
820 |
+
|
821 |
+
// Find the start of the last UTF-8 character (checking up to 4 bytes back)
|
822 |
+
for (size_t i = 0; i < 3 && pos > 0; ++i, --pos) {
|
823 |
+
if ((line[pos] & 0xC0) != 0x80) break; // Found the start of the character
|
824 |
+
}
|
825 |
+
line.erase(pos);
|
826 |
+
}
|
827 |
+
|
828 |
+
bool console_readline(console_state & con_st, std::string & line) {
|
829 |
+
console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
|
830 |
+
if (con_st.out != stdout) {
|
831 |
+
fflush(stdout);
|
832 |
+
}
|
833 |
+
|
834 |
+
line.clear();
|
835 |
+
std::vector<int> widths;
|
836 |
+
bool is_special_char = false;
|
837 |
+
bool end_of_stream = false;
|
838 |
+
|
839 |
+
char32_t input_char;
|
840 |
+
while (true) {
|
841 |
+
fflush(con_st.out); // Ensure all output is displayed before waiting for input
|
842 |
+
input_char = getchar32();
|
843 |
+
|
844 |
+
if (input_char == '\r' || input_char == '\n') {
|
845 |
+
break;
|
846 |
+
}
|
847 |
+
|
848 |
+
if (input_char == (char32_t) WEOF || input_char == 0x04 /* Ctrl+D*/) {
|
849 |
+
end_of_stream = true;
|
850 |
+
break;
|
851 |
+
}
|
852 |
+
|
853 |
+
if (is_special_char) {
|
854 |
+
console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
|
855 |
+
replace_last(con_st, line.back());
|
856 |
+
is_special_char = false;
|
857 |
+
}
|
858 |
+
|
859 |
+
if (input_char == '\033') { // Escape sequence
|
860 |
+
char32_t code = getchar32();
|
861 |
+
if (code == '[' || code == 0x1B) {
|
862 |
+
// Discard the rest of the escape sequence
|
863 |
+
while ((code = getchar32()) != (char32_t) WEOF) {
|
864 |
+
if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z') || code == '~') {
|
865 |
+
break;
|
866 |
+
}
|
867 |
+
}
|
868 |
+
}
|
869 |
+
} else if (input_char == 0x08 || input_char == 0x7F) { // Backspace
|
870 |
+
if (!widths.empty()) {
|
871 |
+
int count;
|
872 |
+
do {
|
873 |
+
count = widths.back();
|
874 |
+
widths.pop_back();
|
875 |
+
// Move cursor back, print space, and move cursor back again
|
876 |
+
for (int i = 0; i < count; i++) {
|
877 |
+
replace_last(con_st, ' ');
|
878 |
+
pop_cursor(con_st);
|
879 |
+
}
|
880 |
+
pop_back_utf8_char(line);
|
881 |
+
} while (count == 0 && !widths.empty());
|
882 |
+
}
|
883 |
+
} else {
|
884 |
+
int offset = line.length();
|
885 |
+
append_utf8(input_char, line);
|
886 |
+
int width = put_codepoint(con_st, line.c_str() + offset, line.length() - offset, estimateWidth(input_char));
|
887 |
+
if (width < 0) {
|
888 |
+
width = 0;
|
889 |
+
}
|
890 |
+
widths.push_back(width);
|
891 |
+
}
|
892 |
+
|
893 |
+
if (!line.empty() && (line.back() == '\\' || line.back() == '/')) {
|
894 |
+
console_set_color(con_st, CONSOLE_COLOR_PROMPT);
|
895 |
+
replace_last(con_st, line.back());
|
896 |
+
is_special_char = true;
|
897 |
+
}
|
898 |
+
}
|
899 |
+
|
900 |
+
bool has_more = con_st.multiline_input;
|
901 |
+
if (is_special_char) {
|
902 |
+
replace_last(con_st, ' ');
|
903 |
+
pop_cursor(con_st);
|
904 |
+
|
905 |
+
char last = line.back();
|
906 |
+
line.pop_back();
|
907 |
+
if (last == '\\') {
|
908 |
+
line += '\n';
|
909 |
+
fputc('\n', con_st.out);
|
910 |
+
has_more = !has_more;
|
911 |
+
} else {
|
912 |
+
// llama will just eat the single space, it won't act as a space
|
913 |
+
if (line.length() == 1 && line.back() == ' ') {
|
914 |
+
line.clear();
|
915 |
+
pop_cursor(con_st);
|
916 |
+
}
|
917 |
+
has_more = false;
|
918 |
+
}
|
919 |
+
} else {
|
920 |
+
if (end_of_stream) {
|
921 |
+
has_more = false;
|
922 |
+
} else {
|
923 |
+
line += '\n';
|
924 |
+
fputc('\n', con_st.out);
|
925 |
+
}
|
926 |
+
}
|
927 |
+
|
928 |
+
fflush(con_st.out);
|
929 |
+
return has_more;
|
930 |
+
}
|
examples/common.h
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Various helper functions and utilities
|
2 |
+
|
3 |
+
#pragma once
|
4 |
+
|
5 |
+
#include "llama.h"
|
6 |
+
|
7 |
+
#include <string>
|
8 |
+
#include <vector>
|
9 |
+
#include <random>
|
10 |
+
#include <thread>
|
11 |
+
#include <unordered_map>
|
12 |
+
|
13 |
+
#if !defined (_WIN32)
|
14 |
+
#include <stdio.h>
|
15 |
+
#include <termios.h>
|
16 |
+
#endif
|
17 |
+
|
18 |
+
//
|
19 |
+
// CLI argument parsing
|
20 |
+
//
|
21 |
+
int32_t get_num_physical_cores();
|
22 |
+
|
23 |
+
struct gpt_params {
|
24 |
+
int32_t seed = -1; // RNG seed
|
25 |
+
int32_t n_threads = get_num_physical_cores();
|
26 |
+
int32_t n_predict = -1; // new tokens to predict
|
27 |
+
int32_t n_ctx = 512; // context size
|
28 |
+
int32_t n_batch = 512; // batch size for prompt processing (must be >=32 to use BLAS)
|
29 |
+
int32_t n_keep = 0; // number of tokens to keep from initial prompt
|
30 |
+
int32_t n_gpu_layers = 0; // number of layers to store in VRAM
|
31 |
+
int32_t main_gpu = 0; // the GPU that is used for scratch and small tensors
|
32 |
+
float tensor_split[LLAMA_MAX_DEVICES] = {0}; // how split tensors should be distributed across GPUs
|
33 |
+
|
34 |
+
// sampling parameters
|
35 |
+
std::unordered_map<llama_token, float> logit_bias; // logit bias for specific tokens
|
36 |
+
int32_t top_k = 40; // <= 0 to use vocab size
|
37 |
+
float top_p = 0.95f; // 1.0 = disabled
|
38 |
+
float tfs_z = 1.00f; // 1.0 = disabled
|
39 |
+
float typical_p = 1.00f; // 1.0 = disabled
|
40 |
+
float temp = 0.80f; // 1.0 = disabled
|
41 |
+
float repeat_penalty = 1.10f; // 1.0 = disabled
|
42 |
+
int32_t repeat_last_n = 64; // last n tokens to penalize (0 = disable penalty, -1 = context size)
|
43 |
+
float frequency_penalty = 0.00f; // 0.0 = disabled
|
44 |
+
float presence_penalty = 0.00f; // 0.0 = disabled
|
45 |
+
int mirostat = 0; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
|
46 |
+
float mirostat_tau = 5.00f; // target entropy
|
47 |
+
float mirostat_eta = 0.10f; // learning rate
|
48 |
+
|
49 |
+
std::string model = "models/7B/ggml-model.bin"; // model path
|
50 |
+
std::string model_alias = "unknown"; // model alias
|
51 |
+
std::string prompt = "";
|
52 |
+
std::string path_prompt_cache = ""; // path to file for saving/loading prompt eval state
|
53 |
+
std::string input_prefix = ""; // string to prefix user inputs with
|
54 |
+
std::string input_suffix = ""; // string to suffix user inputs with
|
55 |
+
std::vector<std::string> antiprompt; // string upon seeing which more user input is prompted
|
56 |
+
|
57 |
+
std::string lora_adapter = ""; // lora adapter path
|
58 |
+
std::string lora_base = ""; // base model path for the lora adapter
|
59 |
+
|
60 |
+
bool memory_f16 = true; // use f16 instead of f32 for memory kv
|
61 |
+
bool random_prompt = false; // do not randomize prompt if none provided
|
62 |
+
bool use_color = false; // use color to distinguish generations and inputs
|
63 |
+
bool interactive = false; // interactive mode
|
64 |
+
bool prompt_cache_all = false; // save user input and generations to prompt cache
|
65 |
+
bool prompt_cache_ro = false; // open the prompt cache read-only and do not update it
|
66 |
+
|
67 |
+
bool embedding = false; // get only sentence embedding
|
68 |
+
bool interactive_first = false; // wait for user input immediately
|
69 |
+
bool multiline_input = false; // reverse the usage of `\`
|
70 |
+
|
71 |
+
bool instruct = false; // instruction mode (used for Alpaca models)
|
72 |
+
bool penalize_nl = true; // consider newlines as a repeatable token
|
73 |
+
bool perplexity = false; // compute perplexity over the prompt
|
74 |
+
bool use_mmap = true; // use mmap for faster loads
|
75 |
+
bool use_mlock = false; // use mlock to keep model in memory
|
76 |
+
bool mem_test = false; // compute maximum memory usage
|
77 |
+
bool export_cgraph = false; // export the computation graph
|
78 |
+
bool verbose_prompt = false; // print prompt tokens before generation
|
79 |
+
};
|
80 |
+
|
81 |
+
bool gpt_params_parse(int argc, char ** argv, gpt_params & params);
|
82 |
+
|
83 |
+
void gpt_print_usage(int argc, char ** argv, const gpt_params & params);
|
84 |
+
|
85 |
+
std::string gpt_random_prompt(std::mt19937 & rng);
|
86 |
+
|
87 |
+
//
|
88 |
+
// Vocab utils
|
89 |
+
//
|
90 |
+
|
91 |
+
std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos);
|
92 |
+
|
93 |
+
//
|
94 |
+
// Model utils
|
95 |
+
//
|
96 |
+
|
97 |
+
struct llama_context * llama_init_from_gpt_params(const gpt_params & params);
|
98 |
+
|
99 |
+
//
|
100 |
+
// Console utils
|
101 |
+
//
|
102 |
+
|
103 |
+
#define ANSI_COLOR_RED "\x1b[31m"
|
104 |
+
#define ANSI_COLOR_GREEN "\x1b[32m"
|
105 |
+
#define ANSI_COLOR_YELLOW "\x1b[33m"
|
106 |
+
#define ANSI_COLOR_BLUE "\x1b[34m"
|
107 |
+
#define ANSI_COLOR_MAGENTA "\x1b[35m"
|
108 |
+
#define ANSI_COLOR_CYAN "\x1b[36m"
|
109 |
+
#define ANSI_COLOR_RESET "\x1b[0m"
|
110 |
+
#define ANSI_BOLD "\x1b[1m"
|
111 |
+
|
112 |
+
enum console_color_t {
|
113 |
+
CONSOLE_COLOR_DEFAULT=0,
|
114 |
+
CONSOLE_COLOR_PROMPT,
|
115 |
+
CONSOLE_COLOR_USER_INPUT,
|
116 |
+
CONSOLE_COLOR_ERROR
|
117 |
+
};
|
118 |
+
|
119 |
+
struct console_state {
|
120 |
+
bool multiline_input = false;
|
121 |
+
bool use_color = false;
|
122 |
+
console_color_t color = CONSOLE_COLOR_DEFAULT;
|
123 |
+
|
124 |
+
FILE* out = stdout;
|
125 |
+
#if defined (_WIN32)
|
126 |
+
void* hConsole;
|
127 |
+
#else
|
128 |
+
FILE* tty = nullptr;
|
129 |
+
termios prev_state;
|
130 |
+
#endif
|
131 |
+
};
|
132 |
+
|
133 |
+
void console_init(console_state & con_st);
|
134 |
+
void console_cleanup(console_state & con_st);
|
135 |
+
void console_set_color(console_state & con_st, console_color_t color);
|
136 |
+
bool console_readline(console_state & con_st, std::string & line);
|
examples/embedding/CMakeLists.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set(TARGET embedding)
|
2 |
+
add_executable(${TARGET} embedding.cpp)
|
3 |
+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
|
4 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_11)
|
5 |
+
if(TARGET BUILD_INFO)
|
6 |
+
add_dependencies(${TARGET} BUILD_INFO)
|
7 |
+
endif()
|
examples/embedding/README.md
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
# embedding
|
2 |
+
|
3 |
+
TODO
|
examples/embedding/embedding.cpp
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "common.h"
|
2 |
+
#include "llama.h"
|
3 |
+
#include "build-info.h"
|
4 |
+
|
5 |
+
#include <ctime>
|
6 |
+
|
7 |
+
int main(int argc, char ** argv) {
|
8 |
+
gpt_params params;
|
9 |
+
|
10 |
+
if (gpt_params_parse(argc, argv, params) == false) {
|
11 |
+
return 1;
|
12 |
+
}
|
13 |
+
|
14 |
+
params.embedding = true;
|
15 |
+
|
16 |
+
if (params.n_ctx > 2048) {
|
17 |
+
fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
|
18 |
+
"expect poor results\n", __func__, params.n_ctx);
|
19 |
+
}
|
20 |
+
|
21 |
+
fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
|
22 |
+
|
23 |
+
if (params.seed < 0) {
|
24 |
+
params.seed = time(NULL);
|
25 |
+
}
|
26 |
+
|
27 |
+
fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
|
28 |
+
|
29 |
+
std::mt19937 rng(params.seed);
|
30 |
+
if (params.random_prompt) {
|
31 |
+
params.prompt = gpt_random_prompt(rng);
|
32 |
+
}
|
33 |
+
|
34 |
+
llama_init_backend();
|
35 |
+
|
36 |
+
llama_context * ctx;
|
37 |
+
|
38 |
+
// load the model
|
39 |
+
ctx = llama_init_from_gpt_params(params);
|
40 |
+
if (ctx == NULL) {
|
41 |
+
fprintf(stderr, "%s: error: unable to load model\n", __func__);
|
42 |
+
return 1;
|
43 |
+
}
|
44 |
+
|
45 |
+
// print system information
|
46 |
+
{
|
47 |
+
fprintf(stderr, "\n");
|
48 |
+
fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
|
49 |
+
params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
|
50 |
+
}
|
51 |
+
|
52 |
+
int n_past = 0;
|
53 |
+
|
54 |
+
// Add a space in front of the first character to match OG llama tokenizer behavior
|
55 |
+
params.prompt.insert(0, 1, ' ');
|
56 |
+
|
57 |
+
// tokenize the prompt
|
58 |
+
auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
|
59 |
+
|
60 |
+
if (params.verbose_prompt) {
|
61 |
+
fprintf(stderr, "\n");
|
62 |
+
fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
|
63 |
+
fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
|
64 |
+
for (int i = 0; i < (int) embd_inp.size(); i++) {
|
65 |
+
fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
|
66 |
+
}
|
67 |
+
fprintf(stderr, "\n");
|
68 |
+
}
|
69 |
+
|
70 |
+
if (params.embedding){
|
71 |
+
if (embd_inp.size() > 0) {
|
72 |
+
if (llama_eval(ctx, embd_inp.data(), embd_inp.size(), n_past, params.n_threads)) {
|
73 |
+
fprintf(stderr, "%s : failed to eval\n", __func__);
|
74 |
+
return 1;
|
75 |
+
}
|
76 |
+
}
|
77 |
+
|
78 |
+
const int n_embd = llama_n_embd(ctx);
|
79 |
+
const auto embeddings = llama_get_embeddings(ctx);
|
80 |
+
|
81 |
+
for (int i = 0; i < n_embd; i++) {
|
82 |
+
printf("%f ", embeddings[i]);
|
83 |
+
}
|
84 |
+
printf("\n");
|
85 |
+
}
|
86 |
+
|
87 |
+
llama_print_timings(ctx);
|
88 |
+
llama_free(ctx);
|
89 |
+
|
90 |
+
return 0;
|
91 |
+
}
|
examples/gpt4all.sh
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
#
|
4 |
+
# Temporary script - will be removed in the future
|
5 |
+
#
|
6 |
+
|
7 |
+
cd `dirname $0`
|
8 |
+
cd ..
|
9 |
+
|
10 |
+
./main --color --instruct --threads 4 \
|
11 |
+
--model ./models/gpt4all-7B/gpt4all-lora-quantized.bin \
|
12 |
+
--file ./prompts/alpaca.txt \
|
13 |
+
--batch_size 8 --ctx_size 2048 -n -1 \
|
14 |
+
--repeat_last_n 64 --repeat_penalty 1.3 \
|
15 |
+
--n_predict 128 --temp 0.1 --top_k 40 --top_p 0.95
|
examples/jeopardy/README.md
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# llama.cpp/example/jeopardy
|
2 |
+
|
3 |
+
This is pretty much just a straight port of aigoopy/llm-jeopardy/ with an added graph viewer.
|
4 |
+
|
5 |
+
The jeopardy test can be used to compare the fact knowledge of different models and compare them to eachother. This is in contrast to some other tests, which test logical deduction, creativity, writing skills, etc.
|
6 |
+
|
7 |
+
|
8 |
+
Step 1: Open jeopardy.sh and modify the following:
|
9 |
+
```
|
10 |
+
MODEL=(path to your model)
|
11 |
+
MODEL_NAME=(name of your model)
|
12 |
+
prefix=(basically, if you use vicuna it's Human: , if you use something else it might be User: , etc)
|
13 |
+
opts=(add -instruct here if needed for your model, or anything else you want to test out)
|
14 |
+
```
|
15 |
+
Step 2: Run `jeopardy.sh` from the llama.cpp folder
|
16 |
+
|
17 |
+
Step 3: Repeat steps 1 and 2 until you have all the results you need.
|
18 |
+
|
19 |
+
Step 4: Run `graph.py`, and follow the instructions. At the end, it will generate your final graph.
|
20 |
+
|
21 |
+
Note: The Human bar is based off of the full, original 100 sample questions. If you modify the question count or questions, it will not be valid.
|
examples/jeopardy/graph.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import matplotlib.pyplot as plt
|
2 |
+
import sys, os
|
3 |
+
import csv
|
4 |
+
|
5 |
+
labels = []
|
6 |
+
numbers = []
|
7 |
+
numEntries = 1
|
8 |
+
|
9 |
+
rows = []
|
10 |
+
|
11 |
+
def bar_chart(numbers, labels, pos):
|
12 |
+
plt.bar(pos, numbers, color='blue')
|
13 |
+
plt.xticks(ticks=pos, labels=labels)
|
14 |
+
plt.title("Jeopardy Results by Model")
|
15 |
+
plt.xlabel("Model")
|
16 |
+
plt.ylabel("Questions Correct")
|
17 |
+
plt.show()
|
18 |
+
|
19 |
+
def calculatecorrect():
|
20 |
+
directory = os.fsencode("./examples/jeopardy/results/")
|
21 |
+
csv_reader = csv.reader(open("./examples/jeopardy/qasheet.csv", 'rt'), delimiter=',')
|
22 |
+
for row in csv_reader:
|
23 |
+
global rows
|
24 |
+
rows.append(row)
|
25 |
+
for listing in os.listdir(directory):
|
26 |
+
filename = os.fsdecode(listing)
|
27 |
+
if filename.endswith(".txt"):
|
28 |
+
file = open("./examples/jeopardy/results/" + filename, "rt")
|
29 |
+
global labels
|
30 |
+
global numEntries
|
31 |
+
global numbers
|
32 |
+
labels.append(filename[:-4])
|
33 |
+
numEntries += 1
|
34 |
+
i = 1
|
35 |
+
totalcorrect = 0
|
36 |
+
for line in file.readlines():
|
37 |
+
if line.strip() != "------":
|
38 |
+
print(line)
|
39 |
+
else:
|
40 |
+
print("Correct answer: " + rows[i][2] + "\n")
|
41 |
+
i+=1
|
42 |
+
print("Did the AI get the question right? (y/n)")
|
43 |
+
if input() == "y":
|
44 |
+
totalcorrect += 1
|
45 |
+
numbers.append(totalcorrect)
|
46 |
+
|
47 |
+
|
48 |
+
|
49 |
+
if __name__ == '__main__':
|
50 |
+
calculatecorrect()
|
51 |
+
pos = list(range(numEntries))
|
52 |
+
labels.append("Human")
|
53 |
+
numbers.append(48.11)
|
54 |
+
bar_chart(numbers, labels, pos)
|
55 |
+
print(labels)
|
56 |
+
print(numbers)
|
examples/jeopardy/jeopardy.sh
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
set -e
|
3 |
+
|
4 |
+
MODEL=./models/ggml-vicuna-13b-1.1-q4_0.bin
|
5 |
+
MODEL_NAME=Vicuna
|
6 |
+
|
7 |
+
# exec options
|
8 |
+
prefix="Human: " # Ex. Vicuna uses "Human: "
|
9 |
+
opts="--temp 0 -n 80" # additional flags
|
10 |
+
nl='
|
11 |
+
'
|
12 |
+
introduction="You will be playing a game of Jeopardy. Simply answer the question in the correct format (Ex. What is Paris, or Who is George Washington)."
|
13 |
+
|
14 |
+
# file options
|
15 |
+
question_file=./examples/jeopardy/questions.txt
|
16 |
+
touch ./examples/jeopardy/results/$MODEL_NAME.txt
|
17 |
+
output_file=./examples/jeopardy/results/$MODEL_NAME.txt
|
18 |
+
|
19 |
+
counter=1
|
20 |
+
|
21 |
+
echo 'Running'
|
22 |
+
while IFS= read -r question
|
23 |
+
do
|
24 |
+
exe_cmd="./main -p "\"$prefix$introduction$nl$prefix$question\"" "$opts" -m ""\"$MODEL\""" >> ""\"$output_file\""
|
25 |
+
echo $counter
|
26 |
+
echo "Current Question: $question"
|
27 |
+
eval "$exe_cmd"
|
28 |
+
echo -e "\n------" >> $output_file
|
29 |
+
counter=$((counter+1))
|
30 |
+
done < "$question_file"
|
examples/jeopardy/qasheet.csv
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Index,Original Category,Original Correct Question,Model Prompt
|
2 |
+
1,The Oscars,Who is John Williams?,Which actor Born in 1932 was the son of a percussionist in the CBS radio orchestra has been nominated for 53 Oscars?
|
3 |
+
2,English Literature,What is Paradise Lost?,"What work in English Literature says: 'The mind is its own place, & in itself can make a heaven of hell, a hell of heaven. What matter where, if I be still the same'?"
|
4 |
+
3,Writers’ Lesser-Known Works,Who is Niccolò Machiavelli?,"Known for more philosophical works, he wrote the play 'La Mandragola', in which Florentines are rewarded for immoral actions?"
|
5 |
+
4,Exploration,What is Easter Island (Rapa Nui)?,"James Cook's account of a 1774 visit where records an object 'near 27 feet long, and upwards of 8 feet over the breast or shoulders'?"
|
6 |
+
5,The Bill of Rights,What is the Eighth Amendment?,England's 'Bloody Assizes' & a 1685 life sentence for perjury were 2 main origins of which amendment to the U.S. Constitution?
|
7 |
+
6,Nobel Peace Prize Winners,Who are Nelson Mandela & Desmond Tutu?,"Which nobel peace price winners each lived at times on Vilakazi St. in Soweto , so it claims to be the world's only street home to 2 Nobel Peace Prize winners?"
|
8 |
+
7,Famous Names,Who is Walt Disney?,"In 1966, the year of who's death did he share plans for an experimental prototype community in Florida?"
|
9 |
+
8,Geography,What is Colombia?,"Of the 13 nations through which the Equator passes, what is the only one whose coastline borders the Caribbean Sea?"
|
10 |
+
9,Fashion History,What are rhinestones?,"Which decorative items in fashion history get their name from their origin in the port city of Strasbourg, on the border of France & Germany?"
|
11 |
+
10,Movies of the ’80s,What is Driving Miss Daisy?,What 1980's movie is based on an off-Broadway play with just 3 characters and won the Best Picture Oscar & the actors in all 3 roles were nominated?
|
12 |
+
11,Novelists,Who is John Grisham?,"A 2012 book review for which novelist noted subjects that 'sparked his ire': capital punishment, big tobacco & 'the plight of the unjustly convicted'?"
|
13 |
+
12,20th Century Eponyms,What is the Maginot Line?,"A 1940 headline about what 20th Century Eponym included 'failure', 'liability when it came to offense' & 'stout hearts no match for tanks'?"
|
14 |
+
13,City History,What is Stockholm?,"Over 700 years after its traditional 1252 founding date, what port city became associated with a psychological response?"
|
15 |
+
14,Brand Names,What is Jacuzzi?,"The success of what brand has its roots with a hydrotherapy pump its cofounder created for his son, who had arthritis?"
|
16 |
+
15,American Authors,Who is Washington Irving?,"In a periodical in 1807, what American Author called New York City 'Gotham, Gotham! Most enlightened of cities'?"
|
17 |
+
16,Symbols,What is “less than”?,What symbol is a rotated V in math and a feeling of some marginalized or underrepresented people in society?
|
18 |
+
17,Movie Theme Songs,Who is James Bond?,"Monty Norman, the composer of what character's theme, said the staccato riff conveyed sexiness, mystery & ruthlessness?"
|
19 |
+
18,American Novelists,Who is Joseph Heller?,"What American Novelist served with an airman named Yohannan in World War II & despite what readers might think, he said he enjoyed his service?"
|
20 |
+
19,Medieval Places,"What is Canterbury, England? (Canterbury Cathedral)","In what Medieval place did one of the participants in an 1170 event say, 'Let us away, knights; he will rise no more'?"
|
21 |
+
20,Countries of Africa,What is Morocco?,"At one time a province of the Roman Empire, what African country kingdom is known to Arabic scholars as Al-Maghrib Al-Aqsa, 'the far west'?"
|
22 |
+
21,Statehood,What is Wyoming?,Congress relented in 1890 after what prospective state said it would wait 100 years rather than come in without the women?
|
23 |
+
22,1980s Movies,What is Raiders of the Lost Ark?,"A writer & producer of what movie said he wanted it to be like a Western or James Bond film, 'only it takes place in the 30s'?"
|
24 |
+
23,Art Exhibitions,Who is Rembrandt?,In 1898 what's been called the first blockbuster art show was devoted to which artist & put on for Queen Wilhelmina's coronation?
|
25 |
+
24,Countries of the World,What is Mongolia?,"Part of the largest contiguous land empire during the 1200s & 1300s, today what is the world's second-largest landlocked country?"
|
26 |
+
25,Literature,What is “Howl”?,A 2006 book was titled 'The Poem That Changed America:' What 'Fifty Years Later'?
|
27 |
+
26,Invasions,Who is William of Orange?,"Backed by 14,000 troops, who invaded England to restore, in his words, its 'religion, laws, and liberties'?"
|
28 |
+
27,Landmarks,What is the Eiffel Tower?,"After its completion in the late 19th c., what was landmark was called 'a truly tragic street lamp' & a 'high & skinny pyramid of iron ladders'?"
|
29 |
+
28,Geographic Name’s the Same,What is Dover?,"The busiest passenger port in the U.K., what shares its name with a capital of one of the original 13 states?"
|
30 |
+
29,Names in the Bookstore,Who is Peter Mark Roget?,"This man made lists, perhaps to cope with depression; a set of lists he published in 1852 made whose name synonymous with a type of book?"
|
31 |
+
30,U.S. History,Who is Dr. Samuel Mudd?,"An 1869 presidential pardon was granted to which man, due in part to a plea by the Medical Society of Harford County, Maryland?"
|
32 |
+
31,American Literature,What is The Things They Carried?,"Letters, pocket knives, C rations & steel helmets are among the tangible items referred to in the title of what American literature modern war classic?"
|
33 |
+
32,Nonfiction,What is The Communist Manifesto,"What nonfiction book has the line, 'The discovery of America…opened up fresh ground for the rising bourgeoisie'?"
|
34 |
+
33, a new version was passed 81 years later,Laws in U.S. History,What is the Civil Rights Act?,,,,,,,,,,,,,,,,,,0, 2/3
|
35 |
+
34,Names of Myth,Who is Helen of Troy?,"Whose brothers, Castor & Pollux, saved her after Theseus stole her away as a kid; a larger force would seek her later in life?"
|
36 |
+
35,African Countries,What is Sudan?,"Once Africa's largest country in area, what African Country dropped to third in 2011 when a portion of it declared independence?"
|
37 |
+
36,The Ancient World,What is Alexandria?,"The ancient writer Galen said books on ships arriving to what city's port were seized, originals kept & copies returned?"
|
38 |
+
37,Famous Names,Who is Andy Warhol?,"For a special 1970s cookbook, who provided one simple recipe–a can of Campbell's tomato soup & 2 cans of milk?"
|
39 |
+
38,People & Places,What is Guam?,"Thought to descend from people of Southeast Asia, the Chamorro make up what U.S. territory’s largest ethnic group?"
|
40 |
+
39,Current World Leaders,What is the Philippines?,"In office from 2022, the president of what country has taken so many foreign trips a play on his name is 'Ferdinand Magellan Jr.'?"
|
41 |
+
40,Writers & The South,Who is Tennessee Williams?,In 1939 which writer lived on Toulouse Street in the French Quarter & chose the professional name that bonded him to the South?
|
42 |
+
41,National Parks,What is Yellowstone?,"What National Park is named for a river indigenous people called Mi tse a-da-zi, translated by French-speaking trappers as 'Pierre Jaune'?"
|
43 |
+
42,Sports,Who are the Harlem Globetrotters?,"In 2010 who introduced the 4-point shot, 35 feet from the basket?"
|
44 |
+
43,The U.S. Military,What is “Top Gun”?,Losses over Asia in the 1960s led to the establishment of the program known as what at a San Diego naval base in 1969?
|
45 |
+
44,Art & Science,What is Halley’s Comet?,"A craft that visited what was named for Giotto, based on the story that 680 years earlier, the painter depicted it as the Star of Bethlehem?"
|
46 |
+
45,Words From World War I,What is “tank”?,"In World War I, 'Cistern' & 'reservoir' were suggested names for what secret invention, but the British preferred this less clumsy monosyllable?"
|
47 |
+
46,European History,What is Holy Roman Emperor?,"Until 1806, some German nobles included among their honors the title of 'Elector' for their role in selecting this personage?"
|
48 |
+
47,Theater History,Who is Peter Pan?,"In 1904, wearing a harness, actress Nina Boucicault became the first to play what character onstage?"
|
49 |
+
48,European Cities,What is Aachen?,"Alphabetically the first German city in encyclopedias, what was also the first one taken by the Allies in World War II?"
|
50 |
+
49,Word Origins,What is mantra?,This Sanskrit word referring to a spoken word or phrase comes from a word for 'to think'?
|
51 |
+
50,Inventions,What is barbed wire?,1917's 'Elements of Trench Warfare' said what Old West invention was 'difficult to destroy' & 'difficult to get through'?
|
52 |
+
51,World War II,What is Schindler’s list?,"Mimi Reinhard, who never learned to type using more than 2 fingers, produced what in World War II with 1,100 names, including hers?"
|
53 |
+
52, their offspring was the source of this mythical object,Mythology,What is the Golden Fleece?
|
54 |
+
53,Literature,What is Pride and Prejudice?,"Published in 2011, P.D. James' final novel, 'Death Comes to Pemberley', was a sequel to what novel from 200 years earlier?"
|
55 |
+
54, only these 2 west of the Mississippi River border each other,U.S. State Names,What are Oregon & Nevada?
|
56 |
+
55,Word Origins,What is passion?,"Originally relating to a story of suffering, what word now more commonly refers to strong emotion of any kind?"
|
57 |
+
56,World Cinema,What is La Vie en Rose?,"The 2007 biopic called 'La Môme' in France, meaning 'The Kid', was released in the U.S. under what other French title?"
|
58 |
+
57,History,What is Santa Maria?,"Returning home in 1493, Columbus stopped in the Azores at an island with what name, also something he'd lost off the Haiti coast?"
|
59 |
+
58,Landmarks,What is a kremlin?,Pskov & Nizhny Novgorod are 2 of the cities that have a fortress called what?
|
60 |
+
59,Foreign-Born Authors,Who is Vladimir Nabokov?,In the 1950s the New York Times said what author 'is writing about all lust' & his lecherous narrator 'is all of us'?
|
61 |
+
60,Astronomy & Geography,What is Capricorn?,"At the winter solstice, the sun is in Sagittarius; it once appeared in what constellation, giving a geographic feature its name?"
|
62 |
+
61,Television,What is Law & Order?,"Mike Post combined the sound of a slamming jail door, an anvil & 100 men stomping on a floor for what television series that debuted in 1990?"
|
63 |
+
62,British Landmarks,What is the Tower of London?,"Like Sir Thomas More, 3 16th century English queens are buried at what British location?"
|
64 |
+
63,Early American History,What are witches?,"In 1692 Increase Mather wrote, 'It were better that ten suspected' of these who 'escape, than that one innocent person … be condemned'?"
|
65 |
+
64,Geography Mnemonics,What are Arkansas and Louisiana?,"The Geography Mnemonic Mimal, sometimes said to be the silhouette of a chef or elf, stands for Minnesota, Iowa, Missouri, and what other 2 states?"
|
66 |
+
65,Business Milestones,What is the Ford Model T?,"What was first sold in 1908, at a price equivalent to about $27,000 today?"
|
67 |
+
66,In The Bookstore,Who is Tom Clancy?,The name of what author dead since 2013 now appears on books written by a former U.S. marshal & a former Apache helicopter pilot?
|
68 |
+
67,Historic Art,What is the Bayeux Tapestry?,The artwork once known in France as 'la tapisserie de la Reine Mathilde' is better known as what?
|
69 |
+
68,Pop Stars,Who is Madonna?,In 2022 which pop star became the first woman to have a Billboard Top 10 album in 5 decades starting with the 1980s?
|
70 |
+
69,Classic Tale Characters,Who is Scheherazade?,"In one 19th century translation, what female classic tale character 'perceived the dawn of day and ceased' speaking nearly 1,000 times?"
|
71 |
+
70,USA,What is Jack Daniel’s?,"Ironically, though what company founded in the 1860s is Moore County, Tennessee's largest employer, Moore is a dry county?"
|
72 |
+
71,Historic People,Who was William Bligh?,"After a 1789 event, who wrote, 'My first determination was to seek a supply of…water at Tofoa, & afterwards to sail for Tongataboo'?"
|
73 |
+
72,The Movies,What is The Godfather?,Laurence Olivier & Ernest Borgnine were considered for the lead role & Sergio Leone to direct for what film that turned 50 in 2022?
|
74 |
+
73,Continental Geography,What is Colombia?,"Until a 1903 secession, what country's contiguous territory spanned 2 continents?"
|
75 |
+
74,Foreign-Born Authors,Who is Isabel Allende?,"Early in her career which foreign-born author translated romance novels into Spanish, often changing the dialogue to make the heroines smarter?"
|
76 |
+
75,Historic Crimes,What is the Mona Lisa?,"Saying it was stolen by Napoleon, self-styled Italian patriot Vincenzo Peruggia took what in 1911?"
|
77 |
+
76,U.S. Bodies of Water,What is Lake Mead?,"Continuing a downward trend, in July 2022 what US body of water was at 27% capacity, its lowest level since 1937 when it was first being filled?"
|
78 |
+
77,Gods & Goddesses,Who is Aurora (or Eos)?,"Each morning which goddess began her ride in her chariot across the sky ahead of her brother Sol, or Helios?"
|
79 |
+
78,America At War,What is the Battle of New Orleans?,"Until the Civil War, the Jan. 8 date of what American battle of dubious military importance but big morale value was a national holiday?"
|
80 |
+
79,Children’s Books,What is The Velveteen Rabbit?,"Which children's book title character is told 'By the time you are real, most of your hair has been loved off your eyes drop out & you get shabby'?"
|
81 |
+
80,TV Finales,What is Grace and Frankie?,"In a TV reunion over 40 years in the making, Dolly Parton appeared as an angel named Agnes in the final episode of what comedy in 2022?"
|
82 |
+
81,American Poems,Who is Evangeline?,"In an 1847 American poem what character sees her town of Grand-Pré burned, but finally reunites with her beau for a kiss before his death?"
|
83 |
+
82,Famous Names,Who is Banksy?,"In 2001 who published a book called 'Banging Your Head Against a Brick Wall'; in 2002, 'Existencilism'?"
|
84 |
+
83,Children’s Lit,What is Charlotte’s Web?,The title object of what childrens book 'never looked more beautiful each strand held dozens of bright drops of early morning dew'?
|
85 |
+
84,Classic Songs,What is “Here Comes Santa Claus”?,The shouts of excited children at a 1946 holiday parade are said to have inspired what perennial classic song favorite?
|
86 |
+
85,Brand Names,What are Milk Duds?,"Unable to make what candies perfectly round, the confectioner embraced this flawed name for the product?"
|
87 |
+
86,Countries of the World,What is Italy?,"What country is home to 58 UNESCO World Heritage Sites, more than any other country; the sites include a volcano & a lagoon?"
|
88 |
+
87,Action Movies,What is Die Hard?,"What action movie's last line is 'If this is their idea of Christmas, I gotta be here for New Years'?"
|
89 |
+
88,Presidential Facts,Who is Woodrow Wilson?,Only 3 presidents have married while in office— John Tyler was the first & which one was the last?
|
90 |
+
89,19th Century Americans,Who is Frederick Douglass?,"Demonstrating the dignity & humanity of Black Americans, who sat for 160 known photographs, the most of any American in the 19th century?"
|
91 |
+
90,Latin Phrases,What is “quid pro quo”?,"Originally, which Latin 3-word phrase referred to when a doctor or apothecary substituted one medicine for another?"
|
92 |
+
91,1970s Movies,What is Monty Python and the Holy Grail?,The 1975 premiere of what movie comedy advertised free coconuts for the first thousand in the audience?
|
93 |
+
92,Name’s The Same,What is Manhattan?,"A cocktail, an island & a WWII venture originally called 'Development of Substitute Materials' all bear what name?"
|
94 |
+
93,U.S. Presidents,Who is Calvin Coolidge?,"Which US President was sworn in twice as President within 2 years, first by his father & then later by a former U.S. President?"
|
95 |
+
94,Plays,What is The Tempest?,A 1609 story in which an exiled king of Bulgaria creates a sea palace with his magic may have inspired the plot of what play?
|
96 |
+
95,Landmarks,What is the Berlin Wall?,"In 2009, during a 20th anniversary celebration, what landmark was called 'an edifice of fear. On Nov. 9, it became a place of joy'?"
|
97 |
+
96,World Capitals,"What is Vienna, Austria?","Among what world capital's nicknames are the 'City of Classical Music' &, possibly in honor of a famous resident from 1860 to 1938, the 'City of Dreams'?"
|
98 |
+
97,Language & Its Meanings,What is a night owl?,"Now meaning someone with nocturnal habits, what catches a sleeping dove in Shakespeare's 'Lucrece'?"
|
99 |
+
98,Flags of Our Hemisphere,What is Brazil?,"The stars on what country's flag represent states, 26 of them; unlike the USA's, its 'federal district' gets its own 27th star?"
|
100 |
+
99,Names in U.S. History,Who is Oliver Brown?,What father was the only man among the 13 plaintiffs in a US class-action case filed in 1951?
|
101 |
+
100,Children’s Authors,"Who is Sarah? (from Sarah, Plain and Tall)","Reversing the story of what heroine she created, childrens author Patricia Maclachlan was born on the prairie but spent much of her life in New England?"
|
102 |
+
,,,
|
103 |
+
TOTALS,,,
|
examples/jeopardy/questions.txt
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Which man born in 1932 was the son of a percussionist in the CBS radio orchestra has been nominated for 53 Oscars?
|
2 |
+
What work in English Literature says: 'The mind is its own place, & in itself can make a heaven of hell, a hell of heaven. What matter where, if I be still the same'?
|
3 |
+
Known for more philosophical works, he wrote the play 'La Mandragola', in which Florentines are rewarded for immoral actions?
|
4 |
+
James Cook's account of a 1774 visit where records an object 'near 27 feet long, and upwards of 8 feet over the breast or shoulders'?
|
5 |
+
England's 'Bloody Assizes' & a 1685 life sentence for perjury were 2 main origins of which amendment to the U.S. Constitution?
|
6 |
+
Which nobel peace price winners each lived at times on Vilakazi St. in Soweto , so it claims to be the world's only street home to 2 Nobel Peace Prize winners?
|
7 |
+
In 1966, the year of who's death did he share plans for an experimental prototype community in Florida?
|
8 |
+
Of the 13 nations through which the Equator passes, what is the only one whose coastline borders the Caribbean Sea?
|
9 |
+
Which decorative items in fashion history get their name from their origin in the port city of Strasbourg, on the border of France & Germany?
|
10 |
+
What 1980's movie is based on an off-Broadway play with just 3 characters and won the Best Picture Oscar & the actors in all 3 roles were nominated?
|
11 |
+
A 2012 book review for which novelist noted subjects that 'sparked his ire': capital punishment, big tobacco & 'the plight of the unjustly convicted'?
|
12 |
+
A 1940 headline about what 20th Century Eponym included 'failure', 'liability when it came to offense' & 'stout hearts no match for tanks'?
|
13 |
+
Over 700 years after its traditional 1252 founding date, what port city became associated with a psychological response?
|
14 |
+
The success of what brand has its roots with a hydrotherapy pump its cofounder created for his son, who had arthritis?
|
15 |
+
In a periodical in 1807, what American Author called New York City 'Gotham, Gotham! Most enlightened of cities'?
|
16 |
+
What symbol is a rotated V in math and a feeling of some marginalized or underrepresented people in society?
|
17 |
+
Monty Norman, the composer of what character's theme, said the staccato riff conveyed sexiness, mystery & ruthlessness?
|
18 |
+
What American Novelist served with an airman named Yohannan in World War II & despite what readers might think, he said he enjoyed his service?
|
19 |
+
In what Medieval place did one of the participants in an 1170 event say, 'Let us away, knights; he will rise no more'?
|
20 |
+
At one time a province of the Roman Empire, what African country kingdom is known to Arabic scholars as Al-Maghrib Al-Aqsa, 'the far west'?
|
21 |
+
Congress relented in 1890 after what prospective state said it would wait 100 years rather than come in without the women?
|
22 |
+
A writer & producer of what movie said he wanted it to be like a Western or James Bond film, 'only it takes place in the 30s'?
|
23 |
+
In 1898 what's been called the first blockbuster art show was devoted to which artist & put on for Queen Wilhelmina's coronation?
|
24 |
+
Part of the largest contiguous land empire during the 1200s & 1300s, today what is the world's second-largest landlocked country?
|
25 |
+
A 2006 book was titled 'The Poem That Changed America:' What 'Fifty Years Later'?
|
26 |
+
Backed by 14,000 troops, who invaded England to restore, in his words, its 'religion, laws, and liberties'?
|
27 |
+
After its completion in the late 19th c., what was landmark was called 'a truly tragic street lamp' & a 'high & skinny pyramid of iron ladders'?
|
28 |
+
The busiest passenger port in the U.K., what shares its name with a capital of one of the original 13 states?
|
29 |
+
This man made lists, perhaps to cope with depression; a set of lists he published in 1852 made whose name synonymous with a type of book?
|
30 |
+
An 1869 presidential pardon was granted to which man, due in part to a plea by the Medical Society of Harford County, Maryland?
|
31 |
+
Letters, pocket knives, C rations & steel helmets are among the tangible items referred to in the title of what American literature modern war classic?
|
32 |
+
What nonfiction book has the line, 'The discovery of America…opened up fresh ground for the rising bourgeoisie'?
|
33 |
+
A radical Republican championed what 1875 act but the Supreme Court struck it down in 1883; a new version was passed 81 years later?
|
34 |
+
Whose brothers, Castor & Pollux, saved her after Theseus stole her away as a kid; a larger force would seek her later in life?
|
35 |
+
Once Africa's largest country in area, what African Country dropped to third in 2011 when a portion of it declared independence?
|
36 |
+
The ancient writer Galen said books on ships arriving to what city's port were seized, originals kept & copies returned?
|
37 |
+
For a special 1970s cookbook, who provided one simple recipe–a can of Campbell's tomato soup & 2 cans of milk?
|
38 |
+
Thought to descend from people of Southeast Asia, the Chamorro make up what U.S. territory’s largest ethnic group?
|
39 |
+
In office from 2022, the president of what country has taken so many foreign trips a play on his name is 'Ferdinand Magellan Jr.'?
|
40 |
+
In 1939 which writer lived on Toulouse Street in the French Quarter & chose the professional name that bonded him to the South?
|
41 |
+
What National Park is named for a river indigenous people called Mi tse a-da-zi, translated by French-speaking trappers as 'Pierre Jaune'?
|
42 |
+
In 2010 who introduced the 4-point shot, 35 feet from the basket?
|
43 |
+
Losses over Asia in the 1960s led to the establishment of the program known as what at a San Diego naval base in 1969?
|
44 |
+
A craft that visited what was named for Giotto, based on the story that 680 years earlier, the painter depicted it as the Star of Bethlehem?
|
45 |
+
In World War I, 'Cistern' & 'reservoir' were suggested names for what secret invention, but the British preferred this less clumsy monosyllable?
|
46 |
+
Until 1806, some German nobles included among their honors the title of 'Elector' for their role in selecting this personage?
|
47 |
+
In 1904, wearing a harness, actress Nina Boucicault became the first to play what character onstage?
|
48 |
+
Alphabetically the first German city in encyclopedias, what was also the first one taken by the Allies in World War II?
|
49 |
+
This Sanskrit word referring to a spoken word or phrase comes from a word for 'to think'?
|
50 |
+
1917's 'Elements of Trench Warfare' said what Old West invention was 'difficult to destroy' & 'difficult to get through'?
|
51 |
+
Mimi Reinhard, who never learned to type using more than 2 fingers, produced what in World War II with 1,100 names, including hers?
|
52 |
+
Poseidon carried off the maiden Theophane & turned her into a ewe; their offspring was the source of what mythical object?
|
53 |
+
Published in 2011, P.D. James' final novel, 'Death Comes to Pemberley', was a sequel to what novel from 200 years earlier?
|
54 |
+
5 U.S. states have 6-letter names; only which 2 west of the Mississippi River border each other?
|
55 |
+
Originally relating to a story of suffering, what word now more commonly refers to strong emotion of any kind?
|
56 |
+
The 2007 biopic called 'La Môme' in France, meaning 'The Kid', was released in the U.S. under what other French title?
|
57 |
+
Returning home in 1493, Columbus stopped in the Azores at an island with what name, also something he'd lost off the Haiti coast?
|
58 |
+
Pskov & Nizhny Novgorod are 2 of the cities that have a fortress called what?
|
59 |
+
In the 1950s the New York Times said what author 'is writing about all lust' & his lecherous narrator 'is all of us'?
|
60 |
+
At the winter solstice, the sun is in Sagittarius; it once appeared in what constellation, giving a geographic feature its name?
|
61 |
+
Mike Post combined the sound of a slamming jail door, an anvil & 100 men stomping on a floor for what television series that debuted in 1990?
|
62 |
+
Like Sir Thomas More, 3 16th century English queens are buried at what British location?
|
63 |
+
In 1692 Increase Mather wrote, 'It were better that ten suspected' of these who 'escape, than that one innocent person be condemned'?
|
64 |
+
The Geography Mnemonic Mimal, sometimes said to be the silhouette of a chef or elf, stands for Minnesota, Iowa, Missouri, and what other 2 states?
|
65 |
+
What was first sold in 1908, at a price equivalent to about $27,000 today?
|
66 |
+
The name of what author dead since 2013 now appears on books written by a former U.S. marshal & a former Apache helicopter pilot?
|
67 |
+
The artwork once known in France as 'la tapisserie de la Reine Mathilde' is better known as what?
|
68 |
+
In 2022 which pop star became the first woman to have a Billboard Top 10 album in 5 decades starting with the 1980s?
|
69 |
+
In one 19th century translation, what female classic tale character 'perceived the dawn of day and ceased' speaking nearly 1,000 times?
|
70 |
+
Ironically, though what company founded in the 1860s is Moore County, Tennessee's largest employer, Moore is a dry county?
|
71 |
+
After a 1789 event, who wrote, 'My first determination was to seek a supply of…water at Tofoa, & afterwards to sail for Tongataboo'?
|
72 |
+
Laurence Olivier & Ernest Borgnine were considered for the lead role & Sergio Leone to direct for what film that turned 50 in 2022?
|
73 |
+
Until a 1903 secession, what country's contiguous territory spanned 2 continents?
|
74 |
+
Early in her career which foreign-born author translated romance novels into Spanish, often changing the dialogue to make the heroines smarter?
|
75 |
+
Saying it was stolen by Napoleon, self-styled Italian patriot Vincenzo Peruggia took what in 1911?
|
76 |
+
Continuing a downward trend, in July 2022 what US body of water was at 27% capacity, its lowest level since 1937 when it was first being filled?
|
77 |
+
Each morning which goddess began her ride in her chariot across the sky ahead of her brother Sol, or Helios?
|
78 |
+
Until the Civil War, the Jan. 8 date of what American battle of dubious military importance but big morale value was a national holiday?
|
79 |
+
Which children's book title character is told 'By the time you are real, most of your hair has been loved off your eyes drop out & you get shabby'?
|
80 |
+
In a TV reunion over 40 years in the making, Dolly Parton appeared as an angel named Agnes in the final episode of what comedy in 2022?
|
81 |
+
In an 1847 American poem what character sees her town of Grand-Pré burned, but finally reunites with her beau for a kiss before his death?
|
82 |
+
In 2001 who published a book called 'Banging Your Head Against a Brick Wall'; in 2002, 'Existencilism'?
|
83 |
+
The title object of what childrens book 'never looked more beautiful each strand held dozens of bright drops of early morning dew'?
|
84 |
+
The shouts of excited children at a 1946 holiday parade are said to have inspired what perennial classic song favorite?
|
85 |
+
Unable to make what candies perfectly round, the confectioner embraced this flawed name for the product?
|
86 |
+
What country is home to 58 UNESCO World Heritage Sites, more than any other country; the sites include a volcano & a lagoon?
|
87 |
+
What action movie's last line is 'If this is their idea of Christmas, I gotta be here for New Years'?
|
88 |
+
Only 3 presidents have married while in office— John Tyler was the first & which one was the last?
|
89 |
+
Demonstrating the dignity & humanity of Black Americans, who sat for 160 known photographs, the most of any American in the 19th century?
|
90 |
+
Originally, which Latin 3-word phrase referred to when a doctor or apothecary substituted one medicine for another?
|
91 |
+
The 1975 premiere of what movie comedy advertised free coconuts for the first thousand in the audience?
|
92 |
+
A cocktail, an island & a WWII venture originally called 'Development of Substitute Materials' all bear what name?
|
93 |
+
Which US President was sworn in twice as President within 2 years, first by his father & then later by a former U.S. President?
|
94 |
+
A 1609 story in which an exiled king of Bulgaria creates a sea palace with his magic may have inspired the plot of what play?
|
95 |
+
In 2009, during a 20th anniversary celebration, what landmark was called 'an edifice of fear. On Nov. 9, it became a place of joy'?
|
96 |
+
Among what world capital's nicknames are the 'City of Classical Music' &, possibly in honor of a famous resident from 1860 to 1938, the 'City of Dreams'?
|
97 |
+
Now meaning someone with nocturnal habits, what catches a sleeping dove in Shakespeare's 'Lucrece'?
|
98 |
+
The stars on what country's flag represent states, 26 of them; unlike the USA's, its 'federal district' gets its own 27th star?
|
99 |
+
What father was the only man among the 13 plaintiffs in a US class-action case filed in 1951?
|
100 |
+
Reversing the story of what heroine she created, childrens author Patricia Maclachlan was born on the prairie but spent much of her life in New England?
|
examples/main/CMakeLists.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set(TARGET main)
|
2 |
+
add_executable(${TARGET} main.cpp)
|
3 |
+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
|
4 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_11)
|
5 |
+
if(TARGET BUILD_INFO)
|
6 |
+
add_dependencies(${TARGET} BUILD_INFO)
|
7 |
+
endif()
|
examples/main/README.md
ADDED
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# llama.cpp/example/main
|
2 |
+
|
3 |
+
This example program allows you to use various LLaMA language models in an easy and efficient way. It is specifically designed to work with the [llama.cpp](https://github.com/ggerganov/llama.cpp) project, which provides a plain C/C++ implementation with optional 4-bit quantization support for faster, lower memory inference, and is optimized for desktop CPUs. This program can be used to perform various inference tasks with LLaMA models, including generating text based on user-provided prompts and chat-like interactions with reverse prompts.
|
4 |
+
|
5 |
+
## Table of Contents
|
6 |
+
|
7 |
+
1. [Quick Start](#quick-start)
|
8 |
+
2. [Common Options](#common-options)
|
9 |
+
3. [Input Prompts](#input-prompts)
|
10 |
+
4. [Interaction](#interaction)
|
11 |
+
5. [Context Management](#context-management)
|
12 |
+
6. [Generation Flags](#generation-flags)
|
13 |
+
7. [Performance Tuning and Memory Options](#performance-tuning-and-memory-options)
|
14 |
+
8. [Additional Options](#additional-options)
|
15 |
+
|
16 |
+
## Quick Start
|
17 |
+
|
18 |
+
To get started right away, run the following command, making sure to use the correct path for the model you have:
|
19 |
+
|
20 |
+
#### Unix-based systems (Linux, macOS, etc.):
|
21 |
+
|
22 |
+
```bash
|
23 |
+
./main -m models/7B/ggml-model.bin --prompt "Once upon a time"
|
24 |
+
```
|
25 |
+
|
26 |
+
#### Windows:
|
27 |
+
|
28 |
+
```powershell
|
29 |
+
main.exe -m models\7B\ggml-model.bin --prompt "Once upon a time"
|
30 |
+
```
|
31 |
+
|
32 |
+
For an interactive experience, try this command:
|
33 |
+
|
34 |
+
#### Unix-based systems (Linux, macOS, etc.):
|
35 |
+
|
36 |
+
```bash
|
37 |
+
./main -m models/7B/ggml-model.bin -n -1 --color -r "User:" --in-prefix " " \
|
38 |
+
'User: Hi
|
39 |
+
AI: Hello. I am an AI chatbot. Would you like to talk?
|
40 |
+
User: Sure!
|
41 |
+
AI: What would you like to talk about?
|
42 |
+
User:'
|
43 |
+
```
|
44 |
+
|
45 |
+
#### Windows:
|
46 |
+
|
47 |
+
```powershell
|
48 |
+
main.exe -m models\7B\ggml-model.bin -n -1 --color -r "User:" --in-prefix " " -e --prompt "User: Hi\nAI: Hello. I am an AI chatbot. Would you like to talk?\nUser: Sure!\nAI: What would you like to talk about?\nUser:"
|
49 |
+
```
|
50 |
+
|
51 |
+
The following command generates "infinite" text from a starting prompt (you can use `Ctrl-C` to stop it):
|
52 |
+
|
53 |
+
#### Unix-based systems (Linux, macOS, etc.):
|
54 |
+
|
55 |
+
```bash
|
56 |
+
./main -m models/7B/ggml-model.bin --ignore-eos -n -1 --random-prompt
|
57 |
+
```
|
58 |
+
|
59 |
+
#### Windows:
|
60 |
+
|
61 |
+
```powershell
|
62 |
+
main.exe -m models\7B\ggml-model.bin --ignore-eos -n -1 --random-prompt
|
63 |
+
```
|
64 |
+
|
65 |
+
## Common Options
|
66 |
+
|
67 |
+
In this section, we cover the most commonly used options for running the `main` program with the LLaMA models:
|
68 |
+
|
69 |
+
- `-m FNAME, --model FNAME`: Specify the path to the LLaMA model file (e.g., `models/7B/ggml-model.bin`).
|
70 |
+
- `-i, --interactive`: Run the program in interactive mode, allowing you to provide input directly and receive real-time responses.
|
71 |
+
- `-ins, --instruct`: Run the program in instruction mode, which is particularly useful when working with Alpaca models.
|
72 |
+
- `-n N, --n-predict N`: Set the number of tokens to predict when generating text. Adjusting this value can influence the length of the generated text.
|
73 |
+
- `-c N, --ctx-size N`: Set the size of the prompt context. The default is 512, but LLaMA models were built with a context of 2048, which will provide better results for longer input/inference.
|
74 |
+
|
75 |
+
## Input Prompts
|
76 |
+
|
77 |
+
The `main` program provides several ways to interact with the LLaMA models using input prompts:
|
78 |
+
|
79 |
+
- `--prompt PROMPT`: Provide a prompt directly as a command-line option.
|
80 |
+
- `--file FNAME`: Provide a file containing a prompt or multiple prompts.
|
81 |
+
- `--interactive-first`: Run the program in interactive mode and wait for input right away. (More on this below.)
|
82 |
+
- `--random-prompt`: Start with a randomized prompt.
|
83 |
+
|
84 |
+
## Interaction
|
85 |
+
|
86 |
+
The `main` program offers a seamless way to interact with LLaMA models, allowing users to engage in real-time conversations or provide instructions for specific tasks. The interactive mode can be triggered using various options, including `--interactive`, `--interactive-first`, and `--instruct`.
|
87 |
+
|
88 |
+
In interactive mode, users can participate in text generation by injecting their input during the process. Users can press `Ctrl+C` at any time to interject and type their input, followed by pressing `Return` to submit it to the LLaMA model. To submit additional lines without finalizing input, users can end the current line with a backslash (`\`) and continue typing.
|
89 |
+
|
90 |
+
### Interaction Options
|
91 |
+
|
92 |
+
- `-i, --interactive`: Run the program in interactive mode, allowing users to engage in real-time conversations or provide specific instructions to the model.
|
93 |
+
- `--interactive-first`: Run the program in interactive mode and immediately wait for user input before starting the text generation.
|
94 |
+
- `-ins, --instruct`: Run the program in instruction mode, which is specifically designed to work with Alpaca models that excel in completing tasks based on user instructions.
|
95 |
+
- `--color`: Enable colorized output to differentiate visually distinguishing between prompts, user input, and generated text.
|
96 |
+
|
97 |
+
By understanding and utilizing these interaction options, you can create engaging and dynamic experiences with the LLaMA models, tailoring the text generation process to your specific needs.
|
98 |
+
|
99 |
+
### Reverse Prompts
|
100 |
+
|
101 |
+
Reverse prompts are a powerful way to create a chat-like experience with a LLaMA model by pausing the text generation when specific text strings are encountered:
|
102 |
+
|
103 |
+
- `-r PROMPT, --reverse-prompt PROMPT`: Specify one or multiple reverse prompts to pause text generation and switch to interactive mode. For example, `-r "User:"` can be used to jump back into the conversation whenever it's the user's turn to speak. This helps create a more interactive and conversational experience. However, the reverse prompt doesn't work when it ends with a space.
|
104 |
+
|
105 |
+
To overcome this limitation, you can use the `--in-prefix` flag to add a space or any other characters after the reverse prompt.
|
106 |
+
|
107 |
+
### In-Prefix
|
108 |
+
|
109 |
+
The `--in-prefix` flag is used to add a prefix to your input, primarily, this is used to insert a space after the reverse prompt. Here's an example of how to use the `--in-prefix` flag in conjunction with the `--reverse-prompt` flag:
|
110 |
+
|
111 |
+
```sh
|
112 |
+
./main -r "User:" --in-prefix " "
|
113 |
+
```
|
114 |
+
|
115 |
+
### In-Suffix
|
116 |
+
|
117 |
+
The `--in-suffix` flag is used to add a suffix after your input. This is useful for adding an "Assistant:" prompt after the user's input. It's added after the new-line character (`\n`) that's automatically added to the end of the user's input. Here's an example of how to use the `--in-suffix` flag in conjunction with the `--reverse-prompt` flag:
|
118 |
+
|
119 |
+
```sh
|
120 |
+
./main -r "User:" --in-prefix " " --in-suffix "Assistant:"
|
121 |
+
```
|
122 |
+
|
123 |
+
### Instruction Mode
|
124 |
+
|
125 |
+
Instruction mode is particularly useful when working with Alpaca models, which are designed to follow user instructions for specific tasks:
|
126 |
+
|
127 |
+
- `-ins, --instruct`: Enable instruction mode to leverage the capabilities of Alpaca models in completing tasks based on user-provided instructions.
|
128 |
+
|
129 |
+
Technical detail: the user's input is internally prefixed with the reverse prompt (or `### Instruction:` as the default), and followed by `### Response:` (except if you just press Return without any input, to keep generating a longer response).
|
130 |
+
|
131 |
+
By understanding and utilizing these interaction options, you can create engaging and dynamic experiences with the LLaMA models, tailoring the text generation process to your specific needs.
|
132 |
+
|
133 |
+
## Context Management
|
134 |
+
|
135 |
+
During text generation, LLaMA models have a limited context size, which means they can only consider a certain number of tokens from the input and generated text. When the context fills up, the model resets internally, potentially losing some information from the beginning of the conversation or instructions. Context management options help maintain continuity and coherence in these situations.
|
136 |
+
|
137 |
+
### Context Size
|
138 |
+
|
139 |
+
The `--ctx-size` option allows you to set the size of the prompt context used by the LLaMA models during text generation. A larger context size helps the model to better comprehend and generate responses for longer input or conversations.
|
140 |
+
|
141 |
+
- `-c N, --ctx-size N`: Set the size of the prompt context (default: 512). The LLaMA models were built with a context of 2048, which will yield the best results on longer input/inference. However, increasing the context size beyond 2048 may lead to unpredictable results.
|
142 |
+
|
143 |
+
### Keep Prompt
|
144 |
+
|
145 |
+
The `--keep` option allows users to retain the original prompt when the model runs out of context, ensuring a connection to the initial instruction or conversation topic is maintained.
|
146 |
+
|
147 |
+
- `--keep N`: Specify the number of tokens from the initial prompt to retain when the model resets its internal context. By default, this value is set to 0 (meaning no tokens are kept). Use `-1` to retain all tokens from the initial prompt.
|
148 |
+
|
149 |
+
By utilizing context management options like `--ctx-size` and `--keep`, you can maintain a more coherent and consistent interaction with the LLaMA models, ensuring that the generated text remains relevant to the original prompt or conversation.
|
150 |
+
|
151 |
+
## Generation Flags
|
152 |
+
|
153 |
+
The following options allow you to control the text generation process and fine-tune the diversity, creativity, and quality of the generated text according to your needs. By adjusting these options and experimenting with different combinations of values, you can find the best settings for your specific use case.
|
154 |
+
|
155 |
+
### Number of Tokens to Predict
|
156 |
+
|
157 |
+
- `-n N, --n-predict N`: Set the number of tokens to predict when generating text (default: 128, -1 = infinity).
|
158 |
+
|
159 |
+
The `--n-predict` option controls the number of tokens the model generates in response to the input prompt. By adjusting this value, you can influence the length of the generated text. A higher value will result in longer text, while a lower value will produce shorter text. A value of -1 will cause text to be generated without limit.
|
160 |
+
|
161 |
+
It is important to note that the generated text may be shorter than the specified number of tokens if an End-of-Sequence (EOS) token or a reverse prompt is encountered. In interactive mode text generation will pause and control will be returned to the user. In non-interactive mode, the program will end. In both cases, the text generation may stop before reaching the specified `n-predict` value. If you want the model to keep going without ever producing End-of-Sequence on its own, you can use the `--ignore-eos` parameter.
|
162 |
+
|
163 |
+
### Temperature
|
164 |
+
|
165 |
+
- `--temp N`: Adjust the randomness of the generated text (default: 0.8).
|
166 |
+
|
167 |
+
Temperature is a hyperparameter that controls the randomness of the generated text. It affects the probability distribution of the model's output tokens. A higher temperature (e.g., 1.5) makes the output more random and creative, while a lower temperature (e.g., 0.5) makes the output more focused, deterministic, and conservative. The default value is 0.8, which provides a balance between randomness and determinism. At the extreme, a temperature of 0 will always pick the most likely next token, leading to identical outputs in each run.
|
168 |
+
|
169 |
+
Example usage: `--temp 0.5`
|
170 |
+
|
171 |
+
### Repeat Penalty
|
172 |
+
|
173 |
+
- `--repeat-penalty N`: Control the repetition of token sequences in the generated text (default: 1.1).
|
174 |
+
- `--repeat-last-n N`: Last n tokens to consider for penalizing repetition (default: 64, 0 = disabled, -1 = ctx-size).
|
175 |
+
- `--no-penalize-nl`: Disable penalization for newline tokens when applying the repeat penalty.
|
176 |
+
|
177 |
+
The `repeat-penalty` option helps prevent the model from generating repetitive or monotonous text. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. The default value is 1.1.
|
178 |
+
|
179 |
+
The `repeat-last-n` option controls the number of tokens in the history to consider for penalizing repetition. A larger value will look further back in the generated text to prevent repetitions, while a smaller value will only consider recent tokens. A value of 0 disables the penalty, and a value of -1 sets the number of tokens considered equal to the context size (`ctx-size`).
|
180 |
+
|
181 |
+
Use the `--no-penalize-nl` option to disable newline penalization when applying the repeat penalty. This option is particularly useful for generating chat conversations, dialogues, code, poetry, or any text where newline tokens play a significant role in structure and formatting. Disabling newline penalization helps maintain the natural flow and intended formatting in these specific use cases.
|
182 |
+
|
183 |
+
Example usage: `--repeat-penalty 1.15 --repeat-last-n 128 --no-penalize-nl`
|
184 |
+
|
185 |
+
### Top-K Sampling
|
186 |
+
|
187 |
+
- `--top-k N`: Limit the next token selection to the K most probable tokens (default: 40).
|
188 |
+
|
189 |
+
Top-k sampling is a text generation method that selects the next token only from the top k most likely tokens predicted by the model. It helps reduce the risk of generating low-probability or nonsensical tokens, but it may also limit the diversity of the output. A higher value for top-k (e.g., 100) will consider more tokens and lead to more diverse text, while a lower value (e.g., 10) will focus on the most probable tokens and generate more conservative text. The default value is 40.
|
190 |
+
|
191 |
+
Example usage: `--top-k 30`
|
192 |
+
|
193 |
+
### Top-P Sampling
|
194 |
+
|
195 |
+
- `--top-p N`: Limit the next token selection to a subset of tokens with a cumulative probability above a threshold P (default: 0.9).
|
196 |
+
|
197 |
+
Top-p sampling, also known as nucleus sampling, is another text generation method that selects the next token from a subset of tokens that together have a cumulative probability of at least p. This method provides a balance between diversity and quality by considering both the probabilities of tokens and the number of tokens to sample from. A higher value for top-p (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. The default value is 0.9.
|
198 |
+
|
199 |
+
Example usage: `--top-p 0.95`
|
200 |
+
|
201 |
+
### Tail Free Sampling (TFS)
|
202 |
+
|
203 |
+
- `--tfs N`: Enable tail free sampling with parameter z (default: 1.0, 1.0 = disabled).
|
204 |
+
|
205 |
+
Tail free sampling (TFS) is a text generation technique that aims to reduce the impact of less likely tokens, which may be less relevant, less coherent, or nonsensical, on the output. The method adjusts the logits (token probabilities) by raising them to the power of the parameter z. A higher value of z (e.g., 2.0) will further suppress less likely tokens from the tail of the distribution, while a value of 1.0 disables the effect of TFS. By setting the parameter z, you can control how much the probabilities of less likely tokens are reduced.
|
206 |
+
|
207 |
+
Example usage: `--tfs 2.0`
|
208 |
+
|
209 |
+
### Locally Typical Sampling
|
210 |
+
|
211 |
+
- `--typical N`: Enable locally typical sampling with parameter p (default: 1.0, 1.0 = disabled).
|
212 |
+
|
213 |
+
Locally typical sampling promotes the generation of contextually coherent and diverse text by sampling tokens that are typical or expected based on the surrounding context. By setting the parameter p between 0 and 1, you can control the balance between producing text that is locally coherent and diverse. A value closer to 1 will promote more contextually coherent tokens, while a value closer to 0 will promote more diverse tokens. A value equal to 1 disables locally typical sampling.
|
214 |
+
|
215 |
+
Example usage: `--typical 0.9`
|
216 |
+
|
217 |
+
### Mirostat Sampling
|
218 |
+
|
219 |
+
- `--mirostat N`: Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0).
|
220 |
+
- `--mirostat-lr N`: Set the Mirostat learning rate, parameter eta (default: 0.1).
|
221 |
+
- `--mirostat-ent N`: Set the Mirostat target entropy, parameter tau (default: 5.0).
|
222 |
+
|
223 |
+
Mirostat is an algorithm that actively maintains the quality of generated text within a desired range during text generation. It aims to strike a balance between coherence and diversity, avoiding low-quality output caused by excessive repetition (boredom traps) or incoherence (confusion traps).
|
224 |
+
|
225 |
+
The `--mirostat-lr` option sets the Mirostat learning rate (eta). The learning rate influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. The default value is `0.1`.
|
226 |
+
|
227 |
+
The `--mirostat-ent` option sets the Mirostat target entropy (tau), which represents the desired perplexity value for the generated text. Adjusting the target entropy allows you to control the balance between coherence and diversity in the generated text. A lower value will result in more focused and coherent text, while a higher value will lead to more diverse and potentially less coherent text. The default value is `5.0`.
|
228 |
+
|
229 |
+
Example usage: `--mirostat 2 --mirostat-lr 0.05 --mirostat-ent 3.0`
|
230 |
+
|
231 |
+
### Logit Bias
|
232 |
+
|
233 |
+
- `-l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS`: Modify the likelihood of a token appearing in the generated text completion.
|
234 |
+
|
235 |
+
The logit bias option allows you to manually adjust the likelihood of specific tokens appearing in the generated text. By providing a token ID and a positive or negative bias value, you can increase or decrease the probability of that token being generated.
|
236 |
+
|
237 |
+
For example, use `--logit-bias 15043+1` to increase the likelihood of the token 'Hello', or `--logit-bias 15043-1` to decrease its likelihood. Using a value of negative infinity, `--logit-bias 15043-inf` ensures that the token `Hello` is never produced.
|
238 |
+
|
239 |
+
A more practical use case might be to prevent the generation of `\code{begin}` and `\code{end}` by setting the `\` token (29905) to negative infinity with `-l 29905-inf`. (This is due to the prevalence of LaTeX codes that show up in LLaMA model inference.)
|
240 |
+
|
241 |
+
Example usage: `--logit-bias 29905-inf`
|
242 |
+
|
243 |
+
### RNG Seed
|
244 |
+
|
245 |
+
- `-s SEED, --seed SEED`: Set the random number generator (RNG) seed (default: -1, < 0 = random seed).
|
246 |
+
|
247 |
+
The RNG seed is used to initialize the random number generator that influences the text generation process. By setting a specific seed value, you can obtain consistent and reproducible results across multiple runs with the same input and settings. This can be helpful for testing, debugging, or comparing the effects of different options on the generated text to see when they diverge. If the seed is set to a value less than 0, a random seed will be used, which will result in different outputs on each run.
|
248 |
+
|
249 |
+
## Performance Tuning and Memory Options
|
250 |
+
|
251 |
+
These options help improve the performance and memory usage of the LLaMA models. By adjusting these settings, you can fine-tune the model's behavior to better suit your system's capabilities and achieve optimal performance for your specific use case.
|
252 |
+
|
253 |
+
### Number of Threads
|
254 |
+
|
255 |
+
- `-t N, --threads N`: Set the number of threads to use during computation. For optimal performance, it is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Using the correct number of threads can greatly improve performance.
|
256 |
+
|
257 |
+
### Mlock
|
258 |
+
|
259 |
+
- `--mlock`: Lock the model in memory, preventing it from being swapped out when memory-mapped. This can improve performance but trades away some of the advantages of memory-mapping by requiring more RAM to run and potentially slowing down load times as the model loads into RAM.
|
260 |
+
|
261 |
+
### No Memory Mapping
|
262 |
+
|
263 |
+
- `--no-mmap`: Do not memory-map the model. By default, models are mapped into memory, which allows the system to load only the necessary parts of the model as needed. However, if the model is larger than your total amount of RAM or if your system is low on available memory, using mmap might increase the risk of pageouts, negatively impacting performance. Disabling mmap results in slower load times but may reduce pageouts if you're not using `--mlock`. Note that if the model is larger than the total amount of RAM, turning off mmap would prevent the model from loading at all.
|
264 |
+
|
265 |
+
### Memory Float 32
|
266 |
+
|
267 |
+
- `--memory-f32`: Use 32-bit floats instead of 16-bit floats for memory key+value. This doubles the context memory requirement and cached prompt file size but does not appear to increase generation quality in a measurable way. Not recommended.
|
268 |
+
|
269 |
+
### Batch Size
|
270 |
+
|
271 |
+
- `-b N, --batch-size N`: Set the batch size for prompt processing (default: 512). This large batch size benefits users who have BLAS installed and enabled it during the build. If you don't have BLAS enabled ("BLAS=0"), you can use a smaller number, such as 8, to see the prompt progress as it's evaluated in some situations.
|
272 |
+
|
273 |
+
### Prompt Caching
|
274 |
+
|
275 |
+
- `--prompt-cache FNAME`: Specify a file to cache the model state after the initial prompt. This can significantly speed up the startup time when you're using longer prompts. The file is created during the first run and is reused and updated in subsequent runs. **Note**: Restoring a cached prompt does not imply restoring the exact state of the session at the point it was saved. So even when specifying a specific seed, you are not guaranteed to get the same sequence of tokens as the original generation.
|
276 |
+
|
277 |
+
### Quantization
|
278 |
+
|
279 |
+
For information about 4-bit quantization, which can significantly improve performance and reduce memory usage, please refer to llama.cpp's primary [README](../../README.md#prepare-data--run).
|
280 |
+
|
281 |
+
## Additional Options
|
282 |
+
|
283 |
+
These options provide extra functionality and customization when running the LLaMA models:
|
284 |
+
|
285 |
+
- `-h, --help`: Display a help message showing all available options and their default values. This is particularly useful for checking the latest options and default values, as they can change frequently, and the information in this document may become outdated.
|
286 |
+
- `--verbose-prompt`: Print the prompt before generating text.
|
287 |
+
- `--mtest`: Test the model's functionality by running a series of tests to ensure it's working properly.
|
288 |
+
- `-ngl N, --n-gpu-layers N`: When compiled with appropriate support (currently CLBlast or cuBLAS), this option allows offloading some layers to the GPU for computation. Generally results in increased performance.
|
289 |
+
- `-mg i, --main-gpu i`: When using multiple GPUs this option controls which GPU is used for small tensors for which the overhead of splitting the computation across all GPUs is not worthwhile. The GPU in question will use slightly more VRAM to store a scratch buffer for temporary results. By default GPU 0 is used. Requires cuBLAS.
|
290 |
+
- `-ts SPLIT, --tensor-split SPLIT`: When using multiple GPUs this option controls how large tensors should be split across all GPUs. `SPLIT` is a comma-separated list of non-negative values that assigns the proportion of data that each GPU should get in order. For example, "3,2" will assign 60% of the data to GPU 0 and 40% to GPU 1. By default the data is split in proportion to VRAM but this may not be optimal for performance. Requires cuBLAS.
|
291 |
+
- `--lora FNAME`: Apply a LoRA (Low-Rank Adaptation) adapter to the model (implies --no-mmap). This allows you to adapt the pretrained model to specific tasks or domains.
|
292 |
+
- `--lora-base FNAME`: Optional model to use as a base for the layers modified by the LoRA adapter. This flag is used in conjunction with the `--lora` flag, and specifies the base model for the adaptation.
|
examples/main/main.cpp
ADDED
@@ -0,0 +1,665 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Defines sigaction on msys:
|
2 |
+
#ifndef _GNU_SOURCE
|
3 |
+
#define _GNU_SOURCE
|
4 |
+
#endif
|
5 |
+
|
6 |
+
#include "common.h"
|
7 |
+
#include "llama.h"
|
8 |
+
#include "build-info.h"
|
9 |
+
|
10 |
+
#include <cassert>
|
11 |
+
#include <cinttypes>
|
12 |
+
#include <cmath>
|
13 |
+
#include <cstdio>
|
14 |
+
#include <cstring>
|
15 |
+
#include <ctime>
|
16 |
+
#include <fstream>
|
17 |
+
#include <iostream>
|
18 |
+
#include <string>
|
19 |
+
#include <vector>
|
20 |
+
|
21 |
+
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
|
22 |
+
#include <signal.h>
|
23 |
+
#include <unistd.h>
|
24 |
+
#elif defined (_WIN32)
|
25 |
+
#define WIN32_LEAN_AND_MEAN
|
26 |
+
#define NOMINMAX
|
27 |
+
#include <windows.h>
|
28 |
+
#include <signal.h>
|
29 |
+
#endif
|
30 |
+
|
31 |
+
static console_state con_st;
|
32 |
+
static llama_context ** g_ctx;
|
33 |
+
|
34 |
+
static bool is_interacting = false;
|
35 |
+
|
36 |
+
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
|
37 |
+
void sigint_handler(int signo) {
|
38 |
+
if (signo == SIGINT) {
|
39 |
+
if (!is_interacting) {
|
40 |
+
is_interacting=true;
|
41 |
+
} else {
|
42 |
+
console_cleanup(con_st);
|
43 |
+
printf("\n");
|
44 |
+
llama_print_timings(*g_ctx);
|
45 |
+
_exit(130);
|
46 |
+
}
|
47 |
+
}
|
48 |
+
}
|
49 |
+
#endif
|
50 |
+
|
51 |
+
int main(int argc, char ** argv) {
|
52 |
+
gpt_params params;
|
53 |
+
|
54 |
+
if (gpt_params_parse(argc, argv, params) == false) {
|
55 |
+
return 1;
|
56 |
+
}
|
57 |
+
|
58 |
+
// save choice to use color for later
|
59 |
+
// (note for later: this is a slightly awkward choice)
|
60 |
+
con_st.use_color = params.use_color;
|
61 |
+
con_st.multiline_input = params.multiline_input;
|
62 |
+
console_init(con_st);
|
63 |
+
atexit([]() { console_cleanup(con_st); });
|
64 |
+
|
65 |
+
if (params.perplexity) {
|
66 |
+
printf("\n************\n");
|
67 |
+
printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
|
68 |
+
printf("************\n\n");
|
69 |
+
|
70 |
+
return 0;
|
71 |
+
}
|
72 |
+
|
73 |
+
if (params.embedding) {
|
74 |
+
printf("\n************\n");
|
75 |
+
printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
|
76 |
+
printf("************\n\n");
|
77 |
+
|
78 |
+
return 0;
|
79 |
+
}
|
80 |
+
|
81 |
+
if (params.n_ctx > 2048) {
|
82 |
+
fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
|
83 |
+
"expect poor results\n", __func__, params.n_ctx);
|
84 |
+
} else if (params.n_ctx < 8) {
|
85 |
+
fprintf(stderr, "%s: warning: minimum context size is 8, using minimum size.\n", __func__);
|
86 |
+
params.n_ctx = 8;
|
87 |
+
}
|
88 |
+
|
89 |
+
fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
|
90 |
+
|
91 |
+
if (params.seed < 0) {
|
92 |
+
params.seed = time(NULL);
|
93 |
+
}
|
94 |
+
|
95 |
+
fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
|
96 |
+
|
97 |
+
std::mt19937 rng(params.seed);
|
98 |
+
if (params.random_prompt) {
|
99 |
+
params.prompt = gpt_random_prompt(rng);
|
100 |
+
}
|
101 |
+
|
102 |
+
llama_init_backend();
|
103 |
+
|
104 |
+
llama_context * ctx;
|
105 |
+
g_ctx = &ctx;
|
106 |
+
|
107 |
+
// load the model and apply lora adapter, if any
|
108 |
+
ctx = llama_init_from_gpt_params(params);
|
109 |
+
if (ctx == NULL) {
|
110 |
+
fprintf(stderr, "%s: error: unable to load model\n", __func__);
|
111 |
+
return 1;
|
112 |
+
}
|
113 |
+
|
114 |
+
// print system information
|
115 |
+
{
|
116 |
+
fprintf(stderr, "\n");
|
117 |
+
fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
|
118 |
+
params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
|
119 |
+
}
|
120 |
+
|
121 |
+
// determine the maximum memory usage needed to do inference for the given n_batch and n_predict parameters
|
122 |
+
// uncomment the "used_mem" line in llama.cpp to see the results
|
123 |
+
if (params.mem_test) {
|
124 |
+
{
|
125 |
+
const std::vector<llama_token> tmp(params.n_batch, llama_token_bos());
|
126 |
+
llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
|
127 |
+
}
|
128 |
+
|
129 |
+
{
|
130 |
+
const std::vector<llama_token> tmp = { 0, };
|
131 |
+
llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
|
132 |
+
}
|
133 |
+
|
134 |
+
llama_print_timings(ctx);
|
135 |
+
llama_free(ctx);
|
136 |
+
|
137 |
+
return 0;
|
138 |
+
}
|
139 |
+
|
140 |
+
// export the cgraph and exit
|
141 |
+
if (params.export_cgraph) {
|
142 |
+
llama_eval_export(ctx, "llama.ggml");
|
143 |
+
llama_free(ctx);
|
144 |
+
|
145 |
+
return 0;
|
146 |
+
}
|
147 |
+
|
148 |
+
std::string path_session = params.path_prompt_cache;
|
149 |
+
std::vector<llama_token> session_tokens;
|
150 |
+
|
151 |
+
if (!path_session.empty()) {
|
152 |
+
fprintf(stderr, "%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
|
153 |
+
|
154 |
+
// fopen to check for existing session
|
155 |
+
FILE * fp = std::fopen(path_session.c_str(), "rb");
|
156 |
+
if (fp != NULL) {
|
157 |
+
std::fclose(fp);
|
158 |
+
|
159 |
+
session_tokens.resize(params.n_ctx);
|
160 |
+
size_t n_token_count_out = 0;
|
161 |
+
if (!llama_load_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
|
162 |
+
fprintf(stderr, "%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
|
163 |
+
return 1;
|
164 |
+
}
|
165 |
+
session_tokens.resize(n_token_count_out);
|
166 |
+
llama_set_rng_seed(ctx, params.seed);
|
167 |
+
|
168 |
+
fprintf(stderr, "%s: loaded a session with prompt size of %d tokens\n", __func__, (int) session_tokens.size());
|
169 |
+
} else {
|
170 |
+
fprintf(stderr, "%s: session file does not exist, will create\n", __func__);
|
171 |
+
}
|
172 |
+
}
|
173 |
+
|
174 |
+
// tokenize the prompt
|
175 |
+
std::vector<llama_token> embd_inp;
|
176 |
+
|
177 |
+
if (params.interactive_first || params.instruct || !params.prompt.empty() || session_tokens.empty()) {
|
178 |
+
// Add a space in front of the first character to match OG llama tokenizer behavior
|
179 |
+
params.prompt.insert(0, 1, ' ');
|
180 |
+
|
181 |
+
embd_inp = ::llama_tokenize(ctx, params.prompt, true);
|
182 |
+
} else {
|
183 |
+
embd_inp = session_tokens;
|
184 |
+
}
|
185 |
+
|
186 |
+
const int n_ctx = llama_n_ctx(ctx);
|
187 |
+
|
188 |
+
if ((int) embd_inp.size() > n_ctx - 4) {
|
189 |
+
fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
|
190 |
+
return 1;
|
191 |
+
}
|
192 |
+
|
193 |
+
// debug message about similarity of saved session, if applicable
|
194 |
+
size_t n_matching_session_tokens = 0;
|
195 |
+
if (session_tokens.size()) {
|
196 |
+
for (llama_token id : session_tokens) {
|
197 |
+
if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
|
198 |
+
break;
|
199 |
+
}
|
200 |
+
n_matching_session_tokens++;
|
201 |
+
}
|
202 |
+
if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
|
203 |
+
fprintf(stderr, "%s: using full prompt from session file\n", __func__);
|
204 |
+
} else if (n_matching_session_tokens >= embd_inp.size()) {
|
205 |
+
fprintf(stderr, "%s: session file has exact match for prompt!\n", __func__);
|
206 |
+
} else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
|
207 |
+
fprintf(stderr, "%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
|
208 |
+
__func__, n_matching_session_tokens, embd_inp.size());
|
209 |
+
} else {
|
210 |
+
fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
|
211 |
+
__func__, n_matching_session_tokens, embd_inp.size());
|
212 |
+
}
|
213 |
+
}
|
214 |
+
|
215 |
+
// if we will use the cache for the full prompt without reaching the end of the cache, force
|
216 |
+
// reevaluation of the last token token to recalculate the cached logits
|
217 |
+
if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() &&
|
218 |
+
session_tokens.size() > embd_inp.size()) {
|
219 |
+
session_tokens.resize(embd_inp.size() - 1);
|
220 |
+
}
|
221 |
+
|
222 |
+
// number of tokens to keep when resetting context
|
223 |
+
if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct) {
|
224 |
+
params.n_keep = (int)embd_inp.size();
|
225 |
+
}
|
226 |
+
|
227 |
+
// prefix & suffix for instruct mode
|
228 |
+
const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
|
229 |
+
const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
|
230 |
+
|
231 |
+
// in instruct mode, we inject a prefix and a suffix to each input by the user
|
232 |
+
if (params.instruct) {
|
233 |
+
params.interactive_first = true;
|
234 |
+
params.antiprompt.push_back("### Instruction:\n\n");
|
235 |
+
}
|
236 |
+
|
237 |
+
// enable interactive mode if interactive start is specified
|
238 |
+
if (params.interactive_first) {
|
239 |
+
params.interactive = true;
|
240 |
+
}
|
241 |
+
|
242 |
+
// determine newline token
|
243 |
+
auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
|
244 |
+
|
245 |
+
if (params.verbose_prompt) {
|
246 |
+
fprintf(stderr, "\n");
|
247 |
+
fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
|
248 |
+
fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
|
249 |
+
for (int i = 0; i < (int) embd_inp.size(); i++) {
|
250 |
+
fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
|
251 |
+
}
|
252 |
+
if (params.n_keep > 0) {
|
253 |
+
fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
|
254 |
+
for (int i = 0; i < params.n_keep; i++) {
|
255 |
+
fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
|
256 |
+
}
|
257 |
+
fprintf(stderr, "'\n");
|
258 |
+
}
|
259 |
+
fprintf(stderr, "\n");
|
260 |
+
}
|
261 |
+
|
262 |
+
if (params.interactive) {
|
263 |
+
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
|
264 |
+
struct sigaction sigint_action;
|
265 |
+
sigint_action.sa_handler = sigint_handler;
|
266 |
+
sigemptyset (&sigint_action.sa_mask);
|
267 |
+
sigint_action.sa_flags = 0;
|
268 |
+
sigaction(SIGINT, &sigint_action, NULL);
|
269 |
+
#elif defined (_WIN32)
|
270 |
+
auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
|
271 |
+
return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
|
272 |
+
};
|
273 |
+
SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
|
274 |
+
#endif
|
275 |
+
|
276 |
+
fprintf(stderr, "%s: interactive mode on.\n", __func__);
|
277 |
+
|
278 |
+
if (params.antiprompt.size()) {
|
279 |
+
for (auto antiprompt : params.antiprompt) {
|
280 |
+
fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
|
281 |
+
}
|
282 |
+
}
|
283 |
+
|
284 |
+
if (!params.input_prefix.empty()) {
|
285 |
+
fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
|
286 |
+
}
|
287 |
+
|
288 |
+
if (!params.input_suffix.empty()) {
|
289 |
+
fprintf(stderr, "Input suffix: '%s'\n", params.input_suffix.c_str());
|
290 |
+
}
|
291 |
+
}
|
292 |
+
fprintf(stderr, "sampling: repeat_last_n = %d, repeat_penalty = %f, presence_penalty = %f, frequency_penalty = %f, top_k = %d, tfs_z = %f, top_p = %f, typical_p = %f, temp = %f, mirostat = %d, mirostat_lr = %f, mirostat_ent = %f\n",
|
293 |
+
params.repeat_last_n, params.repeat_penalty, params.presence_penalty, params.frequency_penalty, params.top_k, params.tfs_z, params.top_p, params.typical_p, params.temp, params.mirostat, params.mirostat_eta, params.mirostat_tau);
|
294 |
+
fprintf(stderr, "generate: n_ctx = %d, n_batch = %d, n_predict = %d, n_keep = %d\n", n_ctx, params.n_batch, params.n_predict, params.n_keep);
|
295 |
+
fprintf(stderr, "\n\n");
|
296 |
+
|
297 |
+
// TODO: replace with ring-buffer
|
298 |
+
std::vector<llama_token> last_n_tokens(n_ctx);
|
299 |
+
std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
|
300 |
+
|
301 |
+
if (params.interactive) {
|
302 |
+
const char *control_message;
|
303 |
+
if (con_st.multiline_input) {
|
304 |
+
control_message = " - To return control to LLaMa, end your input with '\\'.\n"
|
305 |
+
" - To return control without starting a new line, end your input with '/'.\n";
|
306 |
+
} else {
|
307 |
+
control_message = " - Press Return to return control to LLaMa.\n"
|
308 |
+
" - To return control without starting a new line, end your input with '/'.\n"
|
309 |
+
" - If you want to submit another line, end your input with '\\'.\n";
|
310 |
+
}
|
311 |
+
fprintf(stderr, "== Running in interactive mode. ==\n"
|
312 |
+
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
|
313 |
+
" - Press Ctrl+C to interject at any time.\n"
|
314 |
+
#endif
|
315 |
+
"%s\n", control_message);
|
316 |
+
|
317 |
+
is_interacting = params.interactive_first;
|
318 |
+
}
|
319 |
+
|
320 |
+
bool is_antiprompt = false;
|
321 |
+
bool input_echo = true;
|
322 |
+
bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
|
323 |
+
|
324 |
+
int n_past = 0;
|
325 |
+
int n_remain = params.n_predict;
|
326 |
+
int n_consumed = 0;
|
327 |
+
int n_session_consumed = 0;
|
328 |
+
|
329 |
+
// the first thing we will do is to output the prompt, so set color accordingly
|
330 |
+
console_set_color(con_st, CONSOLE_COLOR_PROMPT);
|
331 |
+
|
332 |
+
std::vector<llama_token> embd;
|
333 |
+
|
334 |
+
// do one empty run to warm up the model
|
335 |
+
{
|
336 |
+
const std::vector<llama_token> tmp = { llama_token_bos(), };
|
337 |
+
llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
|
338 |
+
llama_reset_timings(ctx);
|
339 |
+
}
|
340 |
+
|
341 |
+
while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
|
342 |
+
// predict
|
343 |
+
if (embd.size() > 0) {
|
344 |
+
// Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
|
345 |
+
// --prompt or --file which uses the same value.
|
346 |
+
auto max_embd_size = n_ctx - 4;
|
347 |
+
// Ensure the input doesn't exceed the context size by truncating embd if necessary.
|
348 |
+
if ((int)embd.size() > max_embd_size) {
|
349 |
+
auto skipped_tokens = embd.size() - max_embd_size;
|
350 |
+
console_set_color(con_st, CONSOLE_COLOR_ERROR);
|
351 |
+
printf("<<input too long: skipped %ld token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
|
352 |
+
console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
|
353 |
+
fflush(stdout);
|
354 |
+
embd.resize(max_embd_size);
|
355 |
+
}
|
356 |
+
|
357 |
+
// infinite text generation via context swapping
|
358 |
+
// if we run out of context:
|
359 |
+
// - take the n_keep first tokens from the original prompt (via n_past)
|
360 |
+
// - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
|
361 |
+
if (n_past + (int) embd.size() > n_ctx) {
|
362 |
+
const int n_left = n_past - params.n_keep;
|
363 |
+
|
364 |
+
// always keep the first token - BOS
|
365 |
+
n_past = std::max(1, params.n_keep);
|
366 |
+
|
367 |
+
// insert n_left/2 tokens at the start of embd from last_n_tokens
|
368 |
+
embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
|
369 |
+
|
370 |
+
// stop saving session if we run out of context
|
371 |
+
path_session.clear();
|
372 |
+
|
373 |
+
//printf("\n---\n");
|
374 |
+
//printf("resetting: '");
|
375 |
+
//for (int i = 0; i < (int) embd.size(); i++) {
|
376 |
+
// printf("%s", llama_token_to_str(ctx, embd[i]));
|
377 |
+
//}
|
378 |
+
//printf("'\n");
|
379 |
+
//printf("\n---\n");
|
380 |
+
}
|
381 |
+
|
382 |
+
// try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
|
383 |
+
if (n_session_consumed < (int) session_tokens.size()) {
|
384 |
+
size_t i = 0;
|
385 |
+
for ( ; i < embd.size(); i++) {
|
386 |
+
if (embd[i] != session_tokens[n_session_consumed]) {
|
387 |
+
session_tokens.resize(n_session_consumed);
|
388 |
+
break;
|
389 |
+
}
|
390 |
+
|
391 |
+
n_past++;
|
392 |
+
n_session_consumed++;
|
393 |
+
|
394 |
+
if (n_session_consumed >= (int) session_tokens.size()) {
|
395 |
+
++i;
|
396 |
+
break;
|
397 |
+
}
|
398 |
+
}
|
399 |
+
if (i > 0) {
|
400 |
+
embd.erase(embd.begin(), embd.begin() + i);
|
401 |
+
}
|
402 |
+
}
|
403 |
+
|
404 |
+
// evaluate tokens in batches
|
405 |
+
// embd is typically prepared beforehand to fit within a batch, but not always
|
406 |
+
for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
|
407 |
+
int n_eval = (int) embd.size() - i;
|
408 |
+
if (n_eval > params.n_batch) {
|
409 |
+
n_eval = params.n_batch;
|
410 |
+
}
|
411 |
+
if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
|
412 |
+
fprintf(stderr, "%s : failed to eval\n", __func__);
|
413 |
+
return 1;
|
414 |
+
}
|
415 |
+
n_past += n_eval;
|
416 |
+
}
|
417 |
+
|
418 |
+
if (embd.size() > 0 && !path_session.empty()) {
|
419 |
+
session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
|
420 |
+
n_session_consumed = session_tokens.size();
|
421 |
+
}
|
422 |
+
}
|
423 |
+
|
424 |
+
embd.clear();
|
425 |
+
|
426 |
+
if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
|
427 |
+
// out of user input, sample next token
|
428 |
+
const float temp = params.temp;
|
429 |
+
const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
|
430 |
+
const float top_p = params.top_p;
|
431 |
+
const float tfs_z = params.tfs_z;
|
432 |
+
const float typical_p = params.typical_p;
|
433 |
+
const int32_t repeat_last_n = params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
|
434 |
+
const float repeat_penalty = params.repeat_penalty;
|
435 |
+
const float alpha_presence = params.presence_penalty;
|
436 |
+
const float alpha_frequency = params.frequency_penalty;
|
437 |
+
const int mirostat = params.mirostat;
|
438 |
+
const float mirostat_tau = params.mirostat_tau;
|
439 |
+
const float mirostat_eta = params.mirostat_eta;
|
440 |
+
const bool penalize_nl = params.penalize_nl;
|
441 |
+
|
442 |
+
// optionally save the session on first sample (for faster prompt loading next time)
|
443 |
+
if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
|
444 |
+
need_to_save_session = false;
|
445 |
+
llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
|
446 |
+
}
|
447 |
+
|
448 |
+
llama_token id = 0;
|
449 |
+
|
450 |
+
{
|
451 |
+
auto logits = llama_get_logits(ctx);
|
452 |
+
auto n_vocab = llama_n_vocab(ctx);
|
453 |
+
|
454 |
+
// Apply params.logit_bias map
|
455 |
+
for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
|
456 |
+
logits[it->first] += it->second;
|
457 |
+
}
|
458 |
+
|
459 |
+
std::vector<llama_token_data> candidates;
|
460 |
+
candidates.reserve(n_vocab);
|
461 |
+
for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
|
462 |
+
candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
|
463 |
+
}
|
464 |
+
|
465 |
+
llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
|
466 |
+
|
467 |
+
// Apply penalties
|
468 |
+
float nl_logit = logits[llama_token_nl()];
|
469 |
+
auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), n_ctx);
|
470 |
+
llama_sample_repetition_penalty(ctx, &candidates_p,
|
471 |
+
last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
|
472 |
+
last_n_repeat, repeat_penalty);
|
473 |
+
llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
|
474 |
+
last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
|
475 |
+
last_n_repeat, alpha_frequency, alpha_presence);
|
476 |
+
if (!penalize_nl) {
|
477 |
+
logits[llama_token_nl()] = nl_logit;
|
478 |
+
}
|
479 |
+
|
480 |
+
if (temp <= 0) {
|
481 |
+
// Greedy sampling
|
482 |
+
id = llama_sample_token_greedy(ctx, &candidates_p);
|
483 |
+
} else {
|
484 |
+
if (mirostat == 1) {
|
485 |
+
static float mirostat_mu = 2.0f * mirostat_tau;
|
486 |
+
const int mirostat_m = 100;
|
487 |
+
llama_sample_temperature(ctx, &candidates_p, temp);
|
488 |
+
id = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
|
489 |
+
} else if (mirostat == 2) {
|
490 |
+
static float mirostat_mu = 2.0f * mirostat_tau;
|
491 |
+
llama_sample_temperature(ctx, &candidates_p, temp);
|
492 |
+
id = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
|
493 |
+
} else {
|
494 |
+
// Temperature sampling
|
495 |
+
llama_sample_top_k(ctx, &candidates_p, top_k, 1);
|
496 |
+
llama_sample_tail_free(ctx, &candidates_p, tfs_z, 1);
|
497 |
+
llama_sample_typical(ctx, &candidates_p, typical_p, 1);
|
498 |
+
llama_sample_top_p(ctx, &candidates_p, top_p, 1);
|
499 |
+
llama_sample_temperature(ctx, &candidates_p, temp);
|
500 |
+
id = llama_sample_token(ctx, &candidates_p);
|
501 |
+
}
|
502 |
+
}
|
503 |
+
// printf("`%d`", candidates_p.size);
|
504 |
+
|
505 |
+
last_n_tokens.erase(last_n_tokens.begin());
|
506 |
+
last_n_tokens.push_back(id);
|
507 |
+
}
|
508 |
+
|
509 |
+
// replace end of text token with newline token when in interactive mode
|
510 |
+
if (id == llama_token_eos() && params.interactive && !params.instruct) {
|
511 |
+
id = llama_token_newline.front();
|
512 |
+
if (params.antiprompt.size() != 0) {
|
513 |
+
// tokenize and inject first reverse prompt
|
514 |
+
const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
|
515 |
+
embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
|
516 |
+
}
|
517 |
+
}
|
518 |
+
|
519 |
+
// add it to the context
|
520 |
+
embd.push_back(id);
|
521 |
+
|
522 |
+
// echo this to console
|
523 |
+
input_echo = true;
|
524 |
+
|
525 |
+
// decrement remaining sampling budget
|
526 |
+
--n_remain;
|
527 |
+
} else {
|
528 |
+
// some user input remains from prompt or interaction, forward it to processing
|
529 |
+
while ((int) embd_inp.size() > n_consumed) {
|
530 |
+
embd.push_back(embd_inp[n_consumed]);
|
531 |
+
last_n_tokens.erase(last_n_tokens.begin());
|
532 |
+
last_n_tokens.push_back(embd_inp[n_consumed]);
|
533 |
+
++n_consumed;
|
534 |
+
if ((int) embd.size() >= params.n_batch) {
|
535 |
+
break;
|
536 |
+
}
|
537 |
+
}
|
538 |
+
}
|
539 |
+
|
540 |
+
// display text
|
541 |
+
if (input_echo) {
|
542 |
+
for (auto id : embd) {
|
543 |
+
printf("%s", llama_token_to_str(ctx, id));
|
544 |
+
}
|
545 |
+
fflush(stdout);
|
546 |
+
}
|
547 |
+
// reset color to default if we there is no pending user input
|
548 |
+
if (input_echo && (int)embd_inp.size() == n_consumed) {
|
549 |
+
console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
|
550 |
+
}
|
551 |
+
|
552 |
+
// if not currently processing queued inputs;
|
553 |
+
if ((int) embd_inp.size() <= n_consumed) {
|
554 |
+
|
555 |
+
// check for reverse prompt
|
556 |
+
if (params.antiprompt.size()) {
|
557 |
+
std::string last_output;
|
558 |
+
for (auto id : last_n_tokens) {
|
559 |
+
last_output += llama_token_to_str(ctx, id);
|
560 |
+
}
|
561 |
+
|
562 |
+
is_antiprompt = false;
|
563 |
+
// Check if each of the reverse prompts appears at the end of the output.
|
564 |
+
// If we're not running interactively, the reverse prompt might be tokenized with some following characters
|
565 |
+
// so we'll compensate for that by widening the search window a bit.
|
566 |
+
for (std::string & antiprompt : params.antiprompt) {
|
567 |
+
size_t extra_padding = params.interactive ? 0 : 2;
|
568 |
+
size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
|
569 |
+
? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
|
570 |
+
: 0;
|
571 |
+
|
572 |
+
if (last_output.find(antiprompt.c_str(), search_start_pos) != std::string::npos) {
|
573 |
+
if (params.interactive) {
|
574 |
+
is_interacting = true;
|
575 |
+
console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
|
576 |
+
}
|
577 |
+
is_antiprompt = true;
|
578 |
+
fflush(stdout);
|
579 |
+
break;
|
580 |
+
}
|
581 |
+
}
|
582 |
+
}
|
583 |
+
|
584 |
+
if (n_past > 0 && is_interacting) {
|
585 |
+
if (params.instruct) {
|
586 |
+
printf("\n> ");
|
587 |
+
}
|
588 |
+
|
589 |
+
std::string buffer;
|
590 |
+
if (!params.input_prefix.empty()) {
|
591 |
+
buffer += params.input_prefix;
|
592 |
+
printf("%s", buffer.c_str());
|
593 |
+
}
|
594 |
+
|
595 |
+
std::string line;
|
596 |
+
bool another_line = true;
|
597 |
+
do {
|
598 |
+
another_line = console_readline(con_st, line);
|
599 |
+
buffer += line;
|
600 |
+
} while (another_line);
|
601 |
+
|
602 |
+
// done taking input, reset color
|
603 |
+
console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
|
604 |
+
|
605 |
+
// Add tokens to embd only if the input buffer is non-empty
|
606 |
+
// Entering a empty line lets the user pass control back
|
607 |
+
if (buffer.length() > 1) {
|
608 |
+
// append input suffix if any
|
609 |
+
if (!params.input_suffix.empty()) {
|
610 |
+
buffer += params.input_suffix;
|
611 |
+
printf("%s", params.input_suffix.c_str());
|
612 |
+
}
|
613 |
+
|
614 |
+
// instruct mode: insert instruction prefix
|
615 |
+
if (params.instruct && !is_antiprompt) {
|
616 |
+
n_consumed = embd_inp.size();
|
617 |
+
embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
|
618 |
+
}
|
619 |
+
|
620 |
+
auto line_inp = ::llama_tokenize(ctx, buffer, false);
|
621 |
+
embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
|
622 |
+
|
623 |
+
// instruct mode: insert response suffix
|
624 |
+
if (params.instruct) {
|
625 |
+
embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
|
626 |
+
}
|
627 |
+
|
628 |
+
n_remain -= line_inp.size();
|
629 |
+
}
|
630 |
+
|
631 |
+
input_echo = false; // do not echo this again
|
632 |
+
}
|
633 |
+
|
634 |
+
if (n_past > 0) {
|
635 |
+
is_interacting = false;
|
636 |
+
}
|
637 |
+
}
|
638 |
+
|
639 |
+
// end of text token
|
640 |
+
if (!embd.empty() && embd.back() == llama_token_eos()) {
|
641 |
+
if (params.instruct) {
|
642 |
+
is_interacting = true;
|
643 |
+
} else {
|
644 |
+
fprintf(stderr, " [end of text]\n");
|
645 |
+
break;
|
646 |
+
}
|
647 |
+
}
|
648 |
+
|
649 |
+
// In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
|
650 |
+
if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
|
651 |
+
n_remain = params.n_predict;
|
652 |
+
is_interacting = true;
|
653 |
+
}
|
654 |
+
}
|
655 |
+
|
656 |
+
if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
|
657 |
+
fprintf(stderr, "\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
|
658 |
+
llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
|
659 |
+
}
|
660 |
+
|
661 |
+
llama_print_timings(ctx);
|
662 |
+
llama_free(ctx);
|
663 |
+
|
664 |
+
return 0;
|
665 |
+
}
|
examples/metal/CMakeLists.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
set(TEST_TARGET metal)
|
2 |
+
add_executable(${TEST_TARGET} metal.cpp)
|
3 |
+
target_link_libraries(${TEST_TARGET} PRIVATE ggml)
|
examples/metal/metal.cpp
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Evaluate a statically exported ggml computation graph with Metal
|
2 |
+
//
|
3 |
+
// - First, export a LLaMA graph:
|
4 |
+
//
|
5 |
+
// $ ./bin/main -m ../models/7B/ggml-model-q4_0.bin --export
|
6 |
+
//
|
7 |
+
// - Run this tool to evaluate the exported graph:
|
8 |
+
//
|
9 |
+
// $ ./bin/metal llama.ggml
|
10 |
+
//
|
11 |
+
// The purpose of this tool is mostly for debugging and demonstration purposes.
|
12 |
+
// The main limitation of exporting computation graphs is that their sizes are static which often
|
13 |
+
// can be a problem for real-world applications.
|
14 |
+
//
|
15 |
+
|
16 |
+
#include "ggml.h"
|
17 |
+
#include "ggml-metal.h"
|
18 |
+
|
19 |
+
#include <cstdio>
|
20 |
+
#include <cstring>
|
21 |
+
#include <cstdlib>
|
22 |
+
|
23 |
+
int main(int argc, char ** argv) {
|
24 |
+
ggml_time_init();
|
25 |
+
|
26 |
+
if (argc != 2) {
|
27 |
+
fprintf(stderr, "Usage: %s llama.ggml\n", argv[0]);
|
28 |
+
return -1;
|
29 |
+
}
|
30 |
+
|
31 |
+
const char * fname_cgraph = argv[1];
|
32 |
+
|
33 |
+
// load the compute graph
|
34 |
+
struct ggml_context * ctx_data = NULL;
|
35 |
+
struct ggml_context * ctx_eval = NULL;
|
36 |
+
|
37 |
+
struct ggml_cgraph gf = ggml_graph_import(fname_cgraph, &ctx_data, &ctx_eval);
|
38 |
+
gf.n_threads = 1;
|
39 |
+
|
40 |
+
// this allocates all Metal resources and memory buffers
|
41 |
+
auto * ctx_metal = ggml_metal_init();
|
42 |
+
|
43 |
+
ggml_metal_add_buffer(ctx_metal, "data", ggml_get_mem_buffer(ctx_data), ggml_get_mem_size(ctx_data));
|
44 |
+
ggml_metal_add_buffer(ctx_metal, "eval", ggml_get_mem_buffer(ctx_eval), ggml_get_mem_size(ctx_eval));
|
45 |
+
|
46 |
+
// main
|
47 |
+
{
|
48 |
+
struct ggml_tensor * input = ggml_graph_get_tensor(&gf, "embd");
|
49 |
+
*(int32_t *) input->data = 1; // BOS
|
50 |
+
|
51 |
+
ggml_metal_set_tensor(ctx_metal, input);
|
52 |
+
|
53 |
+
// warmup
|
54 |
+
ggml_metal_graph_compute(ctx_metal, &gf);
|
55 |
+
|
56 |
+
const int n_iter = 16;
|
57 |
+
|
58 |
+
const int64_t t0 = ggml_time_us();
|
59 |
+
|
60 |
+
// the actual inference happens here
|
61 |
+
for (int i = 0; i < n_iter; ++i) {
|
62 |
+
ggml_metal_graph_compute(ctx_metal, &gf);
|
63 |
+
}
|
64 |
+
|
65 |
+
const int64_t t1 = ggml_time_us();
|
66 |
+
|
67 |
+
printf("time: %.2f ms, %.2f ms/tok\n", (t1 - t0) / 1000.0, (t1 - t0) / 1000.0 / n_iter);
|
68 |
+
}
|
69 |
+
|
70 |
+
// debug output
|
71 |
+
{
|
72 |
+
struct ggml_tensor * logits = gf.nodes[gf.n_nodes - 1];
|
73 |
+
ggml_metal_get_tensor(ctx_metal, logits);
|
74 |
+
|
75 |
+
float * ptr = (float *) ggml_get_data(logits);
|
76 |
+
|
77 |
+
printf("logits: ");
|
78 |
+
for (int i = 0; i < 10; i++) {
|
79 |
+
printf("%8.4f ", ptr[i]);
|
80 |
+
}
|
81 |
+
printf("\n");
|
82 |
+
int imax = 0;
|
83 |
+
double sum = 0.0;
|
84 |
+
double vmax = -1e9;
|
85 |
+
for (int i = 0; i < 32000; i++) {
|
86 |
+
sum += (double) ptr[i];
|
87 |
+
if (ptr[i] > vmax) {
|
88 |
+
vmax = ptr[i];
|
89 |
+
imax = i;
|
90 |
+
}
|
91 |
+
}
|
92 |
+
printf("sum: %f, imax = %d, vmax = %f\n", sum, imax, vmax);
|
93 |
+
}
|
94 |
+
|
95 |
+
ggml_metal_free(ctx_metal);
|
96 |
+
|
97 |
+
ggml_free(ctx_data);
|
98 |
+
ggml_free(ctx_eval);
|
99 |
+
|
100 |
+
return 0;
|
101 |
+
}
|
102 |
+
|
examples/perplexity/CMakeLists.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set(TARGET perplexity)
|
2 |
+
add_executable(${TARGET} perplexity.cpp)
|
3 |
+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
|
4 |
+
target_compile_features(${TARGET} PRIVATE cxx_std_11)
|
5 |
+
if(TARGET BUILD_INFO)
|
6 |
+
add_dependencies(${TARGET} BUILD_INFO)
|
7 |
+
endif()
|
examples/perplexity/README.md
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
# perplexity
|
2 |
+
|
3 |
+
TODO
|
examples/perplexity/perplexity.cpp
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "common.h"
|
2 |
+
#include "llama.h"
|
3 |
+
#include "build-info.h"
|
4 |
+
|
5 |
+
#include <cmath>
|
6 |
+
#include <ctime>
|
7 |
+
|
8 |
+
std::vector<float> softmax(const std::vector<float>& logits) {
|
9 |
+
std::vector<float> probs(logits.size());
|
10 |
+
float max_logit = logits[0];
|
11 |
+
for (float v : logits) max_logit = std::max(max_logit, v);
|
12 |
+
double sum_exp = 0.0;
|
13 |
+
for (size_t i = 0; i < logits.size(); i++) {
|
14 |
+
// Subtract the maximum logit value from the current logit value for numerical stability
|
15 |
+
const float logit = logits[i] - max_logit;
|
16 |
+
const float exp_logit = expf(logit);
|
17 |
+
sum_exp += exp_logit;
|
18 |
+
probs[i] = exp_logit;
|
19 |
+
}
|
20 |
+
for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
|
21 |
+
return probs;
|
22 |
+
}
|
23 |
+
|
24 |
+
void perplexity(llama_context * ctx, const gpt_params & params) {
|
25 |
+
// Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
|
26 |
+
// Run `./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
|
27 |
+
// Output: `perplexity: 13.5106 [114/114]`
|
28 |
+
// BOS tokens will be added for each chunk before eval
|
29 |
+
auto tokens = ::llama_tokenize(ctx, params.prompt, true);
|
30 |
+
|
31 |
+
int count = 0;
|
32 |
+
|
33 |
+
const int n_chunk = tokens.size() / params.n_ctx;
|
34 |
+
const int n_vocab = llama_n_vocab(ctx);
|
35 |
+
const int n_batch = params.n_batch;
|
36 |
+
|
37 |
+
double nll = 0.0;
|
38 |
+
fprintf(stderr, "%s: calculating perplexity over %d chunks, batch_size=%d\n", __func__, n_chunk, n_batch);
|
39 |
+
|
40 |
+
for (int i = 0; i < n_chunk; ++i) {
|
41 |
+
const int start = i * params.n_ctx;
|
42 |
+
const int end = start + params.n_ctx;
|
43 |
+
|
44 |
+
const int num_batches = (params.n_ctx + n_batch - 1) / n_batch;
|
45 |
+
|
46 |
+
std::vector<float> logits;
|
47 |
+
|
48 |
+
const auto t_start = std::chrono::high_resolution_clock::now();
|
49 |
+
|
50 |
+
for (int j = 0; j < num_batches; ++j) {
|
51 |
+
const int batch_start = start + j * n_batch;
|
52 |
+
const int batch_size = std::min(end - batch_start, n_batch);
|
53 |
+
|
54 |
+
// save original token and restore it after eval
|
55 |
+
const auto token_org = tokens[batch_start];
|
56 |
+
|
57 |
+
// add BOS token for the first batch of each chunk
|
58 |
+
if (j == 0) {
|
59 |
+
tokens[batch_start] = llama_token_bos();
|
60 |
+
}
|
61 |
+
|
62 |
+
if (llama_eval(ctx, tokens.data() + batch_start, batch_size, j * n_batch, params.n_threads)) {
|
63 |
+
fprintf(stderr, "%s : failed to eval\n", __func__);
|
64 |
+
return;
|
65 |
+
}
|
66 |
+
|
67 |
+
// restore the original token in case it was set to BOS
|
68 |
+
tokens[batch_start] = token_org;
|
69 |
+
|
70 |
+
const auto batch_logits = llama_get_logits(ctx);
|
71 |
+
logits.insert(logits.end(), batch_logits, batch_logits + batch_size * n_vocab);
|
72 |
+
}
|
73 |
+
|
74 |
+
const auto t_end = std::chrono::high_resolution_clock::now();
|
75 |
+
|
76 |
+
if (i == 0) {
|
77 |
+
const float t_total = std::chrono::duration<float>(t_end - t_start).count();
|
78 |
+
fprintf(stderr, "%s: %.2f seconds per pass - ETA ", __func__, t_total);
|
79 |
+
int total_seconds = (int)(t_total * n_chunk);
|
80 |
+
if (total_seconds >= 60*60) {
|
81 |
+
fprintf(stderr, "%d hours ", total_seconds / (60*60));
|
82 |
+
total_seconds = total_seconds % (60*60);
|
83 |
+
}
|
84 |
+
fprintf(stderr, "%d minutes\n", total_seconds / 60);
|
85 |
+
}
|
86 |
+
|
87 |
+
// We get the logits for all the tokens in the context window (params.n_ctx)
|
88 |
+
// from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
|
89 |
+
// calculate the perplexity over the last half of the window (so the model always has
|
90 |
+
// some context to predict the token).
|
91 |
+
//
|
92 |
+
// We rely on the fact that attention in the forward pass only looks at previous
|
93 |
+
// tokens here, so the logits returned for each token are an accurate representation
|
94 |
+
// of what the model would have predicted at that point.
|
95 |
+
//
|
96 |
+
// Example, we have a context window of 512, we will compute perplexity for each of the
|
97 |
+
// last 256 tokens. Then, we split the input up into context window size chunks to
|
98 |
+
// process the entire prompt.
|
99 |
+
for (int j = std::min(512, params.n_ctx / 2); j < params.n_ctx - 1; ++j) {
|
100 |
+
// Calculate probability of next token, given the previous ones.
|
101 |
+
const std::vector<float> tok_logits(
|
102 |
+
logits.begin() + (j + 0) * n_vocab,
|
103 |
+
logits.begin() + (j + 1) * n_vocab);
|
104 |
+
|
105 |
+
const float prob = softmax(tok_logits)[tokens[start + j + 1]];
|
106 |
+
|
107 |
+
nll += -std::log(prob);
|
108 |
+
++count;
|
109 |
+
}
|
110 |
+
// perplexity is e^(average negative log-likelihood)
|
111 |
+
printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
|
112 |
+
fflush(stdout);
|
113 |
+
}
|
114 |
+
printf("\n");
|
115 |
+
}
|
116 |
+
|
117 |
+
int main(int argc, char ** argv) {
|
118 |
+
gpt_params params;
|
119 |
+
|
120 |
+
params.n_batch = 512;
|
121 |
+
if (gpt_params_parse(argc, argv, params) == false) {
|
122 |
+
return 1;
|
123 |
+
}
|
124 |
+
|
125 |
+
params.perplexity = true;
|
126 |
+
params.n_batch = std::min(params.n_batch, params.n_ctx);
|
127 |
+
|
128 |
+
if (params.n_ctx > 2048) {
|
129 |
+
fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
|
130 |
+
"expect poor results\n", __func__, params.n_ctx);
|
131 |
+
}
|
132 |
+
|
133 |
+
fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
|
134 |
+
|
135 |
+
if (params.seed < 0) {
|
136 |
+
params.seed = time(NULL);
|
137 |
+
}
|
138 |
+
|
139 |
+
fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
|
140 |
+
|
141 |
+
std::mt19937 rng(params.seed);
|
142 |
+
if (params.random_prompt) {
|
143 |
+
params.prompt = gpt_random_prompt(rng);
|
144 |
+
}
|
145 |
+
|
146 |
+
llama_init_backend();
|
147 |
+
|
148 |
+
llama_context * ctx;
|
149 |
+
|
150 |
+
// load the model and apply lora adapter, if any
|
151 |
+
ctx = llama_init_from_gpt_params(params);
|
152 |
+
if (ctx == NULL) {
|
153 |
+
fprintf(stderr, "%s: error: unable to load model\n", __func__);
|
154 |
+
return 1;
|
155 |
+
}
|
156 |
+
|
157 |
+
// print system information
|
158 |
+
{
|
159 |
+
fprintf(stderr, "\n");
|
160 |
+
fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
|
161 |
+
params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
|
162 |
+
}
|
163 |
+
|
164 |
+
perplexity(ctx, params);
|
165 |
+
|
166 |
+
llama_print_timings(ctx);
|
167 |
+
llama_free(ctx);
|
168 |
+
|
169 |
+
return 0;
|
170 |
+
}
|