kristada673 richardr1126 commited on
Commit
f8c5b0d
0 Parent(s):

Duplicate from richardr1126/Text-to-SQL-WizardCoder

Browse files

Co-authored-by: Richard R. <richardr1126@users.noreply.huggingface.co>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .editorconfig +19 -0
  2. .flake8 +2 -0
  3. .gitattributes +38 -0
  4. .github/ISSUE_TEMPLATE/custom.md +185 -0
  5. .github/workflows/editorconfig.yml +17 -0
  6. .github/workflows/tidy-post.yml +20 -0
  7. .github/workflows/tidy-review.yml +23 -0
  8. .gitignore +66 -0
  9. .pre-commit-config.yaml +15 -0
  10. CMakeLists.txt +299 -0
  11. Dockerfile +10 -0
  12. LICENSE.md +661 -0
  13. MIT_LICENSE_GGML_LLAMACPP_ONLY +26 -0
  14. Makefile +343 -0
  15. Package.swift +24 -0
  16. README.md +24 -0
  17. build-info.h +7 -0
  18. clblast.dll +3 -0
  19. convert-lora-to-ggml.py +129 -0
  20. convert-pth-to-ggml.py +13 -0
  21. convert.py +1178 -0
  22. docs/token_generation_performance_tips.md +40 -0
  23. examples/CMakeLists.txt +47 -0
  24. examples/Miku.sh +49 -0
  25. examples/alpaca.sh +19 -0
  26. examples/baby-llama/CMakeLists.txt +4 -0
  27. examples/baby-llama/baby-llama.cpp +1696 -0
  28. examples/benchmark/CMakeLists.txt +7 -0
  29. examples/benchmark/benchmark-matmult.cpp +261 -0
  30. examples/chat-13B.bat +57 -0
  31. examples/chat-13B.sh +41 -0
  32. examples/chat-persistent.sh +151 -0
  33. examples/chat-vicuna.sh +41 -0
  34. examples/chat.sh +16 -0
  35. examples/common.cpp +950 -0
  36. examples/common.h +137 -0
  37. examples/embedding/CMakeLists.txt +7 -0
  38. examples/embedding/README.md +3 -0
  39. examples/embedding/embedding.cpp +95 -0
  40. examples/gpt4all.sh +15 -0
  41. examples/jeopardy/README.md +21 -0
  42. examples/jeopardy/graph.py +57 -0
  43. examples/jeopardy/jeopardy.sh +30 -0
  44. examples/jeopardy/qasheet.csv +103 -0
  45. examples/jeopardy/questions.txt +100 -0
  46. examples/main/CMakeLists.txt +7 -0
  47. examples/main/README.md +293 -0
  48. examples/main/main.cpp +671 -0
  49. examples/metal/CMakeLists.txt +3 -0
  50. examples/metal/metal.cpp +102 -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
.flake8 ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [flake8]
2
+ max-line-length = 125
.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ out/
26
+
27
+ /main
28
+ /quantize
29
+ /quantize-stats
30
+ /result
31
+ /perplexity
32
+ /embedding
33
+ /train-text-from-scratch
34
+ /benchmark-matmult
35
+ /vdot
36
+ /server
37
+ /Pipfile
38
+ /libllama.so
39
+
40
+ arm_neon.h
41
+ compile_commands.json
42
+ CMakeSettings.json
43
+
44
+ __pycache__
45
+
46
+ dist/
47
+ *.spec
48
+
49
+ zig-out/
50
+ zig-cache/
51
+
52
+ ppl-*.txt
53
+ qnt-*.txt
54
+ perf-*.txt
55
+
56
+ examples/jeopardy/results.txt
57
+ koboldcpp.so
58
+ koboldcpp_failsafe.so
59
+ koboldcpp_openblas.so
60
+ koboldcpp_openblas_noavx2.so
61
+ koboldcpp_clblast.so
62
+ koboldcpp.dll
63
+ koboldcpp_failsafe.dll
64
+ koboldcpp_openblas.dll
65
+ koboldcpp_openblas_noavx2.dll
66
+ koboldcpp_clblast.dll
.pre-commit-config.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://pre-commit.com for more information
2
+ # See https://pre-commit.com/hooks.html for more hooks
3
+ exclude: prompts/.*.txt
4
+ repos:
5
+ - repo: https://github.com/pre-commit/pre-commit-hooks
6
+ rev: v3.2.0
7
+ hooks:
8
+ - id: trailing-whitespace
9
+ - id: end-of-file-fixer
10
+ - id: check-yaml
11
+ - id: check-added-large-files
12
+ - repo: https://github.com/PyCQA/flake8
13
+ rev: 6.0.0
14
+ hooks:
15
+ - id: flake8
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/richardr1126/sql-wizard-coder-ggml/resolve/main/sql-wizard-coder-15b-q4_0.bin\
8
+ && apt remove build-essential wget make -y
9
+
10
+ ENTRYPOINT ["python", "koboldcpp.py", "sql-wizard-coder-15b-q4_0.bin", "--port", "7860", "--stream"]
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,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ exclude: ["ggml-metal.metal"],
15
+ sources: ["ggml.c", "llama.cpp"],
16
+ publicHeadersPath: "spm-headers",
17
+ cSettings: [.unsafeFlags(["-Wno-shorten-64-to-32"]), .define("GGML_USE_ACCELERATE")],
18
+ linkerSettings: [
19
+ .linkedFramework("Accelerate")
20
+ ]
21
+ ),
22
+ ],
23
+ cxxLanguageStandard: .cxx11
24
+ )
README.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Text-to-SQL WizardCoder Demo
3
+ sdk: docker
4
+ emoji: 📚
5
+ colorFrom: blue
6
+ colorTo: purple
7
+ duplicated_from: richardr1126/Text-to-SQL-WizardCoder
8
+ pinned: false
9
+ ---
10
+
11
+ ## Citation
12
+
13
+ Please cite the repo if you use the data or code in this repo.
14
+
15
+ ```
16
+ @misc{luo2023wizardcoder,
17
+ title={WizardCoder: Empowering Code Large Language Models with Evol-Instruct},
18
+ author={Ziyang Luo and Can Xu and Pu Zhao and Qingfeng Sun and Xiubo Geng and Wenxiang Hu and Chongyang Tao and Jing Ma and Qingwei Lin and Daxin Jiang},
19
+ year={2023},
20
+ }
21
+ ```
22
+ ## Disclaimer
23
+
24
+ The resources, including code, data, and model weights, associated with this project are restricted for academic research purposes only and cannot be used for commercial purposes. The content produced by any version of WizardCoder is influenced by uncontrollable variables such as randomness, and therefore, the accuracy of the output cannot be guaranteed by this project. This project does not accept any legal liability for the content of the model output, nor does it assume responsibility for any losses incurred due to the use of associated resources and output results.
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,1178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(
516
+ "Error: Input uses the newer GPTQ-for-LLaMa format (using g_idx), "
517
+ "which is not yet natively supported by GGML. "
518
+ "For now you can still convert this model by passing `--outtype f16` to dequantize, "
519
+ "but that will result in a much larger output file for no quality benefit.\n")
520
+ sys.exit(1)
521
+ assert not data_type.have_g_idx and self.data_type.have_addends and data_type.have_addends
522
+
523
+
524
+ LazyModel = Dict[str, LazyTensor]
525
+
526
+
527
+ @dataclass
528
+ class ModelPlus:
529
+ model: LazyModel
530
+ paths: List[Path] # Where this was read from.
531
+ format: Literal['ggml', 'torch', 'safetensors']
532
+ vocab: Optional[Vocab] # For GGML models (which have vocab built in), the vocab.
533
+
534
+
535
+ def merge_sharded(models: List[LazyModel]) -> LazyModel:
536
+ # Original LLaMA models have each file contain one part of each tensor.
537
+ # Use a dict instead of a set to preserve order.
538
+ names = {name: None for model in models for name in model}
539
+
540
+ def convert(name: str) -> LazyTensor:
541
+ lazy_tensors: List[LazyTensor] = [model[name] for model in models]
542
+ if len(lazy_tensors) == 1:
543
+ # only one file; don't go through this procedure since there might
544
+ # be quantized tensors
545
+ return lazy_tensors[0]
546
+ if len(lazy_tensors[0].shape) == 1:
547
+ # the tensor is just duplicated in every file
548
+ return lazy_tensors[0]
549
+ if name.startswith('tok_embeddings.') or \
550
+ name.endswith('.attention.wo.weight') or \
551
+ name.endswith('.feed_forward.w2.weight'):
552
+ # split by columns
553
+ axis = 1
554
+ else:
555
+ # split by rows
556
+ axis = 0
557
+ concatenated_shape = list(lazy_tensors[0].shape)
558
+ concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
559
+
560
+ def load() -> UnquantizedTensor:
561
+ ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
562
+ concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
563
+ return UnquantizedTensor(concatenated)
564
+ description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
565
+ return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
566
+ return {name: convert(name) for name in names}
567
+
568
+
569
+ def merge_multifile_models(models_plus: List[ModelPlus]) -> ModelPlus:
570
+ formats = set(mp.format for mp in models_plus)
571
+ assert len(formats) == 1, "different formats?"
572
+ format = formats.pop()
573
+ paths = [path for mp in models_plus for path in mp.paths]
574
+ # Use the first non-None vocab, if any.
575
+ try:
576
+ vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
577
+ except StopIteration:
578
+ vocab = None
579
+
580
+ if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
581
+ # Transformers models put different tensors in different files, but
582
+ # don't split indivdual tensors between files.
583
+ model: LazyModel = {}
584
+ for mp in models_plus:
585
+ model.update(mp.model)
586
+ else:
587
+ model = merge_sharded([mp.model for mp in models_plus])
588
+
589
+ return ModelPlus(model, paths, format, vocab)
590
+
591
+
592
+ def permute_lazy(lazy_tensor: LazyTensor, n_head: int) -> LazyTensor:
593
+ def load() -> Tensor:
594
+ return lazy_tensor.load().permute(n_head)
595
+ return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}) ' + lazy_tensor.description)
596
+
597
+
598
+ def convert_transformers_to_orig(model: LazyModel) -> LazyModel:
599
+ out: LazyModel = {}
600
+ out["tok_embeddings.weight"] = model["model.embed_tokens.weight"]
601
+ out["norm.weight"] = model["model.norm.weight"]
602
+ out["output.weight"] = model["lm_head.weight"]
603
+
604
+ n_head = model["model.layers.0.self_attn.q_proj.weight"].shape[1] // 128
605
+ for i in itertools.count():
606
+ if f"model.layers.{i}.self_attn.q_proj.weight" not in model:
607
+ break
608
+ out[f"layers.{i}.attention.wq.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.q_proj.weight"], n_head)
609
+ out[f"layers.{i}.attention.wk.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.k_proj.weight"], n_head)
610
+ out[f"layers.{i}.attention.wv.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
611
+ out[f"layers.{i}.attention.wo.weight"] = model[f"model.layers.{i}.self_attn.o_proj.weight"]
612
+
613
+ out[f"layers.{i}.feed_forward.w1.weight"] = model[f"model.layers.{i}.mlp.gate_proj.weight"]
614
+ out[f"layers.{i}.feed_forward.w2.weight"] = model[f"model.layers.{i}.mlp.down_proj.weight"]
615
+ out[f"layers.{i}.feed_forward.w3.weight"] = model[f"model.layers.{i}.mlp.up_proj.weight"]
616
+
617
+ out[f"layers.{i}.attention_norm.weight"] = model[f"model.layers.{i}.input_layernorm.weight"]
618
+ out[f"layers.{i}.ffn_norm.weight"] = model[f"model.layers.{i}.post_attention_layernorm.weight"]
619
+ return out
620
+
621
+
622
+ def handle_quantization(model: LazyModel) -> LazyModel:
623
+ '''Convert a model with entries for 'foo.qweight', 'foo.scales', etc.
624
+ (which resolve to UnquantizedTensors with the raw data) to one with entries
625
+ for 'foo.weight' (which resolve to QuantizedTensors).
626
+ '''
627
+ def convert(name: str) -> Tuple[str, LazyTensor]:
628
+ if name.endswith(".qweight"):
629
+ namebase = name.rsplit('.', 1)[0]
630
+ orig_name = namebase + ".weight"
631
+
632
+ lazy_tensor = model[name]
633
+ assert len(lazy_tensor.shape) == 2
634
+ real_shape = [lazy_tensor.shape[1], lazy_tensor.shape[0] * 8]
635
+
636
+ # Calculate type. This replicates the logic in
637
+ # GPTQForLLaMaQuantizedTensor (which is executed when the modelis
638
+ # actually loaded).
639
+ lazy_scales = model[f"{namebase}.scales"]
640
+ scales_width = 1 if lazy_scales.shape[1] == 1 else lazy_scales.shape[0]
641
+ assert real_shape[1] % scales_width == 0
642
+ groupsize = real_shape[1] // scales_width
643
+ have_g_idx = f"{namebase}.g_idx" in model
644
+ data_type = QuantizedDataType(groupsize=groupsize, have_addends=True, have_g_idx=have_g_idx)
645
+
646
+ def load() -> Tensor:
647
+ return GPTQForLLaMaQuantizedTensor(model, namebase)
648
+
649
+ return (orig_name, LazyTensor(load, real_shape, data_type, '[quantized]'))
650
+ else:
651
+ return (name, model[name])
652
+ return dict(convert(name) for name in model)
653
+
654
+ # Functionality that simulates `torch.load` but where individual tensors are
655
+ # only loaded into memory on demand, not all at once.
656
+ # PyTorch can't do this natively as of time of writing:
657
+ # - https://github.com/pytorch/pytorch/issues/64327
658
+ # This allows us to de-shard without multiplying RAM usage, and also
659
+ # conveniently drops the PyTorch dependency (though we still need numpy).
660
+
661
+
662
+ @dataclass
663
+ class LazyStorageKind:
664
+ data_type: DataType
665
+
666
+
667
+ @dataclass
668
+ class LazyStorage:
669
+ load: Callable[[int, int], NDArray]
670
+ kind: LazyStorageKind
671
+ description: str
672
+
673
+
674
+ class LazyUnpickler(pickle.Unpickler):
675
+ def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
676
+ super().__init__(fp)
677
+ self.data_base_path = data_base_path
678
+ self.zip_file = zip_file
679
+
680
+ def persistent_load(self, pid: Any) -> Any:
681
+ assert pid[0] == 'storage'
682
+ assert isinstance(pid[1], LazyStorageKind)
683
+ data_type = pid[1].data_type
684
+ filename_stem = pid[2]
685
+ filename = self.data_base_path + '/' + filename_stem
686
+ info = self.zip_file.getinfo(filename)
687
+
688
+ def load(offset: int, elm_count: int) -> NDArray:
689
+ dtype = DATA_TYPE_TO_NUMPY.get(data_type)
690
+ if dtype is None:
691
+ raise Exception("tensor stored in unsupported format")
692
+ fp = self.zip_file.open(info)
693
+ fp.seek(offset * dtype.itemsize)
694
+ size = elm_count * dtype.itemsize
695
+ data = fp.read(size)
696
+ assert len(data) == size
697
+ return np.frombuffer(data, dtype)
698
+ description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
699
+ return LazyStorage(load=load, kind=pid[1], description=description)
700
+
701
+ # @staticmethod
702
+ def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
703
+ # pyright: ignore[reportSelfClsParameterName]
704
+ requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
705
+ assert isinstance(storage, LazyStorage)
706
+
707
+ def load() -> UnquantizedTensor:
708
+ elm_count = stride[0] * size[0]
709
+ return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
710
+ description = f'pickled storage_offset={storage_offset} in {storage.description}'
711
+ return LazyTensor(load, list(size), storage.kind.data_type, description)
712
+
713
+ # @staticmethod
714
+ def rebuild_from_type_v2(func, new_type, args, state):
715
+ return func(*args)
716
+
717
+ CLASSES: Dict[Any, Any] = {
718
+ ('torch._tensor', '_rebuild_from_type_v2'): rebuild_from_type_v2,
719
+ ('torch._utils', '_rebuild_tensor_v2'): lazy_rebuild_tensor_v2,
720
+ ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
721
+ ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
722
+ ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
723
+ ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
724
+ ('torch', 'Tensor'): LazyTensor,
725
+ }
726
+
727
+ def find_class(self, module: str, name: str) -> Any:
728
+ if not module.startswith('torch'):
729
+ return super().find_class(module, name)
730
+ return self.CLASSES[(module, name)]
731
+
732
+
733
+ def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
734
+ zf = zipfile.ZipFile(outer_fp)
735
+ pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
736
+ assert len(pickle_paths) == 1, pickle_paths
737
+ pickle_fp = zf.open(pickle_paths[0], 'r')
738
+ unpickler = LazyUnpickler(pickle_fp,
739
+ data_base_path=pickle_paths[0][:-4],
740
+ zip_file=zf)
741
+ model = unpickler.load()
742
+ as_dict = dict(model.items())
743
+ return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
744
+
745
+
746
+ SAFETENSORS_DATA_TYPES: Dict[str, DataType] = {
747
+ 'F16': DT_F16,
748
+ 'F32': DT_F32,
749
+ 'I32': DT_I32,
750
+ }
751
+
752
+
753
+ def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
754
+ header_size, = struct.unpack('<Q', fp.read(8))
755
+ header: Dict[str, Dict[str, Any]] = json.loads(fp.read(header_size))
756
+ # Use mmap for the actual data to avoid race conditions with the file offset.
757
+ mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
758
+ byte_buf = mapped[8 + header_size:]
759
+
760
+ def convert(info: Dict[str, Any]) -> LazyTensor:
761
+ data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
762
+ numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
763
+ shape: List[int] = info['shape']
764
+ begin, end = info['data_offsets']
765
+ assert 0 <= begin <= end <= len(byte_buf)
766
+ assert end - begin == math.prod(shape) * numpy_dtype.itemsize
767
+ buf = byte_buf[begin:end]
768
+
769
+ def load() -> UnquantizedTensor:
770
+ return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
771
+ description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
772
+ return LazyTensor(load, shape, data_type, description)
773
+ model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
774
+ return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
775
+
776
+
777
+ def must_read(fp: IO[bytes], length: int) -> bytes:
778
+ ret = fp.read(length)
779
+ if len(ret) < length:
780
+ raise Exception("unexpectedly reached end of file")
781
+ return ret
782
+
783
+
784
+ def lazy_load_ggml_file(fp: io.BufferedReader, path: Path) -> ModelPlus:
785
+ magic = must_read(fp, 4)[::-1]
786
+ if magic in (b'ggmf', b'ggjt'):
787
+ version, = struct.unpack("i", must_read(fp, 4))
788
+ assert version == 1
789
+ else:
790
+ assert magic == b'ggml'
791
+ version = None
792
+ n_vocab, n_embd, n_mult, n_head, n_layer, rot, file_type = struct.unpack('<7i', must_read(fp, 28))
793
+
794
+ tokens: List[Tuple[bytes, float]] = []
795
+ for i in range(n_vocab):
796
+ if i == 32000:
797
+ # HACK: GPT4All messed with the format without changing the magic
798
+ # number. Specifically, they changed the vocab section to contain
799
+ # `n_vocab - 1` tokens instead of `n_vocab` (i.e. omitting the
800
+ # extra pad token). Try to detect if we're reading a file like
801
+ # this.
802
+ orig_pos = fp.tell()
803
+ fp.seek(20, io.SEEK_CUR)
804
+ is_gpt4all = fp.read(21) == b'tok_embeddings.weight'
805
+ fp.seek(orig_pos)
806
+ if is_gpt4all:
807
+ break
808
+
809
+ length, = struct.unpack("i", must_read(fp, 4))
810
+ text = must_read(fp, length)
811
+ if magic != b'ggml':
812
+ score, = struct.unpack("f", must_read(fp, 4))
813
+ tokens.append((text, score))
814
+ vocab = GGMLVocab(tokens) if magic != b'ggml' else None
815
+
816
+ model: LazyModel = {}
817
+ # Use mmap for the actual data to avoid race conditions with the file offset.
818
+ off = fp.raw.tell()
819
+ mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
820
+ fp.raw.seek(off) # needed on Windows
821
+
822
+ def read_tensor() -> None: # this is a function so that variables captured in `load` don't change
823
+ shape_len, name_len, ftype = struct.unpack("iii", must_read(fp, 12))
824
+ assert 0 <= shape_len <= 3
825
+ shape: List[int] = list(struct.unpack(f"{shape_len}i", must_read(fp, 4 * shape_len)))
826
+ shape = shape[::-1]
827
+ name = must_read(fp, name_len).decode('utf-8')
828
+ data_type = FTYPE_TO_DATA_TYPE[ftype]
829
+
830
+ if magic == b'ggjt':
831
+ fp.seek((fp.tell() + 31) & -32)
832
+
833
+ if data_type == DT_Q4_1:
834
+ # See GPTQForLLaMaQuantizedTensor.ggml_ndarray()
835
+ size = 24 * (shape[1] // 32) * shape[0]
836
+ elif data_type == DT_Q4_0:
837
+ size = 20 * (shape[1] // 32) * shape[0]
838
+ else:
839
+ numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
840
+ elm_count = math.prod(shape)
841
+ size = elm_count * numpy_dtype.itemsize
842
+ offset = fp.tell()
843
+ buf = mapped[offset:offset+size]
844
+ fp.seek(size, io.SEEK_CUR)
845
+
846
+ def load() -> Tensor:
847
+ if isinstance(data_type, QuantizedDataType):
848
+ ndarray = np.frombuffer(buf, dtype=np.uint32)
849
+ return GGMLQuantizedTensor(ndarray, shape, data_type)
850
+ else:
851
+ return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
852
+ description = f'ggml offset={offset} type={data_type} path={path}'
853
+ model[name] = LazyTensor(load, shape, data_type, description)
854
+
855
+ while fp.read(1) != b'':
856
+ fp.seek(-1, io.SEEK_CUR)
857
+ read_tensor()
858
+
859
+ return ModelPlus(model=model, paths=[path], format='ggml', vocab=vocab)
860
+
861
+
862
+ @functools.lru_cache(maxsize=None)
863
+ def lazy_load_file(path: Path) -> ModelPlus:
864
+ fp = open(path, 'rb')
865
+ first8 = fp.read(8)
866
+ fp.seek(0)
867
+ if first8[:2] == b'PK':
868
+ # A zip file, i.e. PyTorch format
869
+ return lazy_load_torch_file(fp, path)
870
+ elif first8[2:4] == b'gg':
871
+ # GGML format
872
+ return lazy_load_ggml_file(fp, path)
873
+ elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
874
+ # Probably safetensors
875
+ return lazy_load_safetensors_file(fp, path)
876
+ else:
877
+ raise ValueError(f"unknown format: {path}")
878
+
879
+
880
+ In = TypeVar('In')
881
+ Out = TypeVar('Out')
882
+
883
+
884
+ def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int) -> Iterable[Out]:
885
+ '''Parallel map, but with backpressure. If the caller doesn't call `next`
886
+ fast enough, this will stop calling `func` at some point rather than
887
+ letting results pile up in memory. Specifically, there is a max of one
888
+ output value buffered per thread.'''
889
+ with concurrent.futures.ThreadPoolExecutor() as executor:
890
+ futures: List[concurrent.futures.Future[Out]] = []
891
+ items_rev = list(iterable)[::-1]
892
+ for i in range(min(concurrency, len(items_rev))):
893
+ futures.append(executor.submit(func, items_rev.pop()))
894
+ while futures:
895
+ result = futures.pop(0).result()
896
+ if items_rev:
897
+ futures.append(executor.submit(func, items_rev.pop()))
898
+ yield result
899
+
900
+
901
+ def check_vocab_size(params: Params, vocab: Vocab) -> None:
902
+ if params.n_vocab != vocab.vocab_size:
903
+ # GGMLVocab comes from the same file as the model so shouldn't mismatch:
904
+ assert isinstance(vocab, SentencePieceVocab)
905
+ if params.n_vocab == vocab.vocab_size_base:
906
+ print("Ignoring added_tokens.json since model matches vocab size without it.")
907
+ vocab.added_tokens_list = []
908
+ vocab.vocab_size = vocab.vocab_size_base
909
+ return
910
+ msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
911
+ if vocab.fname_added_tokens is not None:
912
+ msg += f" combined with {vocab.fname_added_tokens}"
913
+ msg += f" has {vocab.vocab_size})."
914
+ if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
915
+ msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
916
+ raise Exception(msg)
917
+
918
+
919
+ class OutputFile:
920
+ def __init__(self, fname_out: Path) -> None:
921
+ self.fout = open(fname_out, "wb")
922
+
923
+ def write_file_header(self, params: Params) -> None:
924
+ self.fout.write(b"ggjt"[::-1]) # magic
925
+ values = [
926
+ 1, # file version
927
+ params.n_vocab,
928
+ params.n_embd,
929
+ params.n_mult,
930
+ params.n_head,
931
+ params.n_layer,
932
+ params.n_embd // params.n_head, # rot (obsolete)
933
+ params.file_type.value,
934
+ ]
935
+ self.fout.write(struct.pack("i" * len(values), *values))
936
+
937
+ def write_tensor_header(self, name: str, shape: Sequence[int], data_type: DataType) -> None:
938
+ sname = name.encode('utf-8')
939
+ self.fout.write(struct.pack("iii", len(shape), len(sname), DATA_TYPE_TO_FTYPE[data_type]))
940
+ self.fout.write(struct.pack("i" * len(shape), *shape[::-1]))
941
+ self.fout.write(sname)
942
+ self.fout.seek((self.fout.tell() + 31) & -32)
943
+
944
+ def write_vocab(self, vocab: Vocab) -> None:
945
+ for text, score in vocab.all_tokens():
946
+ self.fout.write(struct.pack("i", len(text)))
947
+ self.fout.write(text)
948
+ self.fout.write(struct.pack("f", score))
949
+
950
+ @staticmethod
951
+ def write_vocab_only(fname_out: Path, vocab: Vocab) -> None:
952
+ of = OutputFile(fname_out)
953
+ params = Params(n_vocab=vocab.vocab_size, n_embd=0, n_mult=0,
954
+ n_head=1, n_layer=0, file_type=GGMLFileType.AllF32)
955
+ of = OutputFile(fname_out)
956
+ of.write_file_header(params)
957
+ of.write_vocab(vocab)
958
+ of.fout.close()
959
+
960
+ @staticmethod
961
+ def write_all(fname_out: Path, params: Params, model: LazyModel, vocab: Vocab) -> None:
962
+ check_vocab_size(params, vocab)
963
+ of = OutputFile(fname_out)
964
+ of.write_file_header(params)
965
+ print("Writing vocab...")
966
+ of.write_vocab(vocab)
967
+
968
+ def do_item(item: Tuple[str, LazyTensor]) -> NDArray:
969
+ name, lazy_tensor = item
970
+ return lazy_tensor.load().to_ggml().ndarray
971
+
972
+ ndarrays = bounded_parallel_map(do_item, model.items(), concurrency=8)
973
+ for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
974
+ size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
975
+ padi = len(str(len(model)))
976
+ print(f"[{i+1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type}")
977
+ of.write_tensor_header(name, lazy_tensor.shape, lazy_tensor.data_type)
978
+ ndarray.tofile(of.fout)
979
+ of.fout.close()
980
+
981
+
982
+ def pick_output_type(model: LazyModel, output_type_str: Optional[str]) -> GGMLFileType:
983
+ wq_type = model["layers.0.attention.wq.weight"].data_type
984
+ if output_type_str == "f32" or (output_type_str is None and wq_type in (DT_F32, DT_BF16)):
985
+ return GGMLFileType.AllF32
986
+ if output_type_str == "f16" or (output_type_str is None and wq_type == DT_F16):
987
+ return GGMLFileType.MostlyF16
988
+ if output_type_str == "q4_1" or (output_type_str is None and isinstance(wq_type, QuantizedDataType) and
989
+ wq_type.have_addends):
990
+ if isinstance(model["output.weight"].data_type, QuantizedDataType):
991
+ return GGMLFileType.MostlyQ4_1
992
+ else:
993
+ return GGMLFileType.PerLayerIsQ4_1
994
+ if output_type_str == "q4_0" or (output_type_str is None and isinstance(wq_type, QuantizedDataType)):
995
+ return GGMLFileType.MostlyQ4_0
996
+ name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
997
+ raise Exception(f"Unexpected combination of types: {name_to_type}")
998
+
999
+
1000
+ def do_necessary_conversions(model: LazyModel) -> LazyModel:
1001
+ model = handle_quantization(model)
1002
+
1003
+ if "lm_head.weight" in model:
1004
+ model = convert_transformers_to_orig(model)
1005
+ model = filter_and_sort_tensors(model)
1006
+
1007
+ return model
1008
+
1009
+
1010
+ def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
1011
+ return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
1012
+ for (name, tensor) in model.items()}
1013
+
1014
+
1015
+ def nth_multifile_path(path: Path, n: int) -> Optional[Path]:
1016
+ '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
1017
+ the nth path in the model.
1018
+ '''
1019
+ # Support the following patterns:
1020
+ patterns: List[Tuple[str, str]] = [
1021
+ # - x.00.pth, x.01.pth, etc.
1022
+ (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
1023
+ # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
1024
+ (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
1025
+ # x.bin, x.bin.1, etc.
1026
+ (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
1027
+ ]
1028
+ for regex, replacement in patterns:
1029
+ if re.search(regex, path.name):
1030
+ new_path = path.with_name(re.sub(regex, replacement, path.name))
1031
+ if new_path.exists():
1032
+ return new_path
1033
+ return None
1034
+
1035
+
1036
+ def find_multifile_paths(path: Path) -> List[Path]:
1037
+ '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
1038
+ the whole list of paths in the model.
1039
+ '''
1040
+ ret: List[Path] = []
1041
+ for i in itertools.count():
1042
+ nth_path = nth_multifile_path(path, i)
1043
+ if nth_path is None:
1044
+ break
1045
+ ret.append(nth_path)
1046
+ if not ret:
1047
+ # No matches. This should only happen if the file was named, e.g.,
1048
+ # foo.0, and there was no file named foo. Oh well, try to process it
1049
+ # as a single file.
1050
+ return [path]
1051
+ return ret
1052
+
1053
+
1054
+ def load_some_model(path: Path) -> ModelPlus:
1055
+ '''Load a model of any supported format.'''
1056
+ # Be extra-friendly and accept either a file or a directory:
1057
+ if path.is_dir():
1058
+ # Check if it's a set of safetensors files first
1059
+ files = list(path.glob("model-00001-of-*.safetensors"))
1060
+ if not files:
1061
+ # Try the PyTorch patterns too, with lower priority
1062
+ globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
1063
+ files = [file for glob in globs for file in path.glob(glob)]
1064
+ if not files:
1065
+ # Try GGML too, but with lower priority, since if both a non-GGML
1066
+ # model and a GGML model exist in the same directory, we assume the
1067
+ # latter was converted from the former.
1068
+ files = list(path.glob("ggml-model*.bin*"))
1069
+ if not files:
1070
+ raise Exception(f"Can't find model in directory {path}")
1071
+ if len(files) > 1:
1072
+ raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
1073
+ path = files[0]
1074
+
1075
+ paths = find_multifile_paths(path)
1076
+ models_plus: List[ModelPlus] = []
1077
+ for path in paths:
1078
+ print(f"Loading model file {path}")
1079
+ models_plus.append(lazy_load_file(path))
1080
+
1081
+ model_plus = merge_multifile_models(models_plus)
1082
+ return model_plus
1083
+
1084
+
1085
+ def filter_and_sort_tensors(model: LazyModel) -> LazyModel:
1086
+ return {name: model[name] for name in TENSORS_LIST if name in model}
1087
+
1088
+
1089
+ def load_vocab(path: Path) -> SentencePieceVocab:
1090
+ # Be extra-friendly and accept either a file or a directory. Also, if it's
1091
+ # a directory, it might be the model directory, and tokenizer.model might
1092
+ # be in the parent of that.
1093
+ if path.is_dir():
1094
+ path2 = path / "tokenizer.model"
1095
+ # Use `.parent` instead of /.. to handle the symlink case better.
1096
+ path3 = path.parent / "tokenizer.model"
1097
+ if path2.exists():
1098
+ path = path2
1099
+ elif path3.exists():
1100
+ path = path3
1101
+ else:
1102
+ raise FileNotFoundError(
1103
+ f"Could not find tokenizer.model in {path} or its parent; "
1104
+ "if it's in another directory, pass the directory as --vocab-dir")
1105
+ added_tokens_path = path.parent / "added_tokens.json"
1106
+ print(f"Loading vocab file {path}")
1107
+ return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
1108
+
1109
+
1110
+ def default_outfile(model_paths: List[Path], params: Params) -> Path:
1111
+ namestr = {
1112
+ GGMLFileType.AllF32: "f32",
1113
+ GGMLFileType.MostlyF16: "f16",
1114
+ GGMLFileType.MostlyQ4_0: "q4_0",
1115
+ GGMLFileType.MostlyQ4_1: "q4_1",
1116
+ GGMLFileType.PerLayerIsQ4_1: "q4_1",
1117
+ }[params.file_type]
1118
+ ret = model_paths[0].parent / f"ggml-model-{namestr}.bin"
1119
+ if ret in model_paths:
1120
+ sys.stderr.write(
1121
+ f"Error: Default output path ({ret}) would overwrite the input. "
1122
+ "Please explicitly specify a path using --outfile.\n")
1123
+ sys.exit(1)
1124
+ return ret
1125
+
1126
+
1127
+ def do_dump_model(model_plus: ModelPlus) -> None:
1128
+ print(f"model_plus.paths = {model_plus.paths!r}")
1129
+ print(f"model_plus.format = {model_plus.format!r}")
1130
+ print(f"model_plus.vocab = {model_plus.vocab!r}")
1131
+ for name, lazy_tensor in model_plus.model.items():
1132
+ print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
1133
+
1134
+
1135
+ def main(args_in: Optional[List[str]] = None) -> None:
1136
+ parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
1137
+ parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
1138
+ parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
1139
+ parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
1140
+ parser.add_argument("--outtype", choices=["f32", "f16", "q4_1", "q4_0"], help="output format (default: based on input)")
1141
+ parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
1142
+ parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
1143
+ parser.add_argument("model", type=Path,
1144
+ help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
1145
+ args = parser.parse_args(args_in)
1146
+
1147
+ vocab: Vocab
1148
+ if args.dump_single:
1149
+ model_plus = lazy_load_file(args.model)
1150
+ do_dump_model(model_plus)
1151
+ elif args.vocab_only:
1152
+ vocab = load_vocab(args.vocab_dir or args.model)
1153
+ assert args.outfile, "need --outfile if using --vocab-only"
1154
+ outfile = args.outfile
1155
+ OutputFile.write_vocab_only(outfile, vocab)
1156
+ print(f"Wrote {outfile}")
1157
+ else:
1158
+ model_plus = load_some_model(args.model)
1159
+ if args.dump:
1160
+ do_dump_model(model_plus)
1161
+ return
1162
+ if model_plus.vocab is not None and args.vocab_dir is None:
1163
+ vocab = model_plus.vocab
1164
+ else:
1165
+ vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
1166
+ vocab = load_vocab(vocab_dir)
1167
+ model = model_plus.model
1168
+ model = do_necessary_conversions(model)
1169
+ output_type = pick_output_type(model, args.outtype)
1170
+ model = convert_to_output_type(model, output_type)
1171
+ params = Params.guessed(model, output_type)
1172
+ outfile = args.outfile or default_outfile(model_plus.paths, params)
1173
+ OutputFile.write_all(outfile, params, model, vocab)
1174
+ print(f"Wrote {outfile}")
1175
+
1176
+
1177
+ if __name__ == '__main__':
1178
+ 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,1696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ggml.h"
2
+ #include <vector>
3
+ #include <cassert>
4
+ #include <random>
5
+ #include <cstring>
6
+
7
+ #if defined(_MSC_VER)
8
+ #pragma warning(disable: 4244 4267) // possible loss of data
9
+ #endif
10
+
11
+ float frand() {
12
+ return (float)rand()/(float)RAND_MAX;
13
+ }
14
+
15
+ struct random_normal_distribution {
16
+ std::mt19937 gen;
17
+ std::normal_distribution<float> nd;
18
+ float min;
19
+ float max;
20
+ };
21
+
22
+ void init_random_normal_distribution(struct random_normal_distribution * rnd, int seed, float mean, float std, float min, float max) {
23
+ rnd->gen = std::mt19937(seed);
24
+ rnd->nd = std::normal_distribution<float>{mean, std};
25
+ rnd->min = min;
26
+ rnd->max = max;
27
+ }
28
+
29
+ float frand_normal(struct random_normal_distribution * rnd) {
30
+ const float r = rnd->nd(rnd->gen);
31
+ return ((r < rnd->min) ? (rnd->min) : (r > rnd->max) ? (rnd->max) : r);
32
+ }
33
+
34
+ struct ggml_tensor * randomize_tensor(
35
+ struct ggml_tensor * tensor,
36
+ int ndims,
37
+ const int64_t ne[],
38
+ float fmin,
39
+ float fmax) {
40
+
41
+ switch (ndims) {
42
+ case 1:
43
+ for (int i0 = 0; i0 < ne[0]; i0++) {
44
+ ((float *)tensor->data)[i0] = frand()*(fmax - fmin) + fmin;
45
+ }
46
+ break;
47
+ case 2:
48
+ for (int i1 = 0; i1 < ne[1]; i1++) {
49
+ for (int i0 = 0; i0 < ne[0]; i0++) {
50
+ ((float *)tensor->data)[i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
51
+ }
52
+ }
53
+ break;
54
+ case 3:
55
+ for (int i2 = 0; i2 < ne[2]; i2++) {
56
+ for (int i1 = 0; i1 < ne[1]; i1++) {
57
+ for (int i0 = 0; i0 < ne[0]; i0++) {
58
+ ((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
59
+ }
60
+ }
61
+ }
62
+ break;
63
+ case 4:
64
+ for (int i3 = 0; i3 < ne[3]; i3++) {
65
+ for (int i2 = 0; i2 < ne[2]; i2++) {
66
+ for (int i1 = 0; i1 < ne[1]; i1++) {
67
+ for (int i0 = 0; i0 < ne[0]; i0++) {
68
+ ((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = frand()*(fmax - fmin) + fmin;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ break;
74
+ default:
75
+ assert(false);
76
+ };
77
+
78
+ return tensor;
79
+ }
80
+
81
+ struct ggml_tensor * randomize_tensor_normal(
82
+ struct ggml_tensor * tensor,
83
+ int ndims,
84
+ const int64_t ne[],
85
+ struct random_normal_distribution * rnd) {
86
+ float scale = 1.0; // xavier
87
+ switch (ndims) {
88
+ case 1:
89
+ scale /= sqrtf(ne[0]);
90
+ for (int i0 = 0; i0 < ne[0]; i0++) {
91
+ ((float *)tensor->data)[i0] = scale * frand_normal(rnd);
92
+ }
93
+ break;
94
+ case 2:
95
+ scale /= sqrtf(ne[0]+ne[1]);
96
+ for (int i1 = 0; i1 < ne[1]; i1++) {
97
+ for (int i0 = 0; i0 < ne[0]; i0++) {
98
+ ((float *)tensor->data)[i1*ne[0] + i0] = scale * frand_normal(rnd);
99
+ }
100
+ }
101
+ break;
102
+ case 3:
103
+ scale /= sqrtf(ne[0]+ne[1]);
104
+ for (int i2 = 0; i2 < ne[2]; i2++) {
105
+ for (int i1 = 0; i1 < ne[1]; i1++) {
106
+ for (int i0 = 0; i0 < ne[0]; i0++) {
107
+ ((float *)tensor->data)[i2*ne[1]*ne[0] + i1*ne[0] + i0] = scale * frand_normal(rnd);
108
+ }
109
+ }
110
+ }
111
+ break;
112
+ case 4:
113
+ scale /= sqrtf(ne[0]+ne[1]);
114
+ for (int i3 = 0; i3 < ne[3]; i3++) {
115
+ for (int i2 = 0; i2 < ne[2]; i2++) {
116
+ for (int i1 = 0; i1 < ne[1]; i1++) {
117
+ for (int i0 = 0; i0 < ne[0]; i0++) {
118
+ ((float *)tensor->data)[i3*ne[2]*ne[1]*ne[0] + i2*ne[1]*ne[0] + i1*ne[0] + i0] = scale * frand_normal(rnd);
119
+ }
120
+ }
121
+ }
122
+ }
123
+ break;
124
+ default:
125
+ assert(false);
126
+ };
127
+
128
+ return tensor;
129
+ }
130
+
131
+ struct llama_hparams {
132
+ uint32_t n_vocab = 32000;
133
+ uint32_t n_ctx = 512; // this is provided as user input?
134
+ uint32_t n_embd = 4096;
135
+ uint32_t n_mult = 4;
136
+ uint32_t n_head = 32;
137
+ uint32_t n_layer = 32;
138
+ uint32_t n_rot = 64;
139
+
140
+ bool operator!=(const llama_hparams & other) const {
141
+ return memcmp(this, &other, sizeof(llama_hparams));
142
+ }
143
+ };
144
+
145
+ uint32_t get_n_ff(const struct llama_hparams* hparams) {
146
+ const uint32_t n_ff = ((2*(4*hparams->n_embd)/3 + hparams->n_mult - 1)/hparams->n_mult)*hparams->n_mult;
147
+ return n_ff;
148
+ }
149
+
150
+ struct llama_hparams_lora {
151
+ uint32_t n_vocab = 32000;
152
+ uint32_t n_ctx = 512; // this is provided as user input?
153
+ uint32_t n_embd = 4096;
154
+ uint32_t n_mult = 4;
155
+ uint32_t n_head = 32;
156
+ uint32_t n_layer = 32;
157
+ uint32_t n_rot = 64;
158
+ uint32_t n_lora = 64;
159
+
160
+ bool operator!=(const llama_hparams_lora & other) const {
161
+ return memcmp(this, &other, sizeof(llama_hparams_lora)) != 0;
162
+ }
163
+ };
164
+
165
+ struct llama_layer {
166
+ // normalization
167
+ struct ggml_tensor * attention_norm;
168
+
169
+ // attention
170
+ struct ggml_tensor * wq;
171
+ struct ggml_tensor * wk;
172
+ struct ggml_tensor * wv;
173
+ struct ggml_tensor * wo;
174
+
175
+ // normalization
176
+ struct ggml_tensor * ffn_norm;
177
+
178
+ // ff
179
+ struct ggml_tensor * w1;
180
+ struct ggml_tensor * w2;
181
+ struct ggml_tensor * w3;
182
+ };
183
+
184
+ struct llama_layer_lora {
185
+ // normalization
186
+ struct ggml_tensor * attention_norm;
187
+
188
+ // attention
189
+ struct ggml_tensor * wqa;
190
+ struct ggml_tensor * wqb;
191
+ struct ggml_tensor * wka;
192
+ struct ggml_tensor * wkb;
193
+ struct ggml_tensor * wva;
194
+ struct ggml_tensor * wvb;
195
+ struct ggml_tensor * woa;
196
+ struct ggml_tensor * wob;
197
+
198
+ // normalization
199
+ struct ggml_tensor * ffn_norm;
200
+
201
+ // ff
202
+ struct ggml_tensor * w1;
203
+ struct ggml_tensor * w2;
204
+ struct ggml_tensor * w3;
205
+ };
206
+
207
+
208
+ struct llama_kv_cache {
209
+ struct ggml_context * ctx = NULL;
210
+
211
+ struct ggml_tensor * k;
212
+ struct ggml_tensor * v;
213
+
214
+ // llama_ctx_buffer buf;
215
+
216
+ int n; // number of tokens currently in the cache
217
+ };
218
+
219
+ struct llama_model {
220
+ struct ggml_context * ctx = NULL;
221
+
222
+ llama_hparams hparams;
223
+
224
+ struct ggml_tensor * tok_embeddings;
225
+
226
+ struct ggml_tensor * norm;
227
+ struct ggml_tensor * output;
228
+
229
+ std::vector<llama_layer> layers;
230
+ };
231
+
232
+ struct llama_model_lora {
233
+ struct ggml_context * ctx = NULL;
234
+
235
+ llama_hparams_lora hparams;
236
+
237
+ struct ggml_tensor * tok_embeddings;
238
+
239
+ struct ggml_tensor * norm;
240
+ struct ggml_tensor * outputa;
241
+ struct ggml_tensor * outputb;
242
+
243
+ std::vector<llama_layer_lora> layers;
244
+ };
245
+
246
+ void init_model(struct llama_model * model) {
247
+ const auto & hparams = model->hparams;
248
+
249
+ const uint32_t n_embd = hparams.n_embd;
250
+ const uint32_t n_layer = hparams.n_layer;
251
+ const uint32_t n_vocab = hparams.n_vocab;
252
+
253
+ const uint32_t n_ff = get_n_ff(&hparams);
254
+
255
+ struct ggml_context * ctx = model->ctx;
256
+
257
+ model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
258
+ model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
259
+ model->output = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("output.weight", {n_embd, n_vocab});
260
+
261
+ model->layers.resize(n_layer);
262
+ for (uint32_t i = 0; i < n_layer; ++i) {
263
+ auto & layer = model->layers[i];
264
+
265
+ // std::string layers_i = "layers." + std::to_string(i);
266
+
267
+ layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
268
+
269
+ layer.wq = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
270
+ layer.wk = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
271
+ layer.wv = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
272
+ layer.wo = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
273
+
274
+ layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
275
+
276
+ layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
277
+ layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
278
+ layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
279
+ }
280
+ }
281
+
282
+
283
+ void init_model_lora(struct llama_model_lora * model) {
284
+ const auto & hparams = model->hparams;
285
+
286
+ const uint32_t n_embd = hparams.n_embd;
287
+ const uint32_t n_mult = hparams.n_mult;
288
+ const uint32_t n_layer = hparams.n_layer;
289
+ const uint32_t n_vocab = hparams.n_vocab;
290
+ const uint32_t n_lora = hparams.n_lora;
291
+
292
+ const uint32_t n_ff = ((2*(4*n_embd)/3 + n_mult - 1)/n_mult)*n_mult;
293
+
294
+ struct ggml_context * ctx = model->ctx;
295
+
296
+ model->tok_embeddings = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_vocab); // ("tok_embeddings.weight", {n_embd, n_vocab});
297
+ model->norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // ("norm.weight", {n_embd});
298
+ model->outputa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_vocab); // ("output.weight", {n_embd, n_vocab});
299
+ model->outputb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // ("output.weight", {n_embd, n_vocab});
300
+
301
+ model->layers.resize(n_layer);
302
+ for (uint32_t i = 0; i < n_layer; ++i) {
303
+ auto & layer = model->layers[i];
304
+
305
+ // std::string layers_i = "layers." + std::to_string(i);
306
+
307
+ layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".attention_norm.weight", {n_embd});
308
+
309
+ layer.wqa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
310
+ layer.wqb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wq.weight", {n_embd, n_embd});
311
+ layer.wka = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
312
+ layer.wkb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wk.weight", {n_embd, n_embd});
313
+ layer.wva = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
314
+ layer.wvb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wv.weight", {n_embd, n_embd});
315
+ layer.woa = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_lora, n_embd); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
316
+ layer.wob = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_lora); // (layers_i + ".attention.wo.weight", {n_embd, n_embd});
317
+
318
+ layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); // (layers_i + ".ffn_norm.weight", {n_embd});
319
+
320
+ layer.w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
321
+ layer.w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_ff, n_embd); // (layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
322
+ layer.w3 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ff); // (layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
323
+ }
324
+ }
325
+
326
+ void set_param_model(struct llama_model * model) {
327
+ const auto& hparams = model->hparams;
328
+
329
+ const uint32_t n_layer = hparams.n_layer;
330
+
331
+ struct ggml_context* ctx = model->ctx;
332
+
333
+ ggml_set_param(ctx, model->tok_embeddings);
334
+ ggml_set_param(ctx, model->norm);
335
+ ggml_set_param(ctx, model->output);
336
+
337
+ for (uint32_t i = 0; i < n_layer; ++i) {
338
+ auto & layer = model->layers[i];
339
+
340
+ ggml_set_param(ctx, layer.attention_norm);
341
+ ggml_set_param(ctx, layer.wq);
342
+ ggml_set_param(ctx, layer.wk);
343
+ ggml_set_param(ctx, layer.wv);
344
+ ggml_set_param(ctx, layer.wo);
345
+ ggml_set_param(ctx, layer.ffn_norm);
346
+ ggml_set_param(ctx, layer.w1);
347
+ ggml_set_param(ctx, layer.w2);
348
+ ggml_set_param(ctx, layer.w3);
349
+ }
350
+ }
351
+
352
+ void set_param_model_lora(struct llama_model_lora * model) {
353
+ const auto& hparams = model->hparams;
354
+
355
+ const uint32_t n_layer = hparams.n_layer;
356
+
357
+ struct ggml_context* ctx = model->ctx;
358
+
359
+ ggml_set_param(ctx, model->tok_embeddings);
360
+ ggml_set_param(ctx, model->norm);
361
+ ggml_set_param(ctx, model->outputa);
362
+ ggml_set_param(ctx, model->outputb);
363
+
364
+ for (uint32_t i = 0; i < n_layer; ++i) {
365
+ auto & layer = model->layers[i];
366
+
367
+ ggml_set_param(ctx, layer.attention_norm);
368
+ ggml_set_param(ctx, layer.wqa);
369
+ ggml_set_param(ctx, layer.wqb);
370
+ ggml_set_param(ctx, layer.wka);
371
+ ggml_set_param(ctx, layer.wkb);
372
+ ggml_set_param(ctx, layer.wva);
373
+ ggml_set_param(ctx, layer.wvb);
374
+ ggml_set_param(ctx, layer.woa);
375
+ ggml_set_param(ctx, layer.wob);
376
+ ggml_set_param(ctx, layer.ffn_norm);
377
+ ggml_set_param(ctx, layer.w1);
378
+ ggml_set_param(ctx, layer.w2);
379
+ ggml_set_param(ctx, layer.w3);
380
+ }
381
+ }
382
+
383
+ void randomize_model(struct llama_model * model, int seed, float mean, float std, float min, float max) {
384
+ const auto & hparams = model->hparams;
385
+
386
+ const uint32_t n_layer = hparams.n_layer;
387
+
388
+ struct random_normal_distribution rnd;
389
+ init_random_normal_distribution(&rnd, seed, mean, std, min, max);
390
+ randomize_tensor_normal(model->tok_embeddings, model->tok_embeddings->n_dims, model->tok_embeddings->ne, &rnd);
391
+ randomize_tensor_normal(model->norm, model->norm->n_dims, model->norm->ne, &rnd);
392
+ randomize_tensor_normal(model->output, model->output->n_dims, model->output->ne, &rnd);
393
+
394
+ for (uint32_t i = 0; i < n_layer; ++i) {
395
+ auto & layer = model->layers[i];
396
+ randomize_tensor_normal(layer.attention_norm, layer.attention_norm->n_dims, layer.attention_norm->ne, &rnd);
397
+
398
+ randomize_tensor_normal(layer.wq, layer.wq->n_dims, layer.wq->ne, &rnd);
399
+ randomize_tensor_normal(layer.wk, layer.wk->n_dims, layer.wk->ne, &rnd);
400
+ randomize_tensor_normal(layer.wv, layer.wv->n_dims, layer.wv->ne, &rnd);
401
+ randomize_tensor_normal(layer.wo, layer.wo->n_dims, layer.wo->ne, &rnd);
402
+
403
+ randomize_tensor_normal(layer.ffn_norm, layer.ffn_norm->n_dims, layer.ffn_norm->ne, &rnd);
404
+
405
+ randomize_tensor_normal(layer.w1, layer.w1->n_dims, layer.w1->ne, &rnd);
406
+ randomize_tensor_normal(layer.w2, layer.w2->n_dims, layer.w2->ne, &rnd);
407
+ randomize_tensor_normal(layer.w3, layer.w3->n_dims, layer.w3->ne, &rnd);
408
+ }
409
+ }
410
+
411
+
412
+ void randomize_model_lora(struct llama_model_lora * model, int seed, float mean, float std, float min, float max) {
413
+ const auto & hparams = model->hparams;
414
+
415
+ const uint32_t n_layer = hparams.n_layer;
416
+
417
+ struct random_normal_distribution rnd;
418
+ init_random_normal_distribution(&rnd, seed, mean, std, min, max);
419
+ randomize_tensor_normal(model->tok_embeddings, model->tok_embeddings->n_dims, model->tok_embeddings->ne, &rnd);
420
+ randomize_tensor_normal(model->norm, model->norm->n_dims, model->norm->ne, &rnd);
421
+ randomize_tensor_normal(model->outputa, model->outputa->n_dims, model->outputa->ne, &rnd);
422
+ randomize_tensor_normal(model->outputb, model->outputb->n_dims, model->outputb->ne, &rnd);
423
+
424
+ for (uint32_t i = 0; i < n_layer; ++i) {
425
+ auto & layer = model->layers[i];
426
+ randomize_tensor_normal(layer.attention_norm, layer.attention_norm->n_dims, layer.attention_norm->ne, &rnd);
427
+
428
+ randomize_tensor_normal(layer.wqa, layer.wqa->n_dims, layer.wqa->ne, &rnd);
429
+ randomize_tensor_normal(layer.wqb, layer.wqb->n_dims, layer.wqb->ne, &rnd);
430
+ randomize_tensor_normal(layer.wka, layer.wka->n_dims, layer.wka->ne, &rnd);
431
+ randomize_tensor_normal(layer.wkb, layer.wkb->n_dims, layer.wkb->ne, &rnd);
432
+ randomize_tensor_normal(layer.wva, layer.wva->n_dims, layer.wva->ne, &rnd);
433
+ randomize_tensor_normal(layer.wvb, layer.wvb->n_dims, layer.wvb->ne, &rnd);
434
+ randomize_tensor_normal(layer.woa, layer.woa->n_dims, layer.woa->ne, &rnd);
435
+ randomize_tensor_normal(layer.wob, layer.wob->n_dims, layer.wob->ne, &rnd);
436
+
437
+ randomize_tensor_normal(layer.ffn_norm, layer.ffn_norm->n_dims, layer.ffn_norm->ne, &rnd);
438
+
439
+ randomize_tensor_normal(layer.w1, layer.w1->n_dims, layer.w1->ne, &rnd);
440
+ randomize_tensor_normal(layer.w2, layer.w2->n_dims, layer.w2->ne, &rnd);
441
+ randomize_tensor_normal(layer.w3, layer.w3->n_dims, layer.w3->ne, &rnd);
442
+ }
443
+ }
444
+
445
+ bool init_kv_cache(struct llama_kv_cache* cache, struct llama_model * model, int n_batch) {
446
+ const auto & hparams = model->hparams;
447
+
448
+ const uint32_t n_ctx = hparams.n_ctx;
449
+ const uint32_t n_embd = hparams.n_embd;
450
+ const uint32_t n_layer = hparams.n_layer;
451
+
452
+ const int64_t n_mem = n_layer*n_ctx*n_batch;
453
+ const int64_t n_elements = n_embd*n_mem;
454
+
455
+ // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
456
+
457
+ // struct ggml_init_params params;
458
+ // params.mem_size = cache.buf.size;
459
+ // params.mem_buffer = cache.buf.addr;
460
+ // params.no_alloc = false;
461
+ if (!cache->ctx) {
462
+ struct ggml_init_params params;
463
+ params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
464
+ params.mem_buffer = NULL;
465
+ params.no_alloc = false;
466
+
467
+ cache->ctx = ggml_init(params);
468
+
469
+ if (!cache->ctx) {
470
+ fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
471
+ return false;
472
+ }
473
+ }
474
+
475
+ cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
476
+ cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
477
+
478
+ return true;
479
+ }
480
+
481
+ bool init_kv_cache_lora(struct llama_kv_cache* cache, struct llama_model_lora * model, int n_batch) {
482
+ const auto & hparams = model->hparams;
483
+
484
+ const uint32_t n_ctx = hparams.n_ctx;
485
+ const uint32_t n_embd = hparams.n_embd;
486
+ const uint32_t n_layer = hparams.n_layer;
487
+
488
+ const int64_t n_mem = n_layer*n_ctx*n_batch;
489
+ const int64_t n_elements = n_embd*n_mem;
490
+
491
+ // cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
492
+
493
+ // struct ggml_init_params params;
494
+ // params.mem_size = cache.buf.size;
495
+ // params.mem_buffer = cache.buf.addr;
496
+ // params.no_alloc = false;
497
+ if (!cache->ctx) {
498
+ struct ggml_init_params params;
499
+ params.mem_size = 2u*n_elements*ggml_type_size(GGML_TYPE_F32) + 2u*1024*1024;
500
+ params.mem_buffer = NULL;
501
+ params.no_alloc = false;
502
+
503
+ cache->ctx = ggml_init(params);
504
+
505
+ if (!cache->ctx) {
506
+ fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
507
+ return false;
508
+ }
509
+ }
510
+
511
+ cache->k = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
512
+ cache->v = ggml_new_tensor_1d(cache->ctx, GGML_TYPE_F32, n_elements);
513
+
514
+ return true;
515
+ }
516
+
517
+ struct ggml_tensor * forward(
518
+ struct llama_model * model,
519
+ struct llama_kv_cache * cache,
520
+ struct ggml_context * ctx0,
521
+ struct ggml_cgraph * gf,
522
+ struct ggml_tensor * tokens_input,
523
+ const int n_tokens,
524
+ const int n_past) {
525
+
526
+ const int N = n_tokens;
527
+
528
+ struct llama_kv_cache& kv_self = *cache;
529
+ const auto & hparams = model->hparams;
530
+ const int n_ctx = hparams.n_ctx;
531
+ const int n_embd = hparams.n_embd;
532
+ const int n_layer = hparams.n_layer;
533
+ const int n_head = hparams.n_head;
534
+ const int n_rot = hparams.n_rot;
535
+
536
+ struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
537
+ memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
538
+
539
+ struct ggml_tensor * kc = kv_self.k;
540
+ struct ggml_tensor * vc = kv_self.v;
541
+
542
+ // inpL shape [n_embd,N,1,1]
543
+ struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
544
+ for (int il = 0; il < n_layer; ++il) {
545
+ struct ggml_tensor * inpSA = inpL;
546
+
547
+ struct ggml_tensor * cur;
548
+
549
+ // lctx.use_buf(ctx0, 0);
550
+
551
+ // norm
552
+ {
553
+ // cur shape [n_embd,N,1,1]
554
+ cur = ggml_rms_norm(ctx0, inpL);
555
+
556
+ // cur = attention_norm*cur
557
+ cur = ggml_mul(ctx0,
558
+ ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
559
+ cur);
560
+ }
561
+
562
+ // self-attention
563
+ {
564
+ // compute Q and K and RoPE them
565
+ // wq shape [n_embd, n_embd, 1, 1]
566
+ // wk shape [n_embd, n_embd, 1, 1]
567
+ // Qcur shape [n_embd/n_head, n_head, N, 1]
568
+ // Kcur shape [n_embd/n_head, n_head, N, 1]
569
+ 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);
570
+ 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);
571
+
572
+ // store key and value to memory
573
+ {
574
+ // compute the transposed [N, n_embd] V matrix
575
+ // wv shape [n_embd, n_embd, 1, 1]
576
+ // Vcur shape [n_embd, N, 1, 1]
577
+ 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)));
578
+
579
+ // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
580
+ // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
581
+ // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
582
+ // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
583
+
584
+ /* {
585
+ 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));
586
+ struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
587
+ ( n_ctx)*ggml_element_size(kv_self.v),
588
+ (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
589
+
590
+ // important: storing RoPE-ed version of K in the KV cache!
591
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
592
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
593
+ } //*/
594
+
595
+ 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));
596
+ vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
597
+ (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
598
+ }
599
+
600
+ // Qcur shape [n_embd/n_head, n_head, N, 1]
601
+ // Q shape [n_embd/n_head, N, n_head, 1]
602
+ struct ggml_tensor * Q =
603
+ ggml_permute(ctx0,
604
+ Qcur,
605
+ 0, 2, 1, 3);
606
+
607
+ // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
608
+ // K shape [n_embd/n_head, n_past + N, n_head, 1]
609
+ struct ggml_tensor * K =
610
+ ggml_permute(ctx0,
611
+ ggml_reshape_3d(ctx0,
612
+ ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
613
+ n_embd/n_head, n_head, n_past + N),
614
+ 0, 2, 1, 3);
615
+
616
+ // K * Q
617
+ // KQ shape [n_past + N, N, n_head, 1]
618
+ struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
619
+
620
+ // KQ_scaled = KQ / sqrt(n_embd/n_head)
621
+ // KQ_scaled shape [n_past + N, N, n_head, 1]
622
+ struct ggml_tensor * KQ_scaled =
623
+ ggml_scale(ctx0,
624
+ KQ,
625
+ ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
626
+
627
+ // KQ_masked = mask_past(KQ_scaled)
628
+ // KQ_masked shape [n_past + N, N, n_head, 1]
629
+ struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
630
+
631
+ // KQ = soft_max(KQ_masked)
632
+ // KQ_soft_max shape [n_past + N, N, n_head, 1]
633
+ struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
634
+
635
+ // split cached V into n_head heads
636
+ //// V shape [n_past + N, n_embd/n_head, n_head, 1]
637
+ // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
638
+ struct ggml_tensor * V =
639
+ ggml_view_3d(ctx0, vc,
640
+ n_past + N, n_embd/n_head, n_head,
641
+ n_ctx*ggml_element_size(vc),
642
+ n_ctx*ggml_element_size(vc)*n_embd/n_head,
643
+ il*n_ctx*ggml_element_size(vc)*n_embd);
644
+
645
+ // KQV shape [n_embd/n_head, N, n_head, 1]
646
+ struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
647
+
648
+ // KQV_merged = KQV.permute(0, 2, 1, 3)
649
+ // KQV_merged shape [n_embd/n_head, n_head, N, 1]
650
+ struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
651
+ // KQV_merged shape
652
+
653
+ // cur = KQV_merged.contiguous().view(n_embd, N)
654
+ // cur shape [n_embd,N,1,1]
655
+ cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
656
+ // cur = ggml_cpy(ctx0,
657
+ // KQV_merged,
658
+ // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
659
+
660
+ // projection (no bias)
661
+ // cur shape [n_embd,N,1,1]
662
+ cur = ggml_mul_mat(ctx0,
663
+ model->layers[il].wo,
664
+ cur);
665
+ }
666
+
667
+ // lctx.use_buf(ctx0, 1);
668
+
669
+ // inpFF shape [n_embd,N,1,1]
670
+ struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
671
+
672
+ // feed-forward network
673
+ {
674
+ // norm
675
+ {
676
+ // cur shape [n_embd,N,1,1]
677
+ cur = ggml_rms_norm(ctx0, inpFF);
678
+
679
+ // cur = ffn_norm*cur
680
+ // cur shape [n_embd,N,1,1]
681
+ cur = ggml_mul(ctx0,
682
+ ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
683
+ cur);
684
+ }
685
+
686
+ // tmp shape [n_ff,N,1,1]
687
+ struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
688
+ model->layers[il].w3,
689
+ cur);
690
+
691
+ // cur shape [n_ff,N,1,1]
692
+ cur = ggml_mul_mat(ctx0,
693
+ model->layers[il].w1,
694
+ cur);
695
+
696
+ // SILU activation
697
+ // cur shape [n_ff,N,1,1]
698
+ cur = ggml_silu(ctx0, cur);
699
+
700
+ // cur shape [n_ff,N,1,1]
701
+ cur = ggml_mul(ctx0, cur, tmp);
702
+
703
+ // cur shape [n_embd,N,1,1]
704
+ cur = ggml_mul_mat(ctx0,
705
+ model->layers[il].w2,
706
+ cur);
707
+ }
708
+
709
+ // cur shape [n_embd,N,1,1]
710
+ cur = ggml_add(ctx0, cur, inpFF);
711
+
712
+ // input for next layer
713
+ // inpL shape [n_embd,N,1,1]
714
+ inpL = cur;
715
+ }
716
+
717
+ // norm
718
+ {
719
+
720
+ // inpL shape [n_embd,N,1,1]
721
+ inpL = ggml_rms_norm(ctx0, inpL);
722
+
723
+ // inpL = norm*inpL
724
+ // inpL shape [n_embd,N,1,1]
725
+ inpL = ggml_mul(ctx0,
726
+ ggml_repeat(ctx0, model->norm, inpL),
727
+ inpL);
728
+
729
+ //embeddings = inpL;
730
+ }
731
+
732
+ // lm_head
733
+ // inpL shape [n_vocab,N,1,1]
734
+ inpL = ggml_mul_mat(ctx0, model->output, inpL);
735
+
736
+ // run the computation
737
+ ggml_build_forward_expand(gf, inpL);
738
+
739
+ return inpL;
740
+ }
741
+
742
+ void assert_shape_1d(struct ggml_tensor * tensor, int64_t ne0) {
743
+ GGML_ASSERT(tensor->n_dims == 1);
744
+ GGML_ASSERT(tensor->ne[0] == ne0);
745
+ }
746
+
747
+ void assert_shape_2d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1) {
748
+ GGML_ASSERT(tensor->n_dims == 2);
749
+ GGML_ASSERT(tensor->ne[0] == ne0);
750
+ GGML_ASSERT(tensor->ne[1] == ne1);
751
+ }
752
+
753
+ void assert_shape_3d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2) {
754
+ GGML_ASSERT(tensor->n_dims == 3);
755
+ GGML_ASSERT(tensor->ne[0] == ne0);
756
+ GGML_ASSERT(tensor->ne[1] == ne1);
757
+ GGML_ASSERT(tensor->ne[2] == ne2);
758
+ }
759
+
760
+ void assert_shape_4d(struct ggml_tensor * tensor, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
761
+ GGML_ASSERT(tensor->n_dims == 4);
762
+ GGML_ASSERT(tensor->ne[0] == ne0);
763
+ GGML_ASSERT(tensor->ne[1] == ne1);
764
+ GGML_ASSERT(tensor->ne[2] == ne2);
765
+ GGML_ASSERT(tensor->ne[3] == ne3);
766
+ }
767
+
768
+ struct ggml_tensor * forward_batch(
769
+ struct llama_model * model,
770
+ struct llama_kv_cache * cache,
771
+ struct ggml_context * ctx0,
772
+ struct ggml_cgraph * gf,
773
+ struct ggml_tensor * tokens_input,
774
+ const int n_tokens,
775
+ const int n_past,
776
+ const int n_batch) {
777
+
778
+ const int N = n_tokens;
779
+
780
+ struct llama_kv_cache& kv_self = *cache;
781
+ const auto & hparams = model->hparams;
782
+ const int n_ctx = hparams.n_ctx;
783
+ const int n_vocab = hparams.n_vocab;
784
+ const int n_embd = hparams.n_embd;
785
+ const int n_layer = hparams.n_layer;
786
+ const int n_head = hparams.n_head;
787
+ const int n_rot = hparams.n_rot;
788
+ const int n_ff = get_n_ff(&hparams);
789
+
790
+ struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N*n_batch);
791
+ memcpy(tokens->data, tokens_input->data, ggml_element_size(tokens)*N*n_batch);
792
+
793
+ struct ggml_tensor * kc = kv_self.k;
794
+ struct ggml_tensor * vc = kv_self.v;
795
+
796
+ // inpL shape [n_embd,N*n_batch,1]
797
+ struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
798
+ assert_shape_2d(inpL, n_embd, N*n_batch);
799
+ for (int il = 0; il < n_layer; ++il) {
800
+ struct ggml_tensor * inpSA = inpL;
801
+
802
+ struct ggml_tensor * cur;
803
+
804
+ // lctx.use_buf(ctx0, 0);
805
+
806
+ // norm
807
+ {
808
+ // cur shape [n_embd,N*n_batch,1,1]
809
+ cur = ggml_rms_norm(ctx0, inpL);
810
+ assert_shape_2d(cur, n_embd, N*n_batch);
811
+
812
+ // cur = attention_norm*cur
813
+ cur = ggml_mul(ctx0,
814
+ ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
815
+ cur);
816
+ assert_shape_2d(cur, n_embd, N*n_batch);
817
+ }
818
+
819
+ // self-attention
820
+ {
821
+ // compute Q and K and RoPE them
822
+ // wq shape [n_embd, n_embd, 1, 1]
823
+ // wk shape [n_embd, n_embd, 1, 1]
824
+ // Qcur shape [n_embd/n_head, n_head, N, n_batch]
825
+ // Kcur shape [n_embd/n_head, n_head, N, n_batch]
826
+ 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);
827
+ 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);
828
+ assert_shape_4d(Qcur, n_embd/n_head, n_head, N, n_batch);
829
+ assert_shape_4d(Kcur, n_embd/n_head, n_head, N, n_batch);
830
+
831
+ // store key and value to memory
832
+ {
833
+ // compute the transposed [N, n_embd] V matrix
834
+ // wv shape [n_embd, n_embd, 1, 1]
835
+ // Vcur shape [N, n_embd, n_batch, 1]
836
+ struct ggml_tensor * Vcur = ggml_cont(ctx0,
837
+ ggml_permute(ctx0,
838
+ ggml_reshape_3d(ctx0,
839
+ ggml_mul_mat(ctx0,
840
+ model->layers[il].wv,
841
+ cur),
842
+ n_embd, N, n_batch),
843
+ 1, 0, 2, 3));
844
+
845
+ assert_shape_3d(Vcur, N, n_embd, n_batch);
846
+
847
+ // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
848
+ // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
849
+ // k shape [n_embd * N, n_batch] == kv_self.k[:,n_past:n_past+N,:,il]
850
+ // v shape [N, n_embd, n_batch, 1] == kv_self.v[:,n_past:n_past+N,:,il]
851
+
852
+ /* {
853
+ 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));
854
+ struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
855
+ ( n_ctx)*ggml_element_size(kv_self.v),
856
+ (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
857
+
858
+ // important: storing RoPE-ed version of K in the KV cache!
859
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
860
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
861
+ } //*/
862
+
863
+ kc = ggml_set_2d(ctx0, kc,
864
+ ggml_reshape_2d(ctx0, Kcur, n_embd*N, n_batch),
865
+ ggml_element_size(kc)*n_embd*n_ctx,
866
+ (ggml_element_size(kc)*n_embd)*(il*n_batch*n_ctx + n_past));
867
+ vc = ggml_set_2d(ctx0, vc,
868
+ ggml_reshape_2d(ctx0, Vcur, N*n_embd, n_batch),
869
+ ggml_element_size(vc)*n_ctx*n_embd,
870
+ ggml_element_size(vc)*(n_past + il*n_embd*n_batch*n_ctx));
871
+
872
+ assert_shape_1d(kc, n_embd * n_ctx * n_batch * n_layer);
873
+ assert_shape_1d(vc, n_embd * n_ctx * n_batch * n_layer);
874
+ }
875
+
876
+ // Qcur shape [n_embd/n_head, n_head, N, n_batch]
877
+ // Q shape [n_embd/n_head, N, n_head, n_batch]
878
+ struct ggml_tensor * Q =
879
+ ggml_permute(ctx0,
880
+ Qcur,
881
+ 0, 2, 1, 3);
882
+ assert_shape_4d(Q, n_embd/n_head, N, n_head, n_batch);
883
+
884
+ // kv_self.k shape [n_embd * n_ctx * n_batch * n_layer]
885
+ // K shape [n_embd/n_head, n_past + N, n_head, n_batch]
886
+ struct ggml_tensor * K =
887
+ ggml_permute(ctx0,
888
+ ggml_reshape_4d(ctx0,
889
+ ggml_view_3d(ctx0,
890
+ kc,
891
+ n_embd,
892
+ (n_past + N),
893
+ n_batch,
894
+ n_embd*ggml_element_size(kc),
895
+ n_ctx*n_embd*ggml_element_size(kc),
896
+ il*n_batch*n_ctx*n_embd*ggml_element_size(kc)),
897
+ n_embd/n_head, n_head, n_past + N, n_batch),
898
+ 0, 2, 1, 3);
899
+ assert_shape_4d(K, n_embd/n_head, n_past + N, n_head, n_batch);
900
+
901
+ // K * Q
902
+ // KQ shape [n_past + N, N, n_head, n_batch]
903
+ struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
904
+ assert_shape_4d(KQ, n_past + N, N, n_head, n_batch);
905
+
906
+ // KQ_scaled = KQ / sqrt(n_embd/n_head)
907
+ // KQ_scaled shape [n_past + N, N, n_head, n_batch]
908
+ struct ggml_tensor * KQ_scaled =
909
+ ggml_scale(ctx0,
910
+ KQ,
911
+ ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
912
+ assert_shape_4d(KQ_scaled, n_past + N, N, n_head, n_batch);
913
+
914
+ // KQ_masked = mask_past(KQ_scaled)
915
+ // KQ_masked shape [n_past + N, N, n_head, n_batch]
916
+ struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
917
+ assert_shape_4d(KQ_masked, n_past + N, N, n_head, n_batch);
918
+
919
+ // KQ = soft_max(KQ_masked)
920
+ // KQ_soft_max shape [n_past + N, N, n_head, n_batch]
921
+ struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
922
+ assert_shape_4d(KQ_soft_max, n_past + N, N, n_head, n_batch);
923
+
924
+ // split cached V into n_head heads
925
+ // kv_self.v shape [n_ctx * n_embd * n_batch * n_layer]
926
+ // V shape [n_past + N, n_embd/n_head, n_head, n_batch] == kv_self.v[:(n_past+N),:,:,il]
927
+ struct ggml_tensor * V =
928
+ ggml_view_4d(ctx0, vc,
929
+ n_past + N, n_embd/n_head, n_head, n_batch,
930
+ ggml_element_size(vc)*n_ctx,
931
+ ggml_element_size(vc)*n_ctx*n_embd/n_head,
932
+ ggml_element_size(vc)*n_ctx*n_embd,
933
+ il*n_batch*n_ctx*n_embd*ggml_element_size(vc));
934
+ assert_shape_4d(V, n_past + N, n_embd/n_head, n_head, n_batch);
935
+
936
+ // KQV shape [n_embd/n_head, N, n_head, n_batch]
937
+ struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
938
+ assert_shape_4d(KQV, n_embd/n_head, N, n_head, n_batch);
939
+
940
+ // KQV_merged = KQV.permute(0, 2, 1, 3)
941
+ // KQV_merged shape [n_embd/n_head, n_head, N, n_batch]
942
+ struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
943
+ assert_shape_4d(KQV_merged, n_embd/n_head, n_head, N, n_batch);
944
+ // KQV_merged shape
945
+
946
+ // cur = KQV_merged.contiguous().view(n_embd, N)
947
+ // cur shape [n_embd,N*n_batch,1,1]
948
+ cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N*n_batch);
949
+ assert_shape_2d(cur, n_embd, N*n_batch);
950
+ // cur = ggml_cpy(ctx0,
951
+ // KQV_merged,
952
+ // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
953
+
954
+ // projection (no bias)
955
+ // cur shape [n_embd,N*n_batch,1,1]
956
+ cur = ggml_mul_mat(ctx0,
957
+ model->layers[il].wo,
958
+ cur);
959
+ assert_shape_2d(cur, n_embd, N*n_batch);
960
+ }
961
+
962
+ // lctx.use_buf(ctx0, 1);
963
+
964
+ // inpFF shape [n_embd,N*n_batch,1,1]
965
+ struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
966
+ assert_shape_2d(inpFF, n_embd, N*n_batch);
967
+
968
+ // feed-forward network
969
+ {
970
+ // norm
971
+ {
972
+ // cur shape [n_embd,N*n_batch,1,1]
973
+ cur = ggml_rms_norm(ctx0, inpFF);
974
+ assert_shape_2d(cur, n_embd, N*n_batch);
975
+
976
+ // cur = ffn_norm*cur
977
+ // cur shape [n_embd,N*n_batch,1,1]
978
+ cur = ggml_mul(ctx0,
979
+ ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
980
+ cur);
981
+ assert_shape_2d(cur, n_embd, N*n_batch);
982
+ }
983
+
984
+ // tmp shape [n_ff,N*n_batch,1,1]
985
+ struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
986
+ model->layers[il].w3,
987
+ cur);
988
+ assert_shape_2d(tmp, n_ff, N*n_batch);
989
+
990
+ // cur shape [n_ff,N*n_batch,1,1]
991
+ cur = ggml_mul_mat(ctx0,
992
+ model->layers[il].w1,
993
+ cur);
994
+ assert_shape_2d(cur, n_ff, N*n_batch);
995
+
996
+ // SILU activation
997
+ // cur shape [n_ff,N*n_batch,1,1]
998
+ cur = ggml_silu(ctx0, cur);
999
+ assert_shape_2d(cur, n_ff, N*n_batch);
1000
+
1001
+ // cur shape [n_ff,N*n_batch,1,1]
1002
+ cur = ggml_mul(ctx0, cur, tmp);
1003
+ assert_shape_2d(cur, n_ff, N*n_batch);
1004
+
1005
+ // cur shape [n_embd,N*n_batch,1,1]
1006
+ cur = ggml_mul_mat(ctx0,
1007
+ model->layers[il].w2,
1008
+ cur);
1009
+ assert_shape_2d(cur, n_embd, N*n_batch);
1010
+ }
1011
+
1012
+ // cur shape [n_embd,N*n_batch,1,1]
1013
+ cur = ggml_add(ctx0, cur, inpFF);
1014
+ assert_shape_2d(cur, n_embd, N*n_batch);
1015
+
1016
+ // input for next layer
1017
+ // inpL shape [n_embd,N*n_batch,1,1]
1018
+ inpL = cur;
1019
+ assert_shape_2d(inpL, n_embd, N*n_batch);
1020
+ }
1021
+
1022
+ // norm
1023
+ {
1024
+
1025
+ // inpL shape [n_embd,N*n_batch,1,1]
1026
+ inpL = ggml_rms_norm(ctx0, inpL);
1027
+ assert_shape_2d(inpL, n_embd, N*n_batch);
1028
+
1029
+ // inpL = norm*inpL
1030
+ // inpL shape [n_embd,N*n_batch,1,1]
1031
+ inpL = ggml_mul(ctx0,
1032
+ ggml_repeat(ctx0, model->norm, inpL),
1033
+ inpL);
1034
+
1035
+ assert_shape_2d(inpL, n_embd, N*n_batch);
1036
+
1037
+ //embeddings = inpL;
1038
+ }
1039
+
1040
+ // lm_head
1041
+ // inpL shape [n_vocab,N*n_batch,1,1]
1042
+ inpL = ggml_mul_mat(ctx0, model->output, inpL);
1043
+ assert_shape_2d(inpL, n_vocab, N*n_batch);
1044
+
1045
+ {
1046
+ // inpL shape [n_vocab,N,n_batch,1]
1047
+ inpL = ggml_reshape_3d(ctx0,
1048
+ inpL,
1049
+ n_vocab, N, n_batch);
1050
+ assert_shape_3d(inpL, n_vocab, N, n_batch);
1051
+ }
1052
+
1053
+ // run the computation
1054
+ ggml_build_forward_expand(gf, inpL);
1055
+
1056
+ return inpL;
1057
+ }
1058
+
1059
+
1060
+ struct ggml_tensor * forward_lora(
1061
+ struct llama_model_lora * model,
1062
+ struct llama_kv_cache * cache,
1063
+ struct ggml_context * ctx0,
1064
+ struct ggml_cgraph * gf,
1065
+ struct ggml_tensor * tokens_input,
1066
+ const int n_tokens,
1067
+ const int n_past) {
1068
+
1069
+ const int N = n_tokens;
1070
+
1071
+ struct llama_kv_cache& kv_self = *cache;
1072
+ const auto & hparams = model->hparams;
1073
+
1074
+ const int n_ctx = hparams.n_ctx;
1075
+ const int n_embd = hparams.n_embd;
1076
+ const int n_layer = hparams.n_layer;
1077
+ const int n_head = hparams.n_head;
1078
+ const int n_rot = hparams.n_rot;
1079
+
1080
+ struct ggml_tensor * tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
1081
+ memcpy(tokens->data, tokens_input->data, N*ggml_element_size(tokens));
1082
+
1083
+ struct ggml_tensor * kc = kv_self.k;
1084
+ struct ggml_tensor * vc = kv_self.v;
1085
+
1086
+ // inpL shape [n_embd,N,1,1]
1087
+ struct ggml_tensor * inpL = ggml_get_rows(ctx0, model->tok_embeddings, tokens);
1088
+ for (int il = 0; il < n_layer; ++il) {
1089
+ struct ggml_tensor * inpSA = inpL;
1090
+
1091
+ struct ggml_tensor * cur;
1092
+
1093
+ // norm
1094
+ {
1095
+ // cur shape [n_embd,N,1,1]
1096
+ cur = ggml_rms_norm(ctx0, inpL);
1097
+
1098
+ // cur = attention_norm*cur
1099
+ cur = ggml_mul(ctx0,
1100
+ ggml_repeat(ctx0, model->layers[il].attention_norm, cur),
1101
+ cur);
1102
+ }
1103
+
1104
+ // self-attention
1105
+ {
1106
+ // compute Q and K and RoPE them
1107
+ // wq shape [n_embd, n_embd, 1, 1]
1108
+ // wk shape [n_embd, n_embd, 1, 1]
1109
+ // Qcur shape [n_embd/n_head, n_head, N, 1]
1110
+ // Kcur shape [n_embd/n_head, n_head, N, 1]
1111
+ struct ggml_tensor * Qcur = ggml_rope(ctx0,
1112
+ ggml_reshape_3d(ctx0,
1113
+ ggml_mul_mat(ctx0,
1114
+ model->layers[il].wqa,
1115
+ ggml_mul_mat(ctx0,
1116
+ model->layers[il].wqb,
1117
+ cur)),
1118
+ n_embd/n_head, n_head, N),
1119
+ n_past, n_rot, 0);
1120
+ struct ggml_tensor * Kcur = ggml_rope(ctx0,
1121
+ ggml_reshape_3d(ctx0,
1122
+ ggml_mul_mat(ctx0,
1123
+ model->layers[il].wka,
1124
+ ggml_mul_mat(ctx0,
1125
+ model->layers[il].wkb,
1126
+ cur)),
1127
+ n_embd/n_head, n_head, N),
1128
+ n_past, n_rot, 0);
1129
+
1130
+ // store key and value to memory
1131
+ {
1132
+ // compute the transposed [N, n_embd] V matrix
1133
+ // wv shape [n_embd, n_embd, 1, 1]
1134
+ // Vcur shape [n_embd, N, 1, 1]
1135
+ struct ggml_tensor * Vcur = ggml_cont(ctx0,
1136
+ ggml_transpose(ctx0,
1137
+ ggml_reshape_2d(ctx0,
1138
+ ggml_mul_mat(ctx0,
1139
+ model->layers[il].wva,
1140
+ ggml_mul_mat(ctx0,
1141
+ model->layers[il].wvb,
1142
+ cur)),
1143
+ n_embd, N)));
1144
+
1145
+ // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
1146
+ // kv_self.v shape [n_embd * n_ctx * n_layer, 1]
1147
+ // k shape [n_embd * N, 1] == kv_self.k[:,n_past:n_past+N,il,0]
1148
+ // v shape [N, n_embd, 1, 1] == kv_self.v[:,n_past:n_past+N,il,0]
1149
+
1150
+ /* {
1151
+ 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));
1152
+ struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
1153
+ ( n_ctx)*ggml_element_size(kv_self.v),
1154
+ (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
1155
+
1156
+ // important: storing RoPE-ed version of K in the KV cache!
1157
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
1158
+ ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
1159
+ } //*/
1160
+
1161
+ 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));
1162
+ vc = ggml_set_2d(ctx0, vc, Vcur, ( n_ctx)*ggml_element_size(kv_self.v),
1163
+ (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
1164
+ }
1165
+
1166
+ // Qcur shape [n_embd/n_head, n_head, N, 1]
1167
+ // Q shape [n_embd/n_head, N, n_head, 1]
1168
+ struct ggml_tensor * Q =
1169
+ ggml_permute(ctx0,
1170
+ Qcur,
1171
+ 0, 2, 1, 3);
1172
+
1173
+ // kv_self.k shape [n_embd * n_ctx * n_layer, 1]
1174
+ // K shape [n_embd/n_head, n_past + N, n_head, 1]
1175
+ struct ggml_tensor * K =
1176
+ ggml_permute(ctx0,
1177
+ ggml_reshape_3d(ctx0,
1178
+ ggml_view_1d(ctx0, kc, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kc)*n_embd),
1179
+ n_embd/n_head, n_head, n_past + N),
1180
+ 0, 2, 1, 3);
1181
+
1182
+ // K * Q
1183
+ // KQ shape [n_past + N, N, n_head, 1]
1184
+ struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
1185
+
1186
+ // KQ_scaled = KQ / sqrt(n_embd/n_head)
1187
+ // KQ_scaled shape [n_past + N, N, n_head, 1]
1188
+ struct ggml_tensor * KQ_scaled =
1189
+ ggml_scale(ctx0,
1190
+ KQ,
1191
+ ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
1192
+
1193
+ // KQ_masked = mask_past(KQ_scaled)
1194
+ // KQ_masked shape [n_past + N, N, n_head, 1]
1195
+ struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
1196
+
1197
+ // KQ = soft_max(KQ_masked)
1198
+ // KQ_soft_max shape [n_past + N, N, n_head, 1]
1199
+ struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
1200
+
1201
+ // split cached V into n_head heads
1202
+ //// V shape [n_past + N, n_embd/n_head, n_head, 1]
1203
+ // V shape [n_past + N, n_embd/n_head, n_head, 1] == kv_self.v[:,:(n_past+N),il,1]
1204
+ struct ggml_tensor * V =
1205
+ ggml_view_3d(ctx0, vc,
1206
+ n_past + N, n_embd/n_head, n_head,
1207
+ n_ctx*ggml_element_size(vc),
1208
+ n_ctx*ggml_element_size(vc)*n_embd/n_head,
1209
+ il*n_ctx*ggml_element_size(vc)*n_embd);
1210
+
1211
+ // KQV shape [n_embd/n_head, N, n_head, 1]
1212
+ struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
1213
+
1214
+ // KQV_merged = KQV.permute(0, 2, 1, 3)
1215
+ // KQV_merged shape [n_embd/n_head, n_head, N, 1]
1216
+ struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
1217
+ // KQV_merged shape
1218
+
1219
+ // cur = KQV_merged.contiguous().view(n_embd, N)
1220
+ // cur shape [n_embd,N,1,1]
1221
+ cur = ggml_reshape_2d(ctx0, ggml_cont(ctx0, KQV_merged), n_embd, N);
1222
+ // cur = ggml_cpy(ctx0,
1223
+ // KQV_merged,
1224
+ // ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
1225
+
1226
+ // projection (no bias)
1227
+ // cur shape [n_embd,N,1,1]
1228
+ cur = ggml_mul_mat(ctx0,
1229
+ model->layers[il].woa,
1230
+ ggml_mul_mat(ctx0,
1231
+ model->layers[il].wob,
1232
+ cur));
1233
+ }
1234
+
1235
+ // inpFF shape [n_embd,N,1,1]
1236
+ struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
1237
+
1238
+ // feed-forward network
1239
+ {
1240
+ // norm
1241
+ {
1242
+ // cur shape [n_embd,N,1,1]
1243
+ cur = ggml_rms_norm(ctx0, inpFF);
1244
+
1245
+ // cur = ffn_norm*cur
1246
+ // cur shape [n_embd,N,1,1]
1247
+ cur = ggml_mul(ctx0,
1248
+ ggml_repeat(ctx0, model->layers[il].ffn_norm, cur),
1249
+ cur);
1250
+ }
1251
+
1252
+ // tmp shape [n_ff,N,1,1]
1253
+ struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
1254
+ model->layers[il].w3,
1255
+ cur);
1256
+
1257
+ // cur shape [n_ff,N,1,1]
1258
+ cur = ggml_mul_mat(ctx0,
1259
+ model->layers[il].w1,
1260
+ cur);
1261
+
1262
+ // SILU activation
1263
+ // cur shape [n_ff,N,1,1]
1264
+ cur = ggml_silu(ctx0, cur);
1265
+
1266
+ // cur shape [n_ff,N,1,1]
1267
+ cur = ggml_mul(ctx0, cur, tmp);
1268
+
1269
+ // cur shape [n_embd,N,1,1]
1270
+ cur = ggml_mul_mat(ctx0,
1271
+ model->layers[il].w2,
1272
+ cur);
1273
+ }
1274
+
1275
+ // cur shape [n_embd,N,1,1]
1276
+ cur = ggml_add(ctx0, cur, inpFF);
1277
+
1278
+ // input for next layer
1279
+ // inpL shape [n_embd,N,1,1]
1280
+ inpL = cur;
1281
+ }
1282
+
1283
+ // norm
1284
+ {
1285
+
1286
+ // inpL shape [n_embd,N,1,1]
1287
+ inpL = ggml_rms_norm(ctx0, inpL);
1288
+
1289
+ // inpL = norm*inpL
1290
+ // inpL shape [n_embd,N,1,1]
1291
+ inpL = ggml_mul(ctx0,
1292
+ ggml_repeat(ctx0, model->norm, inpL),
1293
+ inpL);
1294
+
1295
+ //embeddings = inpL;
1296
+ }
1297
+
1298
+
1299
+ // lm_head
1300
+ // inpL shape [n_vocab,N,1,1]
1301
+ inpL = ggml_mul_mat(ctx0,
1302
+ model->outputa,
1303
+ ggml_mul_mat(ctx0,
1304
+ model->outputb,
1305
+ inpL));
1306
+
1307
+ // ggml_set_scratch(ctx0, { 0, 0, nullptr, });
1308
+ // run the computation
1309
+ ggml_build_forward_expand(gf, inpL);
1310
+
1311
+ return inpL;
1312
+ }
1313
+
1314
+ void sample_softmax(struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
1315
+ assert(logits->n_dims == 2);
1316
+ assert(probs->n_dims == 2);
1317
+ assert(best_samples->n_dims == 1);
1318
+ assert(logits->ne[1] == best_samples->ne[0]);
1319
+ assert(logits->ne[0] == probs->ne[0]);
1320
+ assert(logits->ne[1] == probs->ne[1]);
1321
+ for (int i = 0; i < logits->ne[1]; ++i) {
1322
+ float max_logit = ggml_get_f32_1d(logits, i * logits->ne[0]);
1323
+ ggml_set_i32_1d(best_samples, i, 0);
1324
+ for (int k = 0; k < logits->ne[0]; ++k) {
1325
+ float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
1326
+ if (logit > max_logit) {
1327
+ max_logit = logit;
1328
+ ggml_set_i32_1d(best_samples, i, k);
1329
+ }
1330
+ }
1331
+ float psum = 0;
1332
+ for (int k = 0; k < logits->ne[0]; ++k) {
1333
+ float logit = ggml_get_f32_1d(logits, i * logits->ne[0] + k);
1334
+ float p = (logit == -INFINITY) ? 0 : expf(logit - max_logit);
1335
+ psum += p;
1336
+ ggml_set_f32_1d(probs, i * probs->ne[0] + k, p);
1337
+ }
1338
+ for (int k = 0; k < logits->ne[0]; ++k) {
1339
+ float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
1340
+ ggml_set_f32_1d(probs, i * probs->ne[0] + k, p / psum);
1341
+ }
1342
+ }
1343
+ }
1344
+
1345
+ void sample_softmax_batch(struct ggml_context * ctx, struct ggml_tensor * logits, struct ggml_tensor * probs, struct ggml_tensor * best_samples) {
1346
+ GGML_ASSERT(best_samples->n_dims == 2);
1347
+ GGML_ASSERT(logits->n_dims == 3);
1348
+ GGML_ASSERT(probs->n_dims == 3);
1349
+ int n_tokens = best_samples->ne[0];
1350
+ int n_batch = best_samples->ne[1];
1351
+ int n_vocab = logits->ne[0];
1352
+ GGML_ASSERT(n_tokens == logits->ne[1]);
1353
+ GGML_ASSERT(n_batch == logits->ne[2]);
1354
+ GGML_ASSERT(n_vocab == probs->ne[0]);
1355
+ GGML_ASSERT(n_tokens == probs->ne[1]);
1356
+ GGML_ASSERT(n_batch == probs->ne[2]);
1357
+
1358
+ for (int k = 0; k < n_batch; ++k) {
1359
+ struct ggml_tensor * best_samples_k = ggml_view_1d(ctx,
1360
+ best_samples,
1361
+ best_samples->ne[0],
1362
+ k*best_samples->nb[1]);
1363
+ struct ggml_tensor * logits_k = ggml_view_2d(ctx,
1364
+ logits,
1365
+ logits->ne[0],
1366
+ logits->ne[1],
1367
+ logits->nb[1],
1368
+ k*logits->nb[2]);
1369
+ struct ggml_tensor * probs_k = ggml_view_2d(ctx,
1370
+ probs,
1371
+ probs->ne[0],
1372
+ probs->ne[1],
1373
+ probs->nb[1],
1374
+ k*probs->nb[2]);
1375
+ sample_softmax(logits_k, probs_k, best_samples_k);
1376
+ }
1377
+ }
1378
+
1379
+ void print_row(struct ggml_tensor * probs, int i) {
1380
+ for (int k = 0; k < probs->ne[0]; ++k) {
1381
+ float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
1382
+ printf(" %.2f", p);
1383
+ }
1384
+ printf("\n");
1385
+ }
1386
+
1387
+ void print_matrix(struct ggml_tensor * probs) {
1388
+ assert(probs->n_dims == 2);
1389
+ for (int i = 0; i < probs->ne[1]; ++i) {
1390
+ for (int k = 0; k < probs->ne[0]; ++k) {
1391
+ float p = ggml_get_f32_1d(probs, i*probs->ne[0] + k);
1392
+ printf(" %.2f", p);
1393
+ }
1394
+ printf("\n");
1395
+ }
1396
+ }
1397
+
1398
+ void print_token(int token, int n_vocab) {
1399
+ for (int k = 0; k < token; ++k) {
1400
+ printf(" ");
1401
+ }
1402
+ printf("X");
1403
+ for (int k = token+1; k < n_vocab; ++k) {
1404
+ printf(" ");
1405
+ }
1406
+ printf("\n");
1407
+ }
1408
+
1409
+ void print_tokens(struct ggml_tensor * tokens, int n_vocab) {
1410
+ for (int i=0; i<tokens->ne[0]; ++i) {
1411
+ int token = ggml_get_i32_1d(tokens, i);
1412
+ print_token(token, n_vocab);
1413
+ }
1414
+ }
1415
+
1416
+ void get_example_targets(int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
1417
+ int n_tokens = tokens_input->ne[0];
1418
+ int n_vocab = targets->ne[0];
1419
+ float randomness = 0.0f;
1420
+ // ggml_set_zero(targets);
1421
+ ggml_set_f32(targets, -1.0f);
1422
+ ggml_set_i32_1d(tokens_input, 0, 0);
1423
+ for (int i=1; i<n_tokens+1; ++i) {
1424
+ float x = example_id + i * 3.14159f * 2.0f * 1.0f * 0.5f / n_tokens;
1425
+ float y = sinf(x);//*cosf(x*1.1f+1.0f);
1426
+ float z = (y+1.0f)*0.5f; // scale to [0..1]
1427
+ z += (frand()-0.5f)*(randomness/n_vocab);
1428
+ z = (z < 0.0f) ? 0.0f : (z > 1.0f) ? 1.0f : z; // clamp to [0..1]
1429
+ int token = std::max(1,std::min(1+(int)(z*(float)(n_vocab-1)), n_vocab-1));
1430
+ ggml_set_f32_1d(targets, (i-1)*n_vocab + token, +1.0f);
1431
+ if (i<n_tokens) {
1432
+ ggml_set_i32_1d(tokens_input, i, token);
1433
+ }
1434
+ }
1435
+ }
1436
+
1437
+ void get_example_targets_batch(struct ggml_context * ctx, int example_id, struct ggml_tensor * tokens_input, struct ggml_tensor * targets) {
1438
+ GGML_ASSERT(tokens_input->n_dims == 2);
1439
+ GGML_ASSERT( targets->n_dims == 3);
1440
+ int n_tokens = tokens_input->ne[0];
1441
+ int n_batch = tokens_input->ne[1];
1442
+ GGML_ASSERT(n_tokens == targets->ne[1]);
1443
+ GGML_ASSERT(n_batch == targets->ne[2]);
1444
+
1445
+ for (int k=0; k<n_batch; ++k) {
1446
+ struct ggml_tensor * tokens_input_k = ggml_view_1d(ctx,
1447
+ tokens_input,
1448
+ tokens_input->ne[0],
1449
+ k*tokens_input->nb[1]);
1450
+ struct ggml_tensor * targets_k = ggml_view_2d(ctx,
1451
+ targets,
1452
+ targets->ne[0],
1453
+ targets->ne[1],
1454
+ targets->nb[1],
1455
+ k*targets->nb[2]);
1456
+ get_example_targets(example_id*n_batch + k, tokens_input_k, targets_k);
1457
+ }
1458
+ }
1459
+
1460
+ void lshift_examples(struct ggml_tensor * tokens_input, struct ggml_tensor * targets, int n_shift) {
1461
+ int n_tokens = tokens_input->ne[0];
1462
+ int n_vocab = targets->ne[0];
1463
+ for (int i=0; i<n_tokens-n_shift; ++i) {
1464
+ ggml_set_i32_1d(tokens_input, i, ggml_get_i32_1d(tokens_input, i + n_shift));
1465
+ for (int k=0; k<n_vocab; ++k) {
1466
+ ggml_set_f32_1d(targets, i*n_vocab + k, ggml_get_f32_1d(targets, (i + n_shift)*n_vocab + k));
1467
+ }
1468
+ }
1469
+ }
1470
+
1471
+ struct ggml_tensor * square_error_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b) {
1472
+ // todo: instead of a-b: a[1:]-b[:-1]
1473
+ return ggml_sum(ctx, ggml_sqr(ctx, ggml_sub(ctx, a, b)));
1474
+ }
1475
+
1476
+ struct ggml_tensor * cross_entropy_loss(struct ggml_context * ctx, struct ggml_tensor * a, struct ggml_tensor * b) {
1477
+ const float eps = 1e-3f;
1478
+ return
1479
+ ggml_sum(ctx,
1480
+ ggml_neg(ctx,
1481
+ ggml_sum_rows(ctx,
1482
+ ggml_mul(ctx,
1483
+ ggml_soft_max(ctx, a),
1484
+ ggml_log(ctx,
1485
+ ggml_add1(ctx,
1486
+ ggml_soft_max(ctx, b),
1487
+ ggml_new_f32(ctx, eps)))))));
1488
+ }
1489
+
1490
+ int main(int argc, char ** argv) {
1491
+ if (argc < 1) {
1492
+ fprintf(stderr, "usage: %s\n", argv[0]);
1493
+
1494
+ return 1;
1495
+ }
1496
+
1497
+ struct ggml_init_params lcparams;
1498
+ lcparams.mem_size = 1024ll*1024ll*1024ll;
1499
+ lcparams.mem_buffer = NULL;
1500
+ lcparams.no_alloc = false;
1501
+
1502
+ struct llama_model model;
1503
+ model.hparams.n_vocab = 8;
1504
+ model.hparams.n_ctx = 8;
1505
+ model.hparams.n_embd = 32;
1506
+ model.hparams.n_mult = 2;
1507
+ model.hparams.n_head = 8;
1508
+ model.hparams.n_layer = 1;
1509
+ model.hparams.n_rot = std::min(16u, model.hparams.n_embd / model.hparams.n_head);
1510
+
1511
+ // model.hparams.n_embd = 32;
1512
+ // model.hparams.n_mult = 2;
1513
+ // model.hparams.n_head = 4;
1514
+ // model.hparams.n_layer = 8;
1515
+ // model.hparams.n_rot = 8;
1516
+
1517
+ model.ctx = ggml_init(lcparams);
1518
+ printf("init model\n");
1519
+ init_model(&model);
1520
+ set_param_model(&model);
1521
+
1522
+ randomize_model(&model, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
1523
+
1524
+ /*
1525
+ struct llama_model_lora model_lora;
1526
+ // model.hparams.n_vocab = 6;
1527
+ // model.hparams.n_ctx = 64;
1528
+ // model.hparams.n_embd = 128;
1529
+ // model.hparams.n_mult = 2;
1530
+ // model.hparams.n_head = 8;
1531
+ // model.hparams.n_layer = 6;
1532
+ // model.hparams.n_rot = model.hparams.n_embd / model.hparams.n_head;
1533
+
1534
+ model_lora.hparams.n_vocab = 16;
1535
+ model_lora.hparams.n_ctx = 32;
1536
+ model_lora.hparams.n_embd = 256;
1537
+ model_lora.hparams.n_mult = 2;
1538
+ model_lora.hparams.n_head = 16;
1539
+ model_lora.hparams.n_layer = 1;
1540
+ model_lora.hparams.n_lora = 64;
1541
+ model_lora.hparams.n_rot = MIN(16, model_lora.hparams.n_embd / model_lora.hparams.n_head);
1542
+ // model.hparams.n_rot = (model.hparams.n_embd / model.hparams.n_head) / 2;
1543
+
1544
+ // model.hparams.n_embd = 32;
1545
+ // model.hparams.n_mult = 2;
1546
+ // model.hparams.n_head = 4;
1547
+ // model.hparams.n_layer = 8;
1548
+ // model.hparams.n_rot = 8;
1549
+
1550
+ model_lora.ctx = ggml_init(lcparams);
1551
+ printf("init model_lora\n");
1552
+ init_model_lora(&model_lora);
1553
+ set_param_model_lora(&model_lora);
1554
+
1555
+ randomize_model_lora(&model_lora, 1337, 0.0f, 1.0f, -1.0f, +1.0f);
1556
+ */
1557
+ int n_batch = 8;
1558
+ // key + value cache for the self attention
1559
+ struct llama_kv_cache kv_self;
1560
+ printf("init_kv_cache\n");
1561
+ kv_self.ctx = model.ctx;
1562
+ init_kv_cache(&kv_self, &model, n_batch);
1563
+ //init_kv_cache_lora(&kv_self, &model_lora);
1564
+
1565
+ size_t compute_size = 1024ll*1024ll*1024ll;
1566
+ uint8_t * compute_addr = new uint8_t[compute_size];
1567
+
1568
+ int n_examples = 256;
1569
+ int n_tokens = model.hparams.n_ctx;
1570
+ int n_vocab = model.hparams.n_vocab;
1571
+
1572
+ for (int ex=0; ex<n_examples; ++ex) {
1573
+ struct ggml_init_params params = {
1574
+ /*.mem_size =*/ compute_size,
1575
+ /*.mem_buffer =*/ compute_addr,
1576
+ /*.no_alloc =*/ false,
1577
+ };
1578
+
1579
+ struct ggml_context * ctx0 = ggml_init(params);
1580
+
1581
+ struct ggml_tensor * after_opt_best_samples = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
1582
+ struct ggml_tensor * after_opt_probs = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
1583
+ struct ggml_tensor * tokens_input = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_tokens, n_batch);
1584
+ struct ggml_tensor * targets = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_vocab, n_tokens, n_batch);
1585
+
1586
+ int n_past = 0;
1587
+
1588
+ ggml_cgraph gf = {};
1589
+ gf.n_threads = 1;
1590
+
1591
+ get_example_targets_batch(ctx0, 64*ex+0, tokens_input, targets);
1592
+
1593
+ struct ggml_tensor * logits = forward_batch(&model, &kv_self, ctx0, &gf, tokens_input, n_tokens, n_past, n_batch);
1594
+ // struct ggml_tensor * e = cross_entropy_loss(ctx0, targets, logits);
1595
+ struct ggml_tensor * e = square_error_loss(ctx0, targets, logits);
1596
+
1597
+ ggml_build_forward_expand(&gf, e);
1598
+ ggml_graph_compute(ctx0, &gf);
1599
+
1600
+ float error_before_opt = ggml_get_f32_1d(e, 0);
1601
+
1602
+ struct ggml_opt_params opt_params_adam = ggml_opt_default_params(GGML_OPT_ADAM);
1603
+ struct ggml_opt_params opt_params_lbfgs = ggml_opt_default_params(GGML_OPT_LBFGS);
1604
+ opt_params_adam.print_forward_graph = false;
1605
+ opt_params_adam.print_backward_graph = false;
1606
+ opt_params_lbfgs.print_forward_graph = false;
1607
+ opt_params_lbfgs.print_backward_graph = false;
1608
+ opt_params_adam.adam.n_iter = 16;
1609
+ opt_params_lbfgs.lbfgs.n_iter = 16;
1610
+ // ggml_opt(ctx0, opt_params_adam, e);
1611
+ ggml_opt(ctx0, opt_params_lbfgs, e);
1612
+ //
1613
+ ggml_build_forward_expand(&gf, e);
1614
+ ggml_graph_compute(ctx0, &gf);
1615
+
1616
+ float error_after_opt = ggml_get_f32_1d(e, 0);
1617
+
1618
+ if (ex % 8 == 0) {
1619
+ printf("Example %d\n", (ex+1));
1620
+ printf("error_before_opt: %.2f\n", error_before_opt);
1621
+ printf("error_after_opt: %.2f\n", error_after_opt);
1622
+ }
1623
+
1624
+ if (ex % 64 == 0) {
1625
+ sample_softmax_batch(ctx0, logits, after_opt_probs, after_opt_best_samples);
1626
+ // printf("probabilities after optimization:\n");
1627
+ // print_matrix(after_opt_probs);
1628
+ printf("best samples after optimization:\n");
1629
+ print_tokens(after_opt_best_samples, n_vocab);
1630
+ }
1631
+
1632
+ ggml_free(ctx0);
1633
+ }
1634
+
1635
+ {
1636
+ int n_gen = 128;
1637
+ int sample_ctx = n_tokens-n_tokens/8;
1638
+
1639
+ printf("Generating %d tokens.\n", n_gen);
1640
+
1641
+ struct ggml_tensor * tokens_input = ggml_new_tensor_1d(model.ctx, GGML_TYPE_I32, n_tokens);
1642
+ struct ggml_tensor * targets = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, n_vocab, n_tokens);
1643
+
1644
+ get_example_targets(137, tokens_input, targets);
1645
+ for (int i=sample_ctx; i<n_tokens; ++i) {
1646
+ ggml_set_i32_1d(tokens_input, i, n_vocab/2);
1647
+ }
1648
+
1649
+ for (int i=0; i<sample_ctx-1; ++i) {
1650
+ print_token(ggml_get_i32_1d(tokens_input, i), n_vocab);
1651
+ }
1652
+ printf("---\n");
1653
+ for (int i=0; i<n_gen; ++i) {
1654
+ struct ggml_init_params params = {
1655
+ /*.mem_size =*/ compute_size,
1656
+ /*.mem_buffer =*/ compute_addr,
1657
+ /*.no_alloc =*/ false,
1658
+ };
1659
+ struct ggml_context * ctx0 = ggml_init(params);
1660
+
1661
+ ggml_cgraph gf = {};
1662
+ gf.n_threads = 1;
1663
+
1664
+ int n_past = 0;
1665
+ struct ggml_tensor * logits = forward(&model, &kv_self, ctx0, &gf, tokens_input, sample_ctx, n_past);
1666
+
1667
+ ggml_build_forward_expand(&gf, logits);
1668
+ ggml_graph_compute(ctx0, &gf);
1669
+
1670
+ struct ggml_tensor * best_samples = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, sample_ctx);
1671
+ struct ggml_tensor * probs = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_vocab, sample_ctx);
1672
+
1673
+ sample_softmax(logits, probs, best_samples);
1674
+
1675
+ // int sample_at = n_tokens-1;
1676
+ int token = ggml_get_i32_1d(best_samples, sample_ctx-1);
1677
+
1678
+ // print_row(probs, sample_at);
1679
+ print_token(token, n_vocab);
1680
+
1681
+ lshift_examples(tokens_input, targets, 1);
1682
+ ggml_set_i32_1d(tokens_input, 0, 0);
1683
+ ggml_set_i32_1d(tokens_input, sample_ctx-1, token);
1684
+
1685
+ ggml_free(ctx0);
1686
+ }
1687
+ }
1688
+
1689
+ print_matrix(model.tok_embeddings);
1690
+
1691
+ printf("done\n");
1692
+ // ggml_free(kv_self.ctx);
1693
+ // ggml_free(model_lora.ctx);
1694
+ ggml_free(model.ctx);
1695
+ return 0;
1696
+ }
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,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #if defined(_MSC_VER)
20
+ #pragma warning(disable: 4244 4267) // possible loss of data
21
+ #endif
22
+
23
+ float tensor_sum_elements(const ggml_tensor * tensor) {
24
+ float sum = 0;
25
+ if (tensor->type==GGML_TYPE_F32) {
26
+ for (int j = 0; j < tensor->ne[1]; j++) {
27
+ for (int k = 0; k < tensor->ne[0]; k++) {
28
+ sum += ((float *) tensor->data)[j*tensor->ne[0]+k];
29
+ }
30
+ }
31
+ }
32
+ return sum;
33
+ }
34
+
35
+ void tensor_dump(const ggml_tensor * tensor, const char * name) {
36
+ printf("%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi) - ", name,
37
+ tensor->type, ggml_type_name(tensor->type),
38
+ tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->nb[0], tensor->nb[1], tensor->nb[2]);
39
+ float sum = tensor_sum_elements(tensor);
40
+ printf("Sum of tensor %s is %6.2f\n", name, sum);
41
+ }
42
+
43
+ #define TENSOR_DUMP(tensor) tensor_dump(tensor, #tensor)
44
+
45
+ struct benchmark_params_struct {
46
+ int32_t n_threads = 1;
47
+ int32_t n_iterations = 10;
48
+ };
49
+
50
+ void print_usage(int /*argc*/, char ** argv, struct benchmark_params_struct params) {
51
+ fprintf(stderr, "usage: %s [options]\n", argv[0]);
52
+ fprintf(stderr, "\n");
53
+ fprintf(stderr, "options:\n");
54
+ fprintf(stderr, " -h, --help show this help message and exit\n");
55
+ fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
56
+ fprintf(stderr, " -i N, --iter N number of iterations to use during computation (default: %d)\n", params.n_iterations);
57
+ fprintf(stderr, "\n");
58
+ }
59
+
60
+ int main(int argc, char ** argv) {
61
+ struct benchmark_params_struct benchmark_params;
62
+
63
+ bool invalid_param = false;
64
+ std::string arg;
65
+ for (int i = 1; i < argc; i++) {
66
+ arg = argv[i];
67
+
68
+ if (arg == "-t" || arg == "--threads") {
69
+ if (++i >= argc) {
70
+ invalid_param = true;
71
+ break;
72
+ }
73
+ benchmark_params.n_threads = std::stoi(argv[i]);
74
+ } else if (arg == "-i" || arg == "--iter") {
75
+ if (++i >= argc) {
76
+ invalid_param = true;
77
+ break;
78
+ }
79
+ benchmark_params.n_iterations = std::stoi(argv[i]);
80
+ } else if (arg == "-h" || arg == "--help") {
81
+ print_usage(argc, argv, benchmark_params);
82
+ exit(0);
83
+ }
84
+ }
85
+ if (invalid_param) {
86
+ fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
87
+ print_usage(argc, argv, benchmark_params);
88
+ exit(1);
89
+ }
90
+
91
+ fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
92
+ printf("Starting Test\n");
93
+
94
+ // create the ggml context
95
+ struct ggml_context * ctx;
96
+ //const int sizex = 4096;
97
+ //const int sizey = 11008;
98
+
99
+ #undef VERBOSE_DEBUGGING
100
+ #ifndef VERBOSE_DEBUGGING
101
+ const int sizey = 4096;
102
+ const int sizex = 11008;
103
+ const int sizez = 128;
104
+ #else
105
+ /* Working - let's increase size */
106
+ const int sizey = 1;
107
+ const int sizex = (8*32);
108
+ const int sizez = 1;
109
+
110
+ /*const int sizey = 1;
111
+ const int sizex = 3*(8*32);
112
+ const int sizez = 1;*/
113
+ #endif
114
+
115
+ //printf("Memsize required = %i\n", sizex*sizex);
116
+
117
+ size_t ctx_size = 0;
118
+ ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32);
119
+ ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32);
120
+ ctx_size += sizex*sizez*ggml_type_sizef(GGML_TYPE_F32);
121
+ ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_Q4_0);
122
+ ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_Q4_0);
123
+ ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32); // BLAS
124
+ ctx_size += sizex*sizey*ggml_type_sizef(GGML_TYPE_F32); // BLAS
125
+ ctx_size += 1024*1024*16;
126
+
127
+ printf("Allocating Memory of size %zi bytes, %zi MB\n",ctx_size, (ctx_size/1024/1024));
128
+
129
+ struct ggml_init_params params = {
130
+ /*.mem_size =*/ ctx_size,
131
+ /*.mem_buffer =*/ NULL,
132
+ /* no_alloc =*/ 0
133
+ };
134
+
135
+ ctx = ggml_init(params);
136
+ if (!ctx) {
137
+ fprintf(stderr, "%s: ggml_init() failed\n", __func__);
138
+ return 1;
139
+ }
140
+
141
+
142
+ printf("Creating new tensors\n");
143
+ // printf("Creating new tensor m1\n");
144
+ struct ggml_tensor * m11 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizey);
145
+ ggml_set_f32(m11, 1.0f);
146
+
147
+ // printf("Creating new tensor m1\n");
148
+ struct ggml_tensor * m12 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizey);
149
+ ggml_set_f32(m12, 1.5f);
150
+
151
+ // printf("Creating new tensor m2\n");
152
+ struct ggml_tensor * m2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizez);
153
+ ggml_set_f32(m2, 2.0f);
154
+
155
+ printf("\n------ Test 1 - Matrix Mult via F32 code ------------------------------------------------------------------------------\n");
156
+ // printf("Creating new tensor m11xm2\n");
157
+ struct ggml_tensor * m11xm2 = ggml_mul_mat(ctx, m11, m2);
158
+
159
+ // printf("Creating compute graph\n");
160
+ struct ggml_cgraph gf = ggml_build_forward(m11xm2);
161
+
162
+ gf.n_threads=benchmark_params.n_threads;
163
+ printf("cgraph->n_threads=%i\n",gf.n_threads);
164
+
165
+ TENSOR_DUMP(m11);
166
+ TENSOR_DUMP(m2);
167
+
168
+ ggml_graph_compute(ctx, &gf);
169
+
170
+ TENSOR_DUMP(gf.nodes[0]);
171
+
172
+ printf("\n------ Test 2 - Matrix Mult via Q4_0 code ------------------------------------------------------------------------------\n");
173
+
174
+ int32_t nelements = sizex*sizey;
175
+ int32_t ne[2] = { sizex, sizey };
176
+
177
+ std::vector<int64_t> hist_cur(1 << 4, 0);
178
+
179
+ // Set up a the benchmark matrices
180
+ // printf("Creating new tensor q11 & Running quantize\n");
181
+ struct ggml_tensor * q11 = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, sizex, sizey);
182
+ ggml_quantize_q4_0((const float *) m11->data, q11->data, nelements, ne[0], hist_cur.data());
183
+
184
+ // Set up a the compute graph
185
+ // printf("Creating new tensor q31\n");
186
+ struct ggml_tensor * q31 = ggml_mul_mat(ctx, q11, m2);
187
+
188
+ // printf("Creating compute graph\n");
189
+ struct ggml_cgraph gf31 = ggml_build_forward(q31);
190
+ gf31.n_threads=benchmark_params.n_threads;
191
+
192
+ // Set up a second graph computation to make sure we override the CPU cache lines
193
+ // printf("Creating new tensor q12 & Running quantize\n");
194
+ struct ggml_tensor * q12 = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, sizex, sizey);
195
+ ggml_quantize_q4_0((const float *) m12->data, q12->data, nelements, ne[0], hist_cur.data());
196
+
197
+ // printf("Creating new tensor q32\n");
198
+ struct ggml_tensor * q32 = ggml_mul_mat(ctx, q12, m2);
199
+
200
+ //printf("Creating compute graph\n");
201
+ struct ggml_cgraph gf32 = ggml_build_forward(q32);
202
+ gf32.n_threads=benchmark_params.n_threads;
203
+ printf("cgraph->n_threads=%i\n",gf31.n_threads);
204
+
205
+ const int dimx = sizex;
206
+ const int dimy = sizey;
207
+ const int dimz = sizez;
208
+ long long int flops_per_dot_product = dimy + dimy;
209
+ long long int flops_per_matrix = flops_per_dot_product * dimx * dimz; ;
210
+ 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);
211
+
212
+
213
+ // Let's use the F32 result from above as a reference for the q4_0 multiplication
214
+ float sum_of_F32_reference = tensor_sum_elements(gf.nodes[0]);
215
+
216
+ printf("Iteration;NThreads; SizeX; SizeY; SizeZ; Required_FLOPS; Elapsed_u_Seconds; gigaFLOPS\n");
217
+ printf("=====================================================================================\n");
218
+
219
+ double gflops_sum = 0;
220
+ for (int i=0;i<benchmark_params.n_iterations ;i++) {
221
+
222
+ long long int start = ggml_time_us();
223
+ //printf("Running ggml_graph_compute\n");
224
+ ggml_graph_compute(ctx, &gf31);
225
+ long long int stop = ggml_time_us();
226
+ long long int usec = stop-start;
227
+ double gflops = (double)(flops_per_matrix)/usec/1000.0;
228
+ gflops_sum += gflops;
229
+ printf("%9i;%8i;%6i;%6i;%6i;%15lli;%18lli;%10.2f\n",
230
+ i,
231
+ gf31.n_threads,
232
+ sizex, sizey, sizez, flops_per_matrix,
233
+ usec,gflops);
234
+
235
+ #ifdef VERBOSE_DEBUGGING
236
+ TENSOR_DUMP("res",gf31.nodes[0])
237
+ #endif
238
+
239
+ // Check that the matrix multiplication result is in the right ballpark
240
+ // We cannot use the exact value from the F32 multiplication because the quantizuation will be slightly different
241
+ float sum_of_Q4_result = tensor_sum_elements(gf31.nodes[0]);
242
+ float delta = abs(sum_of_Q4_result - sum_of_F32_reference);
243
+ float allowed_delta = (sum_of_F32_reference) / 1000 / 1000; // Let's accept an epsilon of 10^-6
244
+
245
+ if (delta > allowed_delta) {
246
+ printf("\nABORT - ERROR in Matrix Multiplication result - expected %6.2f, got %6.2f (delta %6.2f > allowed_delta %6.2f)\n",
247
+ sum_of_F32_reference,
248
+ sum_of_Q4_result,
249
+ delta,
250
+ allowed_delta
251
+ );
252
+ exit(0);
253
+ }
254
+
255
+ // Running a different graph computation to make sure we override the CPU cache lines
256
+ ggml_graph_compute(ctx, &gf32);
257
+ }
258
+ printf("\n");
259
+ printf("Average%78.2f\n",gflops_sum/((double)benchmark_params.n_iterations));
260
+ printf("=====================================================================================\n");
261
+ }
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-vicuna.sh ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ set -e
4
+
5
+ cd "$(dirname "$0")/.." || exit
6
+
7
+ MODEL="${MODEL:-./models/ggml-vic13b-uncensored-q5_0.bin}"
8
+ PROMPT_TEMPLATE=${PROMPT_TEMPLATE:-./prompts/chat.txt}
9
+ USER_NAME="### Human"
10
+ AI_NAME="### Assistant"
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
+ ./bin/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 "### Human:" \
40
+ --in-prefix ' ' \
41
+ "$@"
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,950 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #if defined(_MSC_VER)
32
+ #pragma warning(disable: 4244 4267) // possible loss of data
33
+ #endif
34
+
35
+ int32_t get_num_physical_cores() {
36
+ #ifdef __linux__
37
+ // enumerate the set of thread siblings, num entries is num cores
38
+ std::unordered_set<std::string> siblings;
39
+ for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
40
+ std::ifstream thread_siblings("/sys/devices/system/cpu"
41
+ + std::to_string(cpu) + "/topology/thread_siblings");
42
+ if (!thread_siblings.is_open()) {
43
+ break; // no more cpus
44
+ }
45
+ std::string line;
46
+ if (std::getline(thread_siblings, line)) {
47
+ siblings.insert(line);
48
+ }
49
+ }
50
+ if (siblings.size() > 0) {
51
+ return static_cast<int32_t>(siblings.size());
52
+ }
53
+ #elif defined(__APPLE__) && defined(__MACH__)
54
+ int32_t num_physical_cores;
55
+ size_t len = sizeof(num_physical_cores);
56
+ int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
57
+ if (result == 0) {
58
+ return num_physical_cores;
59
+ }
60
+ result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
61
+ if (result == 0) {
62
+ return num_physical_cores;
63
+ }
64
+ #elif defined(_WIN32)
65
+ //TODO: Implement
66
+ #endif
67
+ unsigned int n_threads = std::thread::hardware_concurrency();
68
+ return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
69
+ }
70
+
71
+ void process_escapes(std::string& input) {
72
+ std::size_t input_len = input.length();
73
+ std::size_t output_idx = 0;
74
+
75
+ for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
76
+ if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
77
+ switch (input[++input_idx]) {
78
+ case 'n': input[output_idx++] = '\n'; break;
79
+ case 'r': input[output_idx++] = '\r'; break;
80
+ case 't': input[output_idx++] = '\t'; break;
81
+ case '\'': input[output_idx++] = '\''; break;
82
+ case '\"': input[output_idx++] = '\"'; break;
83
+ case '\\': input[output_idx++] = '\\'; break;
84
+ default: input[output_idx++] = '\\';
85
+ input[output_idx++] = input[input_idx]; break;
86
+ }
87
+ } else {
88
+ input[output_idx++] = input[input_idx];
89
+ }
90
+ }
91
+
92
+ input.resize(output_idx);
93
+ }
94
+
95
+ bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
96
+ bool invalid_param = false;
97
+ bool escape_prompt = false;
98
+ std::string arg;
99
+ gpt_params default_params;
100
+ const std::string arg_prefix = "--";
101
+
102
+ for (int i = 1; i < argc; i++) {
103
+ arg = argv[i];
104
+ if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
105
+ std::replace(arg.begin(), arg.end(), '_', '-');
106
+ }
107
+
108
+ if (arg == "-s" || arg == "--seed") {
109
+ #if defined(GGML_USE_CUBLAS)
110
+ fprintf(stderr, "WARNING: when using cuBLAS generation results are NOT guaranteed to be reproducible.\n");
111
+ #endif
112
+ if (++i >= argc) {
113
+ invalid_param = true;
114
+ break;
115
+ }
116
+ params.seed = std::stoi(argv[i]);
117
+ } else if (arg == "-t" || arg == "--threads") {
118
+ if (++i >= argc) {
119
+ invalid_param = true;
120
+ break;
121
+ }
122
+ params.n_threads = std::stoi(argv[i]);
123
+ } else if (arg == "-p" || arg == "--prompt") {
124
+ if (++i >= argc) {
125
+ invalid_param = true;
126
+ break;
127
+ }
128
+ params.prompt = argv[i];
129
+ } else if (arg == "-e") {
130
+ escape_prompt = true;
131
+ } else if (arg == "--prompt-cache") {
132
+ if (++i >= argc) {
133
+ invalid_param = true;
134
+ break;
135
+ }
136
+ params.path_prompt_cache = argv[i];
137
+ } else if (arg == "--prompt-cache-all") {
138
+ params.prompt_cache_all = true;
139
+ } else if (arg == "--prompt-cache-ro") {
140
+ params.prompt_cache_ro = true;
141
+ } else if (arg == "-f" || arg == "--file") {
142
+ if (++i >= argc) {
143
+ invalid_param = true;
144
+ break;
145
+ }
146
+ std::ifstream file(argv[i]);
147
+ if (!file) {
148
+ fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
149
+ invalid_param = true;
150
+ break;
151
+ }
152
+ std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
153
+ if (params.prompt.back() == '\n') {
154
+ params.prompt.pop_back();
155
+ }
156
+ } else if (arg == "-n" || arg == "--n-predict") {
157
+ if (++i >= argc) {
158
+ invalid_param = true;
159
+ break;
160
+ }
161
+ params.n_predict = std::stoi(argv[i]);
162
+ } else if (arg == "--top-k") {
163
+ if (++i >= argc) {
164
+ invalid_param = true;
165
+ break;
166
+ }
167
+ params.top_k = std::stoi(argv[i]);
168
+ } else if (arg == "-c" || arg == "--ctx-size") {
169
+ if (++i >= argc) {
170
+ invalid_param = true;
171
+ break;
172
+ }
173
+ params.n_ctx = std::stoi(argv[i]);
174
+ } else if (arg == "--memory-f32") {
175
+ params.memory_f16 = false;
176
+ } else if (arg == "--top-p") {
177
+ if (++i >= argc) {
178
+ invalid_param = true;
179
+ break;
180
+ }
181
+ params.top_p = std::stof(argv[i]);
182
+ } else if (arg == "--temp") {
183
+ if (++i >= argc) {
184
+ invalid_param = true;
185
+ break;
186
+ }
187
+ params.temp = std::stof(argv[i]);
188
+ } else if (arg == "--tfs") {
189
+ if (++i >= argc) {
190
+ invalid_param = true;
191
+ break;
192
+ }
193
+ params.tfs_z = std::stof(argv[i]);
194
+ } else if (arg == "--typical") {
195
+ if (++i >= argc) {
196
+ invalid_param = true;
197
+ break;
198
+ }
199
+ params.typical_p = std::stof(argv[i]);
200
+ } else if (arg == "--repeat-last-n") {
201
+ if (++i >= argc) {
202
+ invalid_param = true;
203
+ break;
204
+ }
205
+ params.repeat_last_n = std::stoi(argv[i]);
206
+ } else if (arg == "--repeat-penalty") {
207
+ if (++i >= argc) {
208
+ invalid_param = true;
209
+ break;
210
+ }
211
+ params.repeat_penalty = std::stof(argv[i]);
212
+ } else if (arg == "--frequency-penalty") {
213
+ if (++i >= argc) {
214
+ invalid_param = true;
215
+ break;
216
+ }
217
+ params.frequency_penalty = std::stof(argv[i]);
218
+ } else if (arg == "--presence-penalty") {
219
+ if (++i >= argc) {
220
+ invalid_param = true;
221
+ break;
222
+ }
223
+ params.presence_penalty = std::stof(argv[i]);
224
+ } else if (arg == "--mirostat") {
225
+ if (++i >= argc) {
226
+ invalid_param = true;
227
+ break;
228
+ }
229
+ params.mirostat = std::stoi(argv[i]);
230
+ } else if (arg == "--mirostat-lr") {
231
+ if (++i >= argc) {
232
+ invalid_param = true;
233
+ break;
234
+ }
235
+ params.mirostat_eta = std::stof(argv[i]);
236
+ } else if (arg == "--mirostat-ent") {
237
+ if (++i >= argc) {
238
+ invalid_param = true;
239
+ break;
240
+ }
241
+ params.mirostat_tau = std::stof(argv[i]);
242
+ } else if (arg == "-b" || arg == "--batch-size") {
243
+ if (++i >= argc) {
244
+ invalid_param = true;
245
+ break;
246
+ }
247
+ params.n_batch = std::stoi(argv[i]);
248
+ params.n_batch = std::min(512, params.n_batch);
249
+ } else if (arg == "--keep") {
250
+ if (++i >= argc) {
251
+ invalid_param = true;
252
+ break;
253
+ }
254
+ params.n_keep = std::stoi(argv[i]);
255
+ } else if (arg == "-m" || arg == "--model") {
256
+ if (++i >= argc) {
257
+ invalid_param = true;
258
+ break;
259
+ }
260
+ params.model = argv[i];
261
+ } else if (arg == "-a" || arg == "--alias") {
262
+ if (++i >= argc) {
263
+ invalid_param = true;
264
+ break;
265
+ }
266
+ params.model_alias = argv[i];
267
+ } else if (arg == "--lora") {
268
+ if (++i >= argc) {
269
+ invalid_param = true;
270
+ break;
271
+ }
272
+ params.lora_adapter = argv[i];
273
+ params.use_mmap = false;
274
+ } else if (arg == "--lora-base") {
275
+ if (++i >= argc) {
276
+ invalid_param = true;
277
+ break;
278
+ }
279
+ params.lora_base = argv[i];
280
+ } else if (arg == "-i" || arg == "--interactive") {
281
+ params.interactive = true;
282
+ } else if (arg == "--embedding") {
283
+ params.embedding = true;
284
+ } else if (arg == "--interactive-first") {
285
+ params.interactive_first = true;
286
+ } else if (arg == "-ins" || arg == "--instruct") {
287
+ params.instruct = true;
288
+ } else if (arg == "--multiline-input") {
289
+ params.multiline_input = true;
290
+ } else if (arg == "--color") {
291
+ params.use_color = true;
292
+ } else if (arg == "--mlock") {
293
+ params.use_mlock = true;
294
+ } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
295
+ if (++i >= argc) {
296
+ invalid_param = true;
297
+ break;
298
+ }
299
+ #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
300
+ params.n_gpu_layers = std::stoi(argv[i]);
301
+ #else
302
+ fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
303
+ fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
304
+ #endif
305
+ } else if (arg == "--main-gpu" || arg == "-mg") {
306
+ if (++i >= argc) {
307
+ invalid_param = true;
308
+ break;
309
+ }
310
+ #ifdef GGML_USE_CUBLAS
311
+ params.main_gpu = std::stoi(argv[i]);
312
+ #else
313
+ fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
314
+ #endif
315
+ } else if (arg == "--tensor-split" || arg == "-ts") {
316
+ if (++i >= argc) {
317
+ invalid_param = true;
318
+ break;
319
+ }
320
+ #ifdef GGML_USE_CUBLAS
321
+ std::string arg_next = argv[i];
322
+
323
+ // split string by , and /
324
+ const std::regex regex{R"([,/]+)"};
325
+ std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
326
+ std::vector<std::string> split_arg{it, {}};
327
+ GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
328
+
329
+ for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
330
+ if (i < split_arg.size()) {
331
+ params.tensor_split[i] = std::stof(split_arg[i]);
332
+ } else {
333
+ params.tensor_split[i] = 0.0f;
334
+ }
335
+ }
336
+ #else
337
+ fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
338
+ #endif // GGML_USE_CUBLAS
339
+ } else if (arg == "--low-vram" || arg == "-lv") {
340
+ #ifdef GGML_USE_CUBLAS
341
+ params.low_vram = true;
342
+ #else
343
+ fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
344
+ #endif // GGML_USE_CUBLAS
345
+ } else if (arg == "--no-mmap") {
346
+ params.use_mmap = false;
347
+ } else if (arg == "--mtest") {
348
+ params.mem_test = true;
349
+ } else if (arg == "--export") {
350
+ params.export_cgraph = true;
351
+ } else if (arg == "--verbose-prompt") {
352
+ params.verbose_prompt = true;
353
+ } else if (arg == "-r" || arg == "--reverse-prompt") {
354
+ if (++i >= argc) {
355
+ invalid_param = true;
356
+ break;
357
+ }
358
+ params.antiprompt.push_back(argv[i]);
359
+ } else if (arg == "--perplexity") {
360
+ params.perplexity = true;
361
+ } else if (arg == "--ignore-eos") {
362
+ params.logit_bias[llama_token_eos()] = -INFINITY;
363
+ } else if (arg == "--no-penalize-nl") {
364
+ params.penalize_nl = false;
365
+ } else if (arg == "-l" || arg == "--logit-bias") {
366
+ if (++i >= argc) {
367
+ invalid_param = true;
368
+ break;
369
+ }
370
+ std::stringstream ss(argv[i]);
371
+ llama_token key;
372
+ char sign;
373
+ std::string value_str;
374
+ try {
375
+ if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
376
+ params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
377
+ } else {
378
+ throw std::exception();
379
+ }
380
+ } catch (const std::exception&) {
381
+ invalid_param = true;
382
+ break;
383
+ }
384
+ } else if (arg == "-h" || arg == "--help") {
385
+ gpt_print_usage(argc, argv, default_params);
386
+ exit(0);
387
+ } else if (arg == "--random-prompt") {
388
+ params.random_prompt = true;
389
+ } else if (arg == "--in-prefix") {
390
+ if (++i >= argc) {
391
+ invalid_param = true;
392
+ break;
393
+ }
394
+ params.input_prefix = argv[i];
395
+ } else if (arg == "--in-suffix") {
396
+ if (++i >= argc) {
397
+ invalid_param = true;
398
+ break;
399
+ }
400
+ params.input_suffix = argv[i];
401
+ } else {
402
+ fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
403
+ gpt_print_usage(argc, argv, default_params);
404
+ exit(1);
405
+ }
406
+ }
407
+ if (invalid_param) {
408
+ fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
409
+ gpt_print_usage(argc, argv, default_params);
410
+ exit(1);
411
+ }
412
+ if (params.prompt_cache_all &&
413
+ (params.interactive || params.interactive_first ||
414
+ params.instruct)) {
415
+ fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
416
+ gpt_print_usage(argc, argv, default_params);
417
+ exit(1);
418
+ }
419
+
420
+ #ifdef GGML_USE_CUBLAS
421
+ if (!params.lora_adapter.empty() && params.n_gpu_layers > 0) {
422
+ fprintf(stderr, "%s: error: the simultaneous use of LoRAs and GPU acceleration is not supported", __func__);
423
+ exit(1);
424
+ }
425
+ #endif // GGML_USE_CUBLAS
426
+
427
+ if (escape_prompt) {
428
+ process_escapes(params.prompt);
429
+ }
430
+
431
+ return true;
432
+ }
433
+
434
+ void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
435
+ fprintf(stderr, "usage: %s [options]\n", argv[0]);
436
+ fprintf(stderr, "\n");
437
+ fprintf(stderr, "options:\n");
438
+ fprintf(stderr, " -h, --help show this help message and exit\n");
439
+ fprintf(stderr, " -i, --interactive run in interactive mode\n");
440
+ fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
441
+ fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
442
+ fprintf(stderr, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
443
+ fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
444
+ fprintf(stderr, " halt generation at PROMPT, return control in interactive mode\n");
445
+ fprintf(stderr, " (can be specified more than once for multiple prompts).\n");
446
+ fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
447
+ fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
448
+ fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
449
+ fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
450
+ fprintf(stderr, " prompt to start generation with (default: empty)\n");
451
+ fprintf(stderr, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
452
+ fprintf(stderr, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
453
+ fprintf(stderr, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
454
+ fprintf(stderr, " not supported with --interactive or other interactive options\n");
455
+ fprintf(stderr, " --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
456
+ fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
457
+ fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
458
+ fprintf(stderr, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
459
+ fprintf(stderr, " -f FNAME, --file FNAME\n");
460
+ fprintf(stderr, " prompt file to start generation.\n");
461
+ fprintf(stderr, " -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
462
+ fprintf(stderr, " --top-k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
463
+ fprintf(stderr, " --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
464
+ fprintf(stderr, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
465
+ fprintf(stderr, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
466
+ 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);
467
+ fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
468
+ fprintf(stderr, " --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
469
+ fprintf(stderr, " --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
470
+ fprintf(stderr, " --mirostat N use Mirostat sampling.\n");
471
+ fprintf(stderr, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
472
+ fprintf(stderr, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
473
+ fprintf(stderr, " --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
474
+ fprintf(stderr, " --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
475
+ fprintf(stderr, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
476
+ fprintf(stderr, " modifies the likelihood of token appearing in the completion,\n");
477
+ fprintf(stderr, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
478
+ fprintf(stderr, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
479
+ fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
480
+ fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
481
+ fprintf(stderr, " --no-penalize-nl do not penalize newline token\n");
482
+ fprintf(stderr, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
483
+ fprintf(stderr, " not recommended: doubles context memory required and no measurable increase in quality\n");
484
+ fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
485
+ fprintf(stderr, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
486
+ fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
487
+ fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
488
+ if (llama_mlock_supported()) {
489
+ fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
490
+ }
491
+ if (llama_mmap_supported()) {
492
+ fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
493
+ }
494
+ #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
495
+ fprintf(stderr, " -ngl N, --n-gpu-layers N\n");
496
+ fprintf(stderr, " number of layers to store in VRAM\n");
497
+ fprintf(stderr, " -ts SPLIT --tensor-split SPLIT\n");
498
+ fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
499
+ fprintf(stderr, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n" );
500
+ fprintf(stderr, " -lv, --low-vram don't allocate VRAM scratch buffer\n" );
501
+ #endif
502
+ fprintf(stderr, " --mtest compute maximum memory usage\n");
503
+ fprintf(stderr, " --export export the computation graph to 'llama.ggml'\n");
504
+ fprintf(stderr, " --verbose-prompt print prompt before generation\n");
505
+ fprintf(stderr, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
506
+ fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
507
+ fprintf(stderr, " -m FNAME, --model FNAME\n");
508
+ fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
509
+ fprintf(stderr, "\n");
510
+ }
511
+
512
+ std::string gpt_random_prompt(std::mt19937 & rng) {
513
+ const int r = rng() % 10;
514
+ switch (r) {
515
+ case 0: return "So";
516
+ case 1: return "Once upon a time";
517
+ case 2: return "When";
518
+ case 3: return "The";
519
+ case 4: return "After";
520
+ case 5: return "If";
521
+ case 6: return "import";
522
+ case 7: return "He";
523
+ case 8: return "She";
524
+ case 9: return "They";
525
+ default: return "To";
526
+ }
527
+
528
+ return "The";
529
+ }
530
+
531
+ // TODO: not great allocating this every time
532
+ std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
533
+ // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
534
+ std::vector<llama_token> res(text.size() + (int) add_bos);
535
+ const int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
536
+ assert(n >= 0);
537
+ res.resize(n);
538
+
539
+ return res;
540
+ }
541
+
542
+ struct llama_context * llama_init_from_gpt_params(const gpt_params & params) {
543
+ auto lparams = llama_context_default_params();
544
+
545
+ lparams.n_ctx = params.n_ctx;
546
+ lparams.n_batch = params.n_batch;
547
+ lparams.n_gpu_layers = params.n_gpu_layers;
548
+ lparams.main_gpu = params.main_gpu;
549
+ memcpy(lparams.tensor_split, params.tensor_split, LLAMA_MAX_DEVICES*sizeof(float));
550
+ lparams.low_vram = params.low_vram;
551
+ lparams.seed = params.seed;
552
+ lparams.f16_kv = params.memory_f16;
553
+ lparams.use_mmap = params.use_mmap;
554
+ lparams.use_mlock = params.use_mlock;
555
+ lparams.logits_all = params.perplexity;
556
+ lparams.embedding = params.embedding;
557
+
558
+ llama_context * lctx = llama_init_from_file(params.model.c_str(), lparams);
559
+
560
+ if (lctx == NULL) {
561
+ fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
562
+ return NULL;
563
+ }
564
+
565
+ if (!params.lora_adapter.empty()) {
566
+ int err = llama_apply_lora_from_file(lctx,
567
+ params.lora_adapter.c_str(),
568
+ params.lora_base.empty() ? NULL : params.lora_base.c_str(),
569
+ params.n_threads);
570
+ if (err != 0) {
571
+ fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
572
+ return NULL;
573
+ }
574
+ }
575
+
576
+ return lctx;
577
+ }
578
+
579
+ void console_init(console_state & con_st) {
580
+ #if defined(_WIN32)
581
+ // Windows-specific console initialization
582
+ DWORD dwMode = 0;
583
+ con_st.hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
584
+ if (con_st.hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(con_st.hConsole, &dwMode)) {
585
+ con_st.hConsole = GetStdHandle(STD_ERROR_HANDLE);
586
+ if (con_st.hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(con_st.hConsole, &dwMode))) {
587
+ con_st.hConsole = NULL;
588
+ }
589
+ }
590
+ if (con_st.hConsole) {
591
+ // Enable ANSI colors on Windows 10+
592
+ if (con_st.use_color && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
593
+ SetConsoleMode(con_st.hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
594
+ }
595
+ // Set console output codepage to UTF8
596
+ SetConsoleOutputCP(CP_UTF8);
597
+ }
598
+ HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE);
599
+ if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) {
600
+ // Set console input codepage to UTF16
601
+ _setmode(_fileno(stdin), _O_WTEXT);
602
+
603
+ // Turn off ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT)
604
+ dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
605
+ SetConsoleMode(hConIn, dwMode);
606
+ }
607
+ #else
608
+ // POSIX-specific console initialization
609
+ struct termios new_termios;
610
+ tcgetattr(STDIN_FILENO, &con_st.prev_state);
611
+ new_termios = con_st.prev_state;
612
+ new_termios.c_lflag &= ~(ICANON | ECHO);
613
+ new_termios.c_cc[VMIN] = 1;
614
+ new_termios.c_cc[VTIME] = 0;
615
+ tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
616
+
617
+ con_st.tty = fopen("/dev/tty", "w+");
618
+ if (con_st.tty != nullptr) {
619
+ con_st.out = con_st.tty;
620
+ }
621
+
622
+ setlocale(LC_ALL, "");
623
+ #endif
624
+ }
625
+
626
+ void console_cleanup(console_state & con_st) {
627
+ // Reset console color
628
+ console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
629
+
630
+ #if !defined(_WIN32)
631
+ if (con_st.tty != nullptr) {
632
+ con_st.out = stdout;
633
+ fclose(con_st.tty);
634
+ con_st.tty = nullptr;
635
+ }
636
+ // Restore the terminal settings on POSIX systems
637
+ tcsetattr(STDIN_FILENO, TCSANOW, &con_st.prev_state);
638
+ #endif
639
+ }
640
+
641
+ /* Keep track of current color of output, and emit ANSI code if it changes. */
642
+ void console_set_color(console_state & con_st, console_color_t color) {
643
+ if (con_st.use_color && con_st.color != color) {
644
+ fflush(stdout);
645
+ switch(color) {
646
+ case CONSOLE_COLOR_DEFAULT:
647
+ fprintf(con_st.out, ANSI_COLOR_RESET);
648
+ break;
649
+ case CONSOLE_COLOR_PROMPT:
650
+ fprintf(con_st.out, ANSI_COLOR_YELLOW);
651
+ break;
652
+ case CONSOLE_COLOR_USER_INPUT:
653
+ fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_GREEN);
654
+ break;
655
+ case CONSOLE_COLOR_ERROR:
656
+ fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_RED);
657
+ break;
658
+ }
659
+ con_st.color = color;
660
+ fflush(con_st.out);
661
+ }
662
+ }
663
+
664
+ char32_t getchar32() {
665
+ #if defined(_WIN32)
666
+ HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
667
+ wchar_t high_surrogate = 0;
668
+
669
+ while (true) {
670
+ INPUT_RECORD record;
671
+ DWORD count;
672
+ if (!ReadConsoleInputW(hConsole, &record, 1, &count) || count == 0) {
673
+ return WEOF;
674
+ }
675
+
676
+ if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) {
677
+ wchar_t wc = record.Event.KeyEvent.uChar.UnicodeChar;
678
+ if (wc == 0) {
679
+ continue;
680
+ }
681
+
682
+ if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
683
+ high_surrogate = wc;
684
+ continue;
685
+ } else if ((wc >= 0xDC00) && (wc <= 0xDFFF)) { // Check if wc is a low surrogate
686
+ if (high_surrogate != 0) { // Check if we have a high surrogate
687
+ return ((high_surrogate - 0xD800) << 10) + (wc - 0xDC00) + 0x10000;
688
+ }
689
+ }
690
+
691
+ high_surrogate = 0; // Reset the high surrogate
692
+ return static_cast<char32_t>(wc);
693
+ }
694
+ }
695
+ #else
696
+ wchar_t wc = getwchar();
697
+ if (static_cast<wint_t>(wc) == WEOF) {
698
+ return WEOF;
699
+ }
700
+
701
+ #if WCHAR_MAX == 0xFFFF
702
+ if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
703
+ wchar_t low_surrogate = getwchar();
704
+ if ((low_surrogate >= 0xDC00) && (low_surrogate <= 0xDFFF)) { // Check if the next wchar is a low surrogate
705
+ return (static_cast<char32_t>(wc & 0x03FF) << 10) + (low_surrogate & 0x03FF) + 0x10000;
706
+ }
707
+ }
708
+ if ((wc >= 0xD800) && (wc <= 0xDFFF)) { // Invalid surrogate pair
709
+ return 0xFFFD; // Return the replacement character U+FFFD
710
+ }
711
+ #endif
712
+
713
+ return static_cast<char32_t>(wc);
714
+ #endif
715
+ }
716
+
717
+ void pop_cursor(console_state & con_st) {
718
+ #if defined(_WIN32)
719
+ if (con_st.hConsole != NULL) {
720
+ CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
721
+ GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo);
722
+
723
+ COORD newCursorPosition = bufferInfo.dwCursorPosition;
724
+ if (newCursorPosition.X == 0) {
725
+ newCursorPosition.X = bufferInfo.dwSize.X - 1;
726
+ newCursorPosition.Y -= 1;
727
+ } else {
728
+ newCursorPosition.X -= 1;
729
+ }
730
+
731
+ SetConsoleCursorPosition(con_st.hConsole, newCursorPosition);
732
+ return;
733
+ }
734
+ #endif
735
+ putc('\b', con_st.out);
736
+ }
737
+
738
+ int estimateWidth(char32_t codepoint) {
739
+ #if defined(_WIN32)
740
+ return 1;
741
+ #else
742
+ return wcwidth(codepoint);
743
+ #endif
744
+ }
745
+
746
+ int put_codepoint(console_state & con_st, const char* utf8_codepoint, size_t length, int expectedWidth) {
747
+ #if defined(_WIN32)
748
+ CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
749
+ if (!GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo)) {
750
+ // go with the default
751
+ return expectedWidth;
752
+ }
753
+ COORD initialPosition = bufferInfo.dwCursorPosition;
754
+ DWORD nNumberOfChars = length;
755
+ WriteConsole(con_st.hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL);
756
+
757
+ CONSOLE_SCREEN_BUFFER_INFO newBufferInfo;
758
+ GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
759
+
760
+ // Figure out our real position if we're in the last column
761
+ if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) {
762
+ DWORD nNumberOfChars;
763
+ WriteConsole(con_st.hConsole, &" \b", 2, &nNumberOfChars, NULL);
764
+ GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
765
+ }
766
+
767
+ int width = newBufferInfo.dwCursorPosition.X - initialPosition.X;
768
+ if (width < 0) {
769
+ width += newBufferInfo.dwSize.X;
770
+ }
771
+ return width;
772
+ #else
773
+ // we can trust expectedWidth if we've got one
774
+ if (expectedWidth >= 0 || con_st.tty == nullptr) {
775
+ fwrite(utf8_codepoint, length, 1, con_st.out);
776
+ return expectedWidth;
777
+ }
778
+
779
+ fputs("\033[6n", con_st.tty); // Query cursor position
780
+ int x1, x2, y1, y2;
781
+ int results = 0;
782
+ results = fscanf(con_st.tty, "\033[%d;%dR", &y1, &x1);
783
+
784
+ fwrite(utf8_codepoint, length, 1, con_st.tty);
785
+
786
+ fputs("\033[6n", con_st.tty); // Query cursor position
787
+ results += fscanf(con_st.tty, "\033[%d;%dR", &y2, &x2);
788
+
789
+ if (results != 4) {
790
+ return expectedWidth;
791
+ }
792
+
793
+ int width = x2 - x1;
794
+ if (width < 0) {
795
+ // Calculate the width considering text wrapping
796
+ struct winsize w;
797
+ ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
798
+ width += w.ws_col;
799
+ }
800
+ return width;
801
+ #endif
802
+ }
803
+
804
+ void replace_last(console_state & con_st, char ch) {
805
+ #if defined(_WIN32)
806
+ pop_cursor(con_st);
807
+ put_codepoint(con_st, &ch, 1, 1);
808
+ #else
809
+ fprintf(con_st.out, "\b%c", ch);
810
+ #endif
811
+ }
812
+
813
+ void append_utf8(char32_t ch, std::string & out) {
814
+ if (ch <= 0x7F) {
815
+ out.push_back(static_cast<unsigned char>(ch));
816
+ } else if (ch <= 0x7FF) {
817
+ out.push_back(static_cast<unsigned char>(0xC0 | ((ch >> 6) & 0x1F)));
818
+ out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
819
+ } else if (ch <= 0xFFFF) {
820
+ out.push_back(static_cast<unsigned char>(0xE0 | ((ch >> 12) & 0x0F)));
821
+ out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
822
+ out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
823
+ } else if (ch <= 0x10FFFF) {
824
+ out.push_back(static_cast<unsigned char>(0xF0 | ((ch >> 18) & 0x07)));
825
+ out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 12) & 0x3F)));
826
+ out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
827
+ out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
828
+ } else {
829
+ // Invalid Unicode code point
830
+ }
831
+ }
832
+
833
+ // Helper function to remove the last UTF-8 character from a string
834
+ void pop_back_utf8_char(std::string & line) {
835
+ if (line.empty()) {
836
+ return;
837
+ }
838
+
839
+ size_t pos = line.length() - 1;
840
+
841
+ // Find the start of the last UTF-8 character (checking up to 4 bytes back)
842
+ for (size_t i = 0; i < 3 && pos > 0; ++i, --pos) {
843
+ if ((line[pos] & 0xC0) != 0x80) break; // Found the start of the character
844
+ }
845
+ line.erase(pos);
846
+ }
847
+
848
+ bool console_readline(console_state & con_st, std::string & line) {
849
+ console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
850
+ if (con_st.out != stdout) {
851
+ fflush(stdout);
852
+ }
853
+
854
+ line.clear();
855
+ std::vector<int> widths;
856
+ bool is_special_char = false;
857
+ bool end_of_stream = false;
858
+
859
+ char32_t input_char;
860
+ while (true) {
861
+ fflush(con_st.out); // Ensure all output is displayed before waiting for input
862
+ input_char = getchar32();
863
+
864
+ if (input_char == '\r' || input_char == '\n') {
865
+ break;
866
+ }
867
+
868
+ if (input_char == (char32_t) WEOF || input_char == 0x04 /* Ctrl+D*/) {
869
+ end_of_stream = true;
870
+ break;
871
+ }
872
+
873
+ if (is_special_char) {
874
+ console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
875
+ replace_last(con_st, line.back());
876
+ is_special_char = false;
877
+ }
878
+
879
+ if (input_char == '\033') { // Escape sequence
880
+ char32_t code = getchar32();
881
+ if (code == '[' || code == 0x1B) {
882
+ // Discard the rest of the escape sequence
883
+ while ((code = getchar32()) != (char32_t) WEOF) {
884
+ if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z') || code == '~') {
885
+ break;
886
+ }
887
+ }
888
+ }
889
+ } else if (input_char == 0x08 || input_char == 0x7F) { // Backspace
890
+ if (!widths.empty()) {
891
+ int count;
892
+ do {
893
+ count = widths.back();
894
+ widths.pop_back();
895
+ // Move cursor back, print space, and move cursor back again
896
+ for (int i = 0; i < count; i++) {
897
+ replace_last(con_st, ' ');
898
+ pop_cursor(con_st);
899
+ }
900
+ pop_back_utf8_char(line);
901
+ } while (count == 0 && !widths.empty());
902
+ }
903
+ } else {
904
+ int offset = line.length();
905
+ append_utf8(input_char, line);
906
+ int width = put_codepoint(con_st, line.c_str() + offset, line.length() - offset, estimateWidth(input_char));
907
+ if (width < 0) {
908
+ width = 0;
909
+ }
910
+ widths.push_back(width);
911
+ }
912
+
913
+ if (!line.empty() && (line.back() == '\\' || line.back() == '/')) {
914
+ console_set_color(con_st, CONSOLE_COLOR_PROMPT);
915
+ replace_last(con_st, line.back());
916
+ is_special_char = true;
917
+ }
918
+ }
919
+
920
+ bool has_more = con_st.multiline_input;
921
+ if (is_special_char) {
922
+ replace_last(con_st, ' ');
923
+ pop_cursor(con_st);
924
+
925
+ char last = line.back();
926
+ line.pop_back();
927
+ if (last == '\\') {
928
+ line += '\n';
929
+ fputc('\n', con_st.out);
930
+ has_more = !has_more;
931
+ } else {
932
+ // llama will just eat the single space, it won't act as a space
933
+ if (line.length() == 1 && line.back() == ' ') {
934
+ line.clear();
935
+ pop_cursor(con_st);
936
+ }
937
+ has_more = false;
938
+ }
939
+ } else {
940
+ if (end_of_stream) {
941
+ has_more = false;
942
+ } else {
943
+ line += '\n';
944
+ fputc('\n', con_st.out);
945
+ }
946
+ }
947
+
948
+ fflush(con_st.out);
949
+ return has_more;
950
+ }
examples/common.h ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ bool low_vram = 0; // if true, reduce VRAM usage at the cost of performance
34
+
35
+ // sampling parameters
36
+ std::unordered_map<llama_token, float> logit_bias; // logit bias for specific tokens
37
+ int32_t top_k = 40; // <= 0 to use vocab size
38
+ float top_p = 0.95f; // 1.0 = disabled
39
+ float tfs_z = 1.00f; // 1.0 = disabled
40
+ float typical_p = 1.00f; // 1.0 = disabled
41
+ float temp = 0.80f; // 1.0 = disabled
42
+ float repeat_penalty = 1.10f; // 1.0 = disabled
43
+ int32_t repeat_last_n = 64; // last n tokens to penalize (0 = disable penalty, -1 = context size)
44
+ float frequency_penalty = 0.00f; // 0.0 = disabled
45
+ float presence_penalty = 0.00f; // 0.0 = disabled
46
+ int mirostat = 0; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
47
+ float mirostat_tau = 5.00f; // target entropy
48
+ float mirostat_eta = 0.10f; // learning rate
49
+
50
+ std::string model = "models/7B/ggml-model.bin"; // model path
51
+ std::string model_alias = "unknown"; // model alias
52
+ std::string prompt = "";
53
+ std::string path_prompt_cache = ""; // path to file for saving/loading prompt eval state
54
+ std::string input_prefix = ""; // string to prefix user inputs with
55
+ std::string input_suffix = ""; // string to suffix user inputs with
56
+ std::vector<std::string> antiprompt; // string upon seeing which more user input is prompted
57
+
58
+ std::string lora_adapter = ""; // lora adapter path
59
+ std::string lora_base = ""; // base model path for the lora adapter
60
+
61
+ bool memory_f16 = true; // use f16 instead of f32 for memory kv
62
+ bool random_prompt = false; // do not randomize prompt if none provided
63
+ bool use_color = false; // use color to distinguish generations and inputs
64
+ bool interactive = false; // interactive mode
65
+ bool prompt_cache_all = false; // save user input and generations to prompt cache
66
+ bool prompt_cache_ro = false; // open the prompt cache read-only and do not update it
67
+
68
+ bool embedding = false; // get only sentence embedding
69
+ bool interactive_first = false; // wait for user input immediately
70
+ bool multiline_input = false; // reverse the usage of `\`
71
+
72
+ bool instruct = false; // instruction mode (used for Alpaca models)
73
+ bool penalize_nl = true; // consider newlines as a repeatable token
74
+ bool perplexity = false; // compute perplexity over the prompt
75
+ bool use_mmap = true; // use mmap for faster loads
76
+ bool use_mlock = false; // use mlock to keep model in memory
77
+ bool mem_test = false; // compute maximum memory usage
78
+ bool export_cgraph = false; // export the computation graph
79
+ bool verbose_prompt = false; // print prompt tokens before generation
80
+ };
81
+
82
+ bool gpt_params_parse(int argc, char ** argv, gpt_params & params);
83
+
84
+ void gpt_print_usage(int argc, char ** argv, const gpt_params & params);
85
+
86
+ std::string gpt_random_prompt(std::mt19937 & rng);
87
+
88
+ //
89
+ // Vocab utils
90
+ //
91
+
92
+ std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos);
93
+
94
+ //
95
+ // Model utils
96
+ //
97
+
98
+ struct llama_context * llama_init_from_gpt_params(const gpt_params & params);
99
+
100
+ //
101
+ // Console utils
102
+ //
103
+
104
+ #define ANSI_COLOR_RED "\x1b[31m"
105
+ #define ANSI_COLOR_GREEN "\x1b[32m"
106
+ #define ANSI_COLOR_YELLOW "\x1b[33m"
107
+ #define ANSI_COLOR_BLUE "\x1b[34m"
108
+ #define ANSI_COLOR_MAGENTA "\x1b[35m"
109
+ #define ANSI_COLOR_CYAN "\x1b[36m"
110
+ #define ANSI_COLOR_RESET "\x1b[0m"
111
+ #define ANSI_BOLD "\x1b[1m"
112
+
113
+ enum console_color_t {
114
+ CONSOLE_COLOR_DEFAULT=0,
115
+ CONSOLE_COLOR_PROMPT,
116
+ CONSOLE_COLOR_USER_INPUT,
117
+ CONSOLE_COLOR_ERROR
118
+ };
119
+
120
+ struct console_state {
121
+ bool multiline_input = false;
122
+ bool use_color = false;
123
+ console_color_t color = CONSOLE_COLOR_DEFAULT;
124
+
125
+ FILE* out = stdout;
126
+ #if defined (_WIN32)
127
+ void* hConsole;
128
+ #else
129
+ FILE* tty = nullptr;
130
+ termios prev_state;
131
+ #endif
132
+ };
133
+
134
+ void console_init(console_state & con_st);
135
+ void console_cleanup(console_state & con_st);
136
+ void console_set_color(console_state & con_st, console_color_t color);
137
+ 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,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "common.h"
2
+ #include "llama.h"
3
+ #include "build-info.h"
4
+
5
+ #include <ctime>
6
+
7
+ #if defined(_MSC_VER)
8
+ #pragma warning(disable: 4244 4267) // possible loss of data
9
+ #endif
10
+
11
+ int main(int argc, char ** argv) {
12
+ gpt_params params;
13
+
14
+ if (gpt_params_parse(argc, argv, params) == false) {
15
+ return 1;
16
+ }
17
+
18
+ params.embedding = true;
19
+
20
+ if (params.n_ctx > 2048) {
21
+ fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
22
+ "expect poor results\n", __func__, params.n_ctx);
23
+ }
24
+
25
+ fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
26
+
27
+ if (params.seed < 0) {
28
+ params.seed = time(NULL);
29
+ }
30
+
31
+ fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
32
+
33
+ std::mt19937 rng(params.seed);
34
+ if (params.random_prompt) {
35
+ params.prompt = gpt_random_prompt(rng);
36
+ }
37
+
38
+ llama_init_backend();
39
+
40
+ llama_context * ctx;
41
+
42
+ // load the model
43
+ ctx = llama_init_from_gpt_params(params);
44
+ if (ctx == NULL) {
45
+ fprintf(stderr, "%s: error: unable to load model\n", __func__);
46
+ return 1;
47
+ }
48
+
49
+ // print system information
50
+ {
51
+ fprintf(stderr, "\n");
52
+ fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
53
+ params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
54
+ }
55
+
56
+ int n_past = 0;
57
+
58
+ // Add a space in front of the first character to match OG llama tokenizer behavior
59
+ params.prompt.insert(0, 1, ' ');
60
+
61
+ // tokenize the prompt
62
+ auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
63
+
64
+ if (params.verbose_prompt) {
65
+ fprintf(stderr, "\n");
66
+ fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
67
+ fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
68
+ for (int i = 0; i < (int) embd_inp.size(); i++) {
69
+ fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
70
+ }
71
+ fprintf(stderr, "\n");
72
+ }
73
+
74
+ if (params.embedding){
75
+ if (embd_inp.size() > 0) {
76
+ if (llama_eval(ctx, embd_inp.data(), embd_inp.size(), n_past, params.n_threads)) {
77
+ fprintf(stderr, "%s : failed to eval\n", __func__);
78
+ return 1;
79
+ }
80
+ }
81
+
82
+ const int n_embd = llama_n_embd(ctx);
83
+ const auto embeddings = llama_get_embeddings(ctx);
84
+
85
+ for (int i = 0; i < n_embd; i++) {
86
+ printf("%f ", embeddings[i]);
87
+ }
88
+ printf("\n");
89
+ }
90
+
91
+ llama_print_timings(ctx);
92
+ llama_free(ctx);
93
+
94
+ return 0;
95
+ }
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,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import os
3
+ import csv
4
+
5
+ labels = []
6
+ numbers = []
7
+ numEntries = 1
8
+
9
+ rows = []
10
+
11
+
12
+ def bar_chart(numbers, labels, pos):
13
+ plt.bar(pos, numbers, color='blue')
14
+ plt.xticks(ticks=pos, labels=labels)
15
+ plt.title("Jeopardy Results by Model")
16
+ plt.xlabel("Model")
17
+ plt.ylabel("Questions Correct")
18
+ plt.show()
19
+
20
+
21
+ def calculatecorrect():
22
+ directory = os.fsencode("./examples/jeopardy/results/")
23
+ csv_reader = csv.reader(open("./examples/jeopardy/qasheet.csv", 'rt'), delimiter=',')
24
+ for row in csv_reader:
25
+ global rows
26
+ rows.append(row)
27
+ for listing in os.listdir(directory):
28
+ filename = os.fsdecode(listing)
29
+ if filename.endswith(".txt"):
30
+ file = open("./examples/jeopardy/results/" + filename, "rt")
31
+ global labels
32
+ global numEntries
33
+ global numbers
34
+ labels.append(filename[:-4])
35
+ numEntries += 1
36
+ i = 1
37
+ totalcorrect = 0
38
+ for line in file.readlines():
39
+ if line.strip() != "------":
40
+ print(line)
41
+ else:
42
+ print("Correct answer: " + rows[i][2] + "\n")
43
+ i += 1
44
+ print("Did the AI get the question right? (y/n)")
45
+ if input() == "y":
46
+ totalcorrect += 1
47
+ numbers.append(totalcorrect)
48
+
49
+
50
+ if __name__ == '__main__':
51
+ calculatecorrect()
52
+ pos = list(range(numEntries))
53
+ labels.append("Human")
54
+ numbers.append(48.11)
55
+ bar_chart(numbers, labels, pos)
56
+ print(labels)
57
+ 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,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ - `-lv, --low-vram`: Do not allocate a VRAM scratch buffer for holding temporary results. Reduces VRAM usage at the cost of performance, particularly prompt processing speed. Requires cuBLAS.
292
+ - `--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.
293
+ - `--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,671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef NOMINMAX
27
+ #define NOMINMAX
28
+ #endif
29
+ #include <windows.h>
30
+ #include <signal.h>
31
+ #endif
32
+
33
+ #if defined(_MSC_VER)
34
+ #pragma warning(disable: 4244 4267) // possible loss of data
35
+ #endif
36
+
37
+ static console_state con_st;
38
+ static llama_context ** g_ctx;
39
+
40
+ static bool is_interacting = false;
41
+
42
+ #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
43
+ void sigint_handler(int signo) {
44
+ if (signo == SIGINT) {
45
+ if (!is_interacting) {
46
+ is_interacting=true;
47
+ } else {
48
+ console_cleanup(con_st);
49
+ printf("\n");
50
+ llama_print_timings(*g_ctx);
51
+ _exit(130);
52
+ }
53
+ }
54
+ }
55
+ #endif
56
+
57
+ int main(int argc, char ** argv) {
58
+ gpt_params params;
59
+
60
+ if (gpt_params_parse(argc, argv, params) == false) {
61
+ return 1;
62
+ }
63
+
64
+ // save choice to use color for later
65
+ // (note for later: this is a slightly awkward choice)
66
+ con_st.use_color = params.use_color;
67
+ con_st.multiline_input = params.multiline_input;
68
+ console_init(con_st);
69
+ atexit([]() { console_cleanup(con_st); });
70
+
71
+ if (params.perplexity) {
72
+ printf("\n************\n");
73
+ printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
74
+ printf("************\n\n");
75
+
76
+ return 0;
77
+ }
78
+
79
+ if (params.embedding) {
80
+ printf("\n************\n");
81
+ printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
82
+ printf("************\n\n");
83
+
84
+ return 0;
85
+ }
86
+
87
+ if (params.n_ctx > 2048) {
88
+ fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
89
+ "expect poor results\n", __func__, params.n_ctx);
90
+ } else if (params.n_ctx < 8) {
91
+ fprintf(stderr, "%s: warning: minimum context size is 8, using minimum size.\n", __func__);
92
+ params.n_ctx = 8;
93
+ }
94
+
95
+ fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
96
+
97
+ if (params.seed < 0) {
98
+ params.seed = time(NULL);
99
+ }
100
+
101
+ fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
102
+
103
+ std::mt19937 rng(params.seed);
104
+ if (params.random_prompt) {
105
+ params.prompt = gpt_random_prompt(rng);
106
+ }
107
+
108
+ llama_init_backend();
109
+
110
+ llama_context * ctx;
111
+ g_ctx = &ctx;
112
+
113
+ // load the model and apply lora adapter, if any
114
+ ctx = llama_init_from_gpt_params(params);
115
+ if (ctx == NULL) {
116
+ fprintf(stderr, "%s: error: unable to load model\n", __func__);
117
+ return 1;
118
+ }
119
+
120
+ // print system information
121
+ {
122
+ fprintf(stderr, "\n");
123
+ fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
124
+ params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
125
+ }
126
+
127
+ // determine the maximum memory usage needed to do inference for the given n_batch and n_predict parameters
128
+ // uncomment the "used_mem" line in llama.cpp to see the results
129
+ if (params.mem_test) {
130
+ {
131
+ const std::vector<llama_token> tmp(params.n_batch, llama_token_bos());
132
+ llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
133
+ }
134
+
135
+ {
136
+ const std::vector<llama_token> tmp = { 0, };
137
+ llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
138
+ }
139
+
140
+ llama_print_timings(ctx);
141
+ llama_free(ctx);
142
+
143
+ return 0;
144
+ }
145
+
146
+ // export the cgraph and exit
147
+ if (params.export_cgraph) {
148
+ llama_eval_export(ctx, "llama.ggml");
149
+ llama_free(ctx);
150
+
151
+ return 0;
152
+ }
153
+
154
+ std::string path_session = params.path_prompt_cache;
155
+ std::vector<llama_token> session_tokens;
156
+
157
+ if (!path_session.empty()) {
158
+ fprintf(stderr, "%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
159
+
160
+ // fopen to check for existing session
161
+ FILE * fp = std::fopen(path_session.c_str(), "rb");
162
+ if (fp != NULL) {
163
+ std::fclose(fp);
164
+
165
+ session_tokens.resize(params.n_ctx);
166
+ size_t n_token_count_out = 0;
167
+ if (!llama_load_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
168
+ fprintf(stderr, "%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
169
+ return 1;
170
+ }
171
+ session_tokens.resize(n_token_count_out);
172
+ llama_set_rng_seed(ctx, params.seed);
173
+
174
+ fprintf(stderr, "%s: loaded a session with prompt size of %d tokens\n", __func__, (int) session_tokens.size());
175
+ } else {
176
+ fprintf(stderr, "%s: session file does not exist, will create\n", __func__);
177
+ }
178
+ }
179
+
180
+ // tokenize the prompt
181
+ std::vector<llama_token> embd_inp;
182
+
183
+ if (params.interactive_first || params.instruct || !params.prompt.empty() || session_tokens.empty()) {
184
+ // Add a space in front of the first character to match OG llama tokenizer behavior
185
+ params.prompt.insert(0, 1, ' ');
186
+
187
+ embd_inp = ::llama_tokenize(ctx, params.prompt, true);
188
+ } else {
189
+ embd_inp = session_tokens;
190
+ }
191
+
192
+ const int n_ctx = llama_n_ctx(ctx);
193
+
194
+ if ((int) embd_inp.size() > n_ctx - 4) {
195
+ fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
196
+ return 1;
197
+ }
198
+
199
+ // debug message about similarity of saved session, if applicable
200
+ size_t n_matching_session_tokens = 0;
201
+ if (session_tokens.size()) {
202
+ for (llama_token id : session_tokens) {
203
+ if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
204
+ break;
205
+ }
206
+ n_matching_session_tokens++;
207
+ }
208
+ if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
209
+ fprintf(stderr, "%s: using full prompt from session file\n", __func__);
210
+ } else if (n_matching_session_tokens >= embd_inp.size()) {
211
+ fprintf(stderr, "%s: session file has exact match for prompt!\n", __func__);
212
+ } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
213
+ fprintf(stderr, "%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
214
+ __func__, n_matching_session_tokens, embd_inp.size());
215
+ } else {
216
+ fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
217
+ __func__, n_matching_session_tokens, embd_inp.size());
218
+ }
219
+ }
220
+
221
+ // if we will use the cache for the full prompt without reaching the end of the cache, force
222
+ // reevaluation of the last token token to recalculate the cached logits
223
+ if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() &&
224
+ session_tokens.size() > embd_inp.size()) {
225
+ session_tokens.resize(embd_inp.size() - 1);
226
+ }
227
+
228
+ // number of tokens to keep when resetting context
229
+ if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct) {
230
+ params.n_keep = (int)embd_inp.size();
231
+ }
232
+
233
+ // prefix & suffix for instruct mode
234
+ const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
235
+ const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
236
+
237
+ // in instruct mode, we inject a prefix and a suffix to each input by the user
238
+ if (params.instruct) {
239
+ params.interactive_first = true;
240
+ params.antiprompt.push_back("### Instruction:\n\n");
241
+ }
242
+
243
+ // enable interactive mode if interactive start is specified
244
+ if (params.interactive_first) {
245
+ params.interactive = true;
246
+ }
247
+
248
+ // determine newline token
249
+ auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
250
+
251
+ if (params.verbose_prompt) {
252
+ fprintf(stderr, "\n");
253
+ fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
254
+ fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
255
+ for (int i = 0; i < (int) embd_inp.size(); i++) {
256
+ fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
257
+ }
258
+ if (params.n_keep > 0) {
259
+ fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
260
+ for (int i = 0; i < params.n_keep; i++) {
261
+ fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
262
+ }
263
+ fprintf(stderr, "'\n");
264
+ }
265
+ fprintf(stderr, "\n");
266
+ }
267
+
268
+ if (params.interactive) {
269
+ #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
270
+ struct sigaction sigint_action;
271
+ sigint_action.sa_handler = sigint_handler;
272
+ sigemptyset (&sigint_action.sa_mask);
273
+ sigint_action.sa_flags = 0;
274
+ sigaction(SIGINT, &sigint_action, NULL);
275
+ #elif defined (_WIN32)
276
+ auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
277
+ return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
278
+ };
279
+ SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
280
+ #endif
281
+
282
+ fprintf(stderr, "%s: interactive mode on.\n", __func__);
283
+
284
+ if (params.antiprompt.size()) {
285
+ for (auto antiprompt : params.antiprompt) {
286
+ fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
287
+ }
288
+ }
289
+
290
+ if (!params.input_prefix.empty()) {
291
+ fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
292
+ }
293
+
294
+ if (!params.input_suffix.empty()) {
295
+ fprintf(stderr, "Input suffix: '%s'\n", params.input_suffix.c_str());
296
+ }
297
+ }
298
+ 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",
299
+ 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);
300
+ 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);
301
+ fprintf(stderr, "\n\n");
302
+
303
+ // TODO: replace with ring-buffer
304
+ std::vector<llama_token> last_n_tokens(n_ctx);
305
+ std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
306
+
307
+ if (params.interactive) {
308
+ const char *control_message;
309
+ if (con_st.multiline_input) {
310
+ control_message = " - To return control to LLaMa, end your input with '\\'.\n"
311
+ " - To return control without starting a new line, end your input with '/'.\n";
312
+ } else {
313
+ control_message = " - Press Return to return control to LLaMa.\n"
314
+ " - To return control without starting a new line, end your input with '/'.\n"
315
+ " - If you want to submit another line, end your input with '\\'.\n";
316
+ }
317
+ fprintf(stderr, "== Running in interactive mode. ==\n"
318
+ #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
319
+ " - Press Ctrl+C to interject at any time.\n"
320
+ #endif
321
+ "%s\n", control_message);
322
+
323
+ is_interacting = params.interactive_first;
324
+ }
325
+
326
+ bool is_antiprompt = false;
327
+ bool input_echo = true;
328
+ bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
329
+
330
+ int n_past = 0;
331
+ int n_remain = params.n_predict;
332
+ int n_consumed = 0;
333
+ int n_session_consumed = 0;
334
+
335
+ // the first thing we will do is to output the prompt, so set color accordingly
336
+ console_set_color(con_st, CONSOLE_COLOR_PROMPT);
337
+
338
+ std::vector<llama_token> embd;
339
+
340
+ // do one empty run to warm up the model
341
+ {
342
+ const std::vector<llama_token> tmp = { llama_token_bos(), };
343
+ llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
344
+ llama_reset_timings(ctx);
345
+ }
346
+
347
+ while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
348
+ // predict
349
+ if (embd.size() > 0) {
350
+ // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
351
+ // --prompt or --file which uses the same value.
352
+ auto max_embd_size = n_ctx - 4;
353
+ // Ensure the input doesn't exceed the context size by truncating embd if necessary.
354
+ if ((int)embd.size() > max_embd_size) {
355
+ auto skipped_tokens = embd.size() - max_embd_size;
356
+ console_set_color(con_st, CONSOLE_COLOR_ERROR);
357
+ printf("<<input too long: skipped %" PRIu64 " token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
358
+ console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
359
+ fflush(stdout);
360
+ embd.resize(max_embd_size);
361
+ }
362
+
363
+ // infinite text generation via context swapping
364
+ // if we run out of context:
365
+ // - take the n_keep first tokens from the original prompt (via n_past)
366
+ // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
367
+ if (n_past + (int) embd.size() > n_ctx) {
368
+ const int n_left = n_past - params.n_keep;
369
+
370
+ // always keep the first token - BOS
371
+ n_past = std::max(1, params.n_keep);
372
+
373
+ // insert n_left/2 tokens at the start of embd from last_n_tokens
374
+ embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
375
+
376
+ // stop saving session if we run out of context
377
+ path_session.clear();
378
+
379
+ //printf("\n---\n");
380
+ //printf("resetting: '");
381
+ //for (int i = 0; i < (int) embd.size(); i++) {
382
+ // printf("%s", llama_token_to_str(ctx, embd[i]));
383
+ //}
384
+ //printf("'\n");
385
+ //printf("\n---\n");
386
+ }
387
+
388
+ // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
389
+ if (n_session_consumed < (int) session_tokens.size()) {
390
+ size_t i = 0;
391
+ for ( ; i < embd.size(); i++) {
392
+ if (embd[i] != session_tokens[n_session_consumed]) {
393
+ session_tokens.resize(n_session_consumed);
394
+ break;
395
+ }
396
+
397
+ n_past++;
398
+ n_session_consumed++;
399
+
400
+ if (n_session_consumed >= (int) session_tokens.size()) {
401
+ ++i;
402
+ break;
403
+ }
404
+ }
405
+ if (i > 0) {
406
+ embd.erase(embd.begin(), embd.begin() + i);
407
+ }
408
+ }
409
+
410
+ // evaluate tokens in batches
411
+ // embd is typically prepared beforehand to fit within a batch, but not always
412
+ for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
413
+ int n_eval = (int) embd.size() - i;
414
+ if (n_eval > params.n_batch) {
415
+ n_eval = params.n_batch;
416
+ }
417
+ if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
418
+ fprintf(stderr, "%s : failed to eval\n", __func__);
419
+ return 1;
420
+ }
421
+ n_past += n_eval;
422
+ }
423
+
424
+ if (embd.size() > 0 && !path_session.empty()) {
425
+ session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
426
+ n_session_consumed = session_tokens.size();
427
+ }
428
+ }
429
+
430
+ embd.clear();
431
+
432
+ if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
433
+ // out of user input, sample next token
434
+ const float temp = params.temp;
435
+ const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
436
+ const float top_p = params.top_p;
437
+ const float tfs_z = params.tfs_z;
438
+ const float typical_p = params.typical_p;
439
+ const int32_t repeat_last_n = params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
440
+ const float repeat_penalty = params.repeat_penalty;
441
+ const float alpha_presence = params.presence_penalty;
442
+ const float alpha_frequency = params.frequency_penalty;
443
+ const int mirostat = params.mirostat;
444
+ const float mirostat_tau = params.mirostat_tau;
445
+ const float mirostat_eta = params.mirostat_eta;
446
+ const bool penalize_nl = params.penalize_nl;
447
+
448
+ // optionally save the session on first sample (for faster prompt loading next time)
449
+ if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
450
+ need_to_save_session = false;
451
+ llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
452
+ }
453
+
454
+ llama_token id = 0;
455
+
456
+ {
457
+ auto logits = llama_get_logits(ctx);
458
+ auto n_vocab = llama_n_vocab(ctx);
459
+
460
+ // Apply params.logit_bias map
461
+ for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
462
+ logits[it->first] += it->second;
463
+ }
464
+
465
+ std::vector<llama_token_data> candidates;
466
+ candidates.reserve(n_vocab);
467
+ for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
468
+ candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
469
+ }
470
+
471
+ llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
472
+
473
+ // Apply penalties
474
+ float nl_logit = logits[llama_token_nl()];
475
+ auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), n_ctx);
476
+ llama_sample_repetition_penalty(ctx, &candidates_p,
477
+ last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
478
+ last_n_repeat, repeat_penalty);
479
+ llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
480
+ last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
481
+ last_n_repeat, alpha_frequency, alpha_presence);
482
+ if (!penalize_nl) {
483
+ logits[llama_token_nl()] = nl_logit;
484
+ }
485
+
486
+ if (temp <= 0) {
487
+ // Greedy sampling
488
+ id = llama_sample_token_greedy(ctx, &candidates_p);
489
+ } else {
490
+ if (mirostat == 1) {
491
+ static float mirostat_mu = 2.0f * mirostat_tau;
492
+ const int mirostat_m = 100;
493
+ llama_sample_temperature(ctx, &candidates_p, temp);
494
+ id = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
495
+ } else if (mirostat == 2) {
496
+ static float mirostat_mu = 2.0f * mirostat_tau;
497
+ llama_sample_temperature(ctx, &candidates_p, temp);
498
+ id = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
499
+ } else {
500
+ // Temperature sampling
501
+ llama_sample_top_k(ctx, &candidates_p, top_k, 1);
502
+ llama_sample_tail_free(ctx, &candidates_p, tfs_z, 1);
503
+ llama_sample_typical(ctx, &candidates_p, typical_p, 1);
504
+ llama_sample_top_p(ctx, &candidates_p, top_p, 1);
505
+ llama_sample_temperature(ctx, &candidates_p, temp);
506
+ id = llama_sample_token(ctx, &candidates_p);
507
+ }
508
+ }
509
+ // printf("`%d`", candidates_p.size);
510
+
511
+ last_n_tokens.erase(last_n_tokens.begin());
512
+ last_n_tokens.push_back(id);
513
+ }
514
+
515
+ // replace end of text token with newline token when in interactive mode
516
+ if (id == llama_token_eos() && params.interactive && !params.instruct) {
517
+ id = llama_token_newline.front();
518
+ if (params.antiprompt.size() != 0) {
519
+ // tokenize and inject first reverse prompt
520
+ const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
521
+ embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
522
+ }
523
+ }
524
+
525
+ // add it to the context
526
+ embd.push_back(id);
527
+
528
+ // echo this to console
529
+ input_echo = true;
530
+
531
+ // decrement remaining sampling budget
532
+ --n_remain;
533
+ } else {
534
+ // some user input remains from prompt or interaction, forward it to processing
535
+ while ((int) embd_inp.size() > n_consumed) {
536
+ embd.push_back(embd_inp[n_consumed]);
537
+ last_n_tokens.erase(last_n_tokens.begin());
538
+ last_n_tokens.push_back(embd_inp[n_consumed]);
539
+ ++n_consumed;
540
+ if ((int) embd.size() >= params.n_batch) {
541
+ break;
542
+ }
543
+ }
544
+ }
545
+
546
+ // display text
547
+ if (input_echo) {
548
+ for (auto id : embd) {
549
+ printf("%s", llama_token_to_str(ctx, id));
550
+ }
551
+ fflush(stdout);
552
+ }
553
+ // reset color to default if we there is no pending user input
554
+ if (input_echo && (int)embd_inp.size() == n_consumed) {
555
+ console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
556
+ }
557
+
558
+ // if not currently processing queued inputs;
559
+ if ((int) embd_inp.size() <= n_consumed) {
560
+
561
+ // check for reverse prompt
562
+ if (params.antiprompt.size()) {
563
+ std::string last_output;
564
+ for (auto id : last_n_tokens) {
565
+ last_output += llama_token_to_str(ctx, id);
566
+ }
567
+
568
+ is_antiprompt = false;
569
+ // Check if each of the reverse prompts appears at the end of the output.
570
+ // If we're not running interactively, the reverse prompt might be tokenized with some following characters
571
+ // so we'll compensate for that by widening the search window a bit.
572
+ for (std::string & antiprompt : params.antiprompt) {
573
+ size_t extra_padding = params.interactive ? 0 : 2;
574
+ size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
575
+ ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
576
+ : 0;
577
+
578
+ if (last_output.find(antiprompt.c_str(), search_start_pos) != std::string::npos) {
579
+ if (params.interactive) {
580
+ is_interacting = true;
581
+ console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
582
+ }
583
+ is_antiprompt = true;
584
+ fflush(stdout);
585
+ break;
586
+ }
587
+ }
588
+ }
589
+
590
+ if (n_past > 0 && is_interacting) {
591
+ if (params.instruct) {
592
+ printf("\n> ");
593
+ }
594
+
595
+ std::string buffer;
596
+ if (!params.input_prefix.empty()) {
597
+ buffer += params.input_prefix;
598
+ printf("%s", buffer.c_str());
599
+ }
600
+
601
+ std::string line;
602
+ bool another_line = true;
603
+ do {
604
+ another_line = console_readline(con_st, line);
605
+ buffer += line;
606
+ } while (another_line);
607
+
608
+ // done taking input, reset color
609
+ console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
610
+
611
+ // Add tokens to embd only if the input buffer is non-empty
612
+ // Entering a empty line lets the user pass control back
613
+ if (buffer.length() > 1) {
614
+ // append input suffix if any
615
+ if (!params.input_suffix.empty()) {
616
+ buffer += params.input_suffix;
617
+ printf("%s", params.input_suffix.c_str());
618
+ }
619
+
620
+ // instruct mode: insert instruction prefix
621
+ if (params.instruct && !is_antiprompt) {
622
+ n_consumed = embd_inp.size();
623
+ embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
624
+ }
625
+
626
+ auto line_inp = ::llama_tokenize(ctx, buffer, false);
627
+ embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
628
+
629
+ // instruct mode: insert response suffix
630
+ if (params.instruct) {
631
+ embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
632
+ }
633
+
634
+ n_remain -= line_inp.size();
635
+ }
636
+
637
+ input_echo = false; // do not echo this again
638
+ }
639
+
640
+ if (n_past > 0) {
641
+ is_interacting = false;
642
+ }
643
+ }
644
+
645
+ // end of text token
646
+ if (!embd.empty() && embd.back() == llama_token_eos()) {
647
+ if (params.instruct) {
648
+ is_interacting = true;
649
+ } else {
650
+ fprintf(stderr, " [end of text]\n");
651
+ break;
652
+ }
653
+ }
654
+
655
+ // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
656
+ if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
657
+ n_remain = params.n_predict;
658
+ is_interacting = true;
659
+ }
660
+ }
661
+
662
+ if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
663
+ fprintf(stderr, "\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
664
+ llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
665
+ }
666
+
667
+ llama_print_timings(ctx);
668
+ llama_free(ctx);
669
+
670
+ return 0;
671
+ }
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
+