diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 1a068ae75f9..d206f21bbea 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -1,5 +1,20 @@
name: CI
-on: [push, pull_request]
+
+on:
+ workflow_dispatch: # allows manual triggering
+ inputs:
+ create_release:
+ description: 'Create new release'
+ required: true
+ type: boolean
+ push:
+ paths: ['.github/workflows/**', 'CMakeLists.txt', 'Makefile', '**.h', '*.c', '**.cpp']
+ pull_request:
+ types: [opened, synchronize, edited, reopened, review_requested, ready_for_review]
+ paths: ['CMakeLists.txt', 'Makefile', '**.h', '*.c', '**.cpp']
+
+env:
+ BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
jobs:
ubuntu-latest:
@@ -7,46 +22,126 @@ jobs:
steps:
- name: Clone
+ id: checkout
uses: actions/checkout@v1
- name: Dependencies
+ id: depends
run: |
sudo apt-get update
sudo apt-get install build-essential
- name: Build
+ id: make_build
run: |
make
+ - name: Archive production artifacts
+ uses: actions/upload-artifact@v3
+ with:
+ name: ubuntu
+ path: |
+ chat
+
+
macOS-latest:
runs-on: macOS-latest
steps:
- name: Clone
+ id: checkout
uses: actions/checkout@v1
- name: Dependencies
+ id: depends
run: |
brew update
- name: Build
+ id: make_build
run: |
make
+ - name: Archive production artifacts
+ uses: actions/upload-artifact@v3
+ with:
+ name: macos
+ path: |
+ chat
+
+ # macos-arm64:
+ # runs-on: macos-arm64
+
+ # steps:
+ # - name: Clone
+ # id: checkout
+ # uses: actions/checkout@v1
+
+ # - name: Dependencies
+ # id: depends
+ # run: |
+ # brew update
+
+ # - name: Build
+ # id: make_build
+ # run: |
+ # make
+
+ # - name: Archive production artifacts
+ # uses: actions/upload-artifact@v3
+ # with:
+ # name: macos
+ # path: |
+ # chat
+
windows-latest:
runs-on: windows-latest
steps:
- name: Clone
+ id: checkout
uses: actions/checkout@v1
- name: Build
+ id: cmake_build
run: |
mkdir build
cd build
cmake ..
cmake --build . --config Release
+ - name: Set commit hash variables
+ id: commit
+ if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) || github.event.inputs.create_release == 'true' }}
+ uses: pr-mpt/actions-commit-hash@v2
+
+ - name: Pack artifacts
+ id: pack_artifacts
+ if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) || github.event.inputs.create_release == 'true' }}
+ run: |
+ 7z a alpaca-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-x64.zip .\build\Release\*
+
+ - name: Create release
+ id: create_release
+ if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) || github.event.inputs.create_release == 'true' }}
+ uses: zendesk/action-create-release@v1
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ tag_name: ${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}
+
+ - name: Upload release
+ id: upload_release
+ if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) || github.event.inputs.create_release == 'true' }}
+ uses: actions/upload-release-asset@v1
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ upload_url: ${{ steps.create_release.outputs.upload_url }}
+ asset_path: .\alpaca-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-x64.zip
+ asset_name: alpaca-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-x64.zip
+ asset_content_type: application/octet-stream
+
# ubuntu-latest-gcc:
# runs-on: ubuntu-latest
#
diff --git a/.gitignore b/.gitignore
index 5eb1ff1b873..da9e6bed800 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
+/chat
+
*.o
*.a
.cache/
@@ -15,9 +17,22 @@ build-sanitize-addr/
build-sanitize-thread/
models/*
+*.bin
/main
/quantize
arm_neon.h
compile_commands.json
+
+# Windows CMake files
+*.vcxproj
+*.filters
+*.cmake
+*.sln
+x64/
+Debug/
+Release/
+CMakeFiles/
+CMakeCache.txt
+*.dir/
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ca3be38a557..48c7c4fa350 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.8)
-project("llama.cpp")
+project("alpaca.cpp")
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED true)
@@ -104,8 +104,8 @@ endif()
# set(LLAMA_EXTRA_FLAGS ${LLAMA_EXTRA_FLAGS} -DGGML_PERF)
# endif()
-add_executable(llama
- main.cpp
+add_executable(chat
+ chat.cpp
utils.cpp
utils.h)
@@ -119,10 +119,10 @@ add_library(ggml
ggml.h)
target_compile_definitions(ggml PUBLIC ${LLAMA_EXTRA_FLAGS})
-target_compile_definitions(llama PUBLIC ${LLAMA_EXTRA_FLAGS})
+target_compile_definitions(chat PUBLIC ${LLAMA_EXTRA_FLAGS})
target_compile_definitions(quantize PUBLIC ${LLAMA_EXTRA_FLAGS})
target_link_libraries(ggml PRIVATE ${LLAMA_EXTRA_LIBS})
target_include_directories(ggml PUBLIC .)
target_link_libraries(quantize PRIVATE ggml)
-target_link_libraries(llama PRIVATE ggml)
+target_link_libraries(chat PRIVATE ggml)
diff --git a/Makefile b/Makefile
index 1601079a486..fb83d41badc 100644
--- a/Makefile
+++ b/Makefile
@@ -176,7 +176,7 @@ $(info I CC: $(CCV))
$(info I CXX: $(CXXV))
$(info )
-default: main quantize
+default: chat quantize
#
# Build library
@@ -191,9 +191,9 @@ utils.o: utils.cpp utils.h
clean:
rm -f *.o main quantize
-main: main.cpp ggml.o utils.o
- $(CXX) $(CXXFLAGS) main.cpp ggml.o utils.o -o main $(LDFLAGS)
- ./main -h
+chat: chat.cpp ggml.o utils.o
+ $(CXX) $(CXXFLAGS) chat.cpp ggml.o utils.o -o chat $(LDFLAGS)
+
quantize: quantize.cpp ggml.o utils.o
$(CXX) $(CXXFLAGS) quantize.cpp ggml.o utils.o -o quantize $(LDFLAGS)
diff --git a/README.md b/README.md
index 1f7e19412f5..d7358dad076 100644
--- a/README.md
+++ b/README.md
@@ -1,223 +1,78 @@
-# llama.cpp
-
-[](https://github.com/ggerganov/llama.cpp/actions)
-[](https://opensource.org/licenses/MIT)
-
-Inference of [LLaMA](https://arxiv.org/abs/2302.13971) model in pure C/C++
-
-**Hot topics:**
-
-- Cache input prompts for faster initialization: https://github.com/ggerganov/llama.cpp/issues/64
-- Create a `llama.cpp` logo: https://github.com/ggerganov/llama.cpp/issues/105
-
-## Description
-
-The main goal is to run the model using 4-bit quantization on a MacBook
-
-- Plain C/C++ implementation without dependencies
-- Apple silicon first-class citizen - optimized via ARM NEON
-- AVX2 support for x86 architectures
-- Mixed F16 / F32 precision
-- 4-bit quantization support
-- Runs on the CPU
-
-This was [hacked in an evening](https://github.com/ggerganov/llama.cpp/issues/33#issuecomment-1465108022) - I have no idea if it works correctly.
-Please do not make conclusions about the models based on the results from this implementation.
-For all I know, it can be completely wrong. This project is for educational purposes.
-New features will probably be added mostly through community contributions.
-
-Supported platforms:
-
-- [X] Mac OS
-- [X] Linux
-- [X] Windows (via CMake)
-
----
-
-Here is a typical run using LLaMA-7B:
-
-```java
-make -j && ./main -m ./models/7B/ggml-model-q4_0.bin -p "Building a website can be done in 10 simple steps:" -t 8 -n 512
-I llama.cpp build info:
-I UNAME_S: Darwin
-I UNAME_P: arm
-I UNAME_M: arm64
-I CFLAGS: -I. -O3 -DNDEBUG -std=c11 -fPIC -pthread -DGGML_USE_ACCELERATE
-I CXXFLAGS: -I. -I./examples -O3 -DNDEBUG -std=c++11 -fPIC -pthread
-I LDFLAGS: -framework Accelerate
-I CC: Apple clang version 14.0.0 (clang-1400.0.29.202)
-I CXX: Apple clang version 14.0.0 (clang-1400.0.29.202)
-
-make: Nothing to be done for `default'.
-main: seed = 1678486056
-llama_model_load: loading model from './models/7B/ggml-model-q4_0.bin' - please wait ...
-llama_model_load: n_vocab = 32000
-llama_model_load: n_ctx = 512
-llama_model_load: n_embd = 4096
-llama_model_load: n_mult = 256
-llama_model_load: n_head = 32
-llama_model_load: n_layer = 32
-llama_model_load: n_rot = 128
-llama_model_load: f16 = 2
-llama_model_load: n_ff = 11008
-llama_model_load: ggml ctx size = 4529.34 MB
-llama_model_load: memory_size = 512.00 MB, n_mem = 16384
-llama_model_load: .................................... done
-llama_model_load: model size = 4017.27 MB / num tensors = 291
-
-main: prompt: 'Building a website can be done in 10 simple steps:'
-main: number of tokens in prompt = 15
- 1 -> ''
- 8893 -> 'Build'
- 292 -> 'ing'
- 263 -> ' a'
- 4700 -> ' website'
- 508 -> ' can'
- 367 -> ' be'
- 2309 -> ' done'
- 297 -> ' in'
- 29871 -> ' '
- 29896 -> '1'
- 29900 -> '0'
- 2560 -> ' simple'
- 6576 -> ' steps'
- 29901 -> ':'
-
-sampling parameters: temp = 0.800000, top_k = 40, top_p = 0.950000
-
-
-Building a website can be done in 10 simple steps:
-1) Select a domain name and web hosting plan
-2) Complete a sitemap
-3) List your products
-4) Write product descriptions
-5) Create a user account
-6) Build the template
-7) Start building the website
-8) Advertise the website
-9) Provide email support
-10) Submit the website to search engines
-A website is a collection of web pages that are formatted with HTML. HTML is the code that defines what the website looks like and how it behaves.
-The HTML code is formatted into a template or a format. Once this is done, it is displayed on the user's browser.
-The web pages are stored in a web server. The web server is also called a host. When the website is accessed, it is retrieved from the server and displayed on the user's computer.
-A website is known as a website when it is hosted. This means that it is displayed on a host. The host is usually a web server.
-A website can be displayed on different browsers. The browsers are basically the software that renders the website on the user's screen.
-A website can also be viewed on different devices such as desktops, tablets and smartphones.
-Hence, to have a website displayed on a browser, the website must be hosted.
-A domain name is an address of a website. It is the name of the website.
-The website is known as a website when it is hosted. This means that it is displayed on a host. The host is usually a web server.
-A website can be displayed on different browsers. The browsers are basically the software that renders the website on the user’s screen.
-A website can also be viewed on different devices such as desktops, tablets and smartphones. Hence, to have a website displayed on a browser, the website must be hosted.
-A domain name is an address of a website. It is the name of the website.
-A website is an address of a website. It is a collection of web pages that are formatted with HTML. HTML is the code that defines what the website looks like and how it behaves.
-The HTML code is formatted into a template or a format. Once this is done, it is displayed on the user’s browser.
-A website is known as a website when it is hosted
-
-main: mem per token = 14434244 bytes
-main: load time = 1332.48 ms
-main: sample time = 1081.40 ms
-main: predict time = 31378.77 ms / 61.41 ms per token
-main: total time = 34036.74 ms
-```
-
-And here is another demo of running both LLaMA-7B and [whisper.cpp](https://github.com/ggerganov/whisper.cpp) on a single M1 Pro MacBook:
-
-https://user-images.githubusercontent.com/1991296/224442907-7693d4be-acaa-4e01-8b4f-add84093ffff.mp4
+# Alpaca.cpp
-## Usage
+Run a fast ChatGPT-like model locally on your device. The screencast below is not sped up and running on an M2 Macbook Air with 4GB of weights.
-Here are the step for the LLaMA-7B model:
-```bash
-# build this repo
-git clone https://github.com/ggerganov/llama.cpp
-cd llama.cpp
-make
+[](https://asciinema.org/a/dfJ8QXZ4u978Ona59LPEldtKK)
-# obtain the original LLaMA model weights and place them in ./models
-ls ./models
-65B 30B 13B 7B tokenizer_checklist.chk tokenizer.model
-# install Python dependencies
-python3 -m pip install torch numpy sentencepiece
+This combines the [LLaMA foundation model](https://github.com/facebookresearch/llama) with an [open reproduction](https://github.com/tloen/alpaca-lora) of [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca) a fine-tuning of the base model to obey instructions (akin to the [RLHF](https://huggingface.co/blog/rlhf) used to train ChatGPT) and a set of modifications to [llama.cpp](https://github.com/ggerganov/llama.cpp) to add a chat interface.
-# convert the 7B model to ggml FP16 format
-python3 convert-pth-to-ggml.py models/7B/ 1
+## Get started
-# quantize the model to 4-bits
-./quantize.sh 7B
+```sh
+git clone https://github.com/antimatter15/alpaca.cpp
+cd alpaca.cpp
-# run the inference
-./main -m ./models/7B/ggml-model-q4_0.bin -t 8 -n 128
+make chat
+./chat
```
-When running the larger models, make sure you have enough disk space to store all the intermediate files.
+You can download the weights for `ggml-alpaca-7b-q4.bin` with BitTorrent `magnet:?xt=urn:btih:5aaceaec63b03e51a98f04fd5c42320b2a033010&dn=ggml-alpaca-7b-q4.bin&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337%2Fannounce&tr=udp%3A%2F%2Fopentracker.i2p.rocks%3A6969%2Fannounce`
-TODO: add model disk/mem requirements
-### Interactive mode
+Alternatively you can download them with IPFS.
-If you want a more ChatGPT-like experience, you can run in interactive mode by passing `-i` as a parameter.
-In this mode, you can always interrupt generation by pressing Ctrl+C and enter one or more lines of text which will be converted into tokens and appended to the current context. You can also specify a *reverse prompt* with the parameter `-r "reverse prompt string"`. This will result in user input being prompted whenever the exact tokens of the reverse prompt string are encountered in the generation. A typical use is to use a prompt which makes LLaMa emulate a chat between multiple users, say Alice and Bob, and pass `-r "Alice:"`.
-
-Here is an example few-shot interaction, invoked with the command
```
-./main -m ./models/13B/ggml-model-q4_0.bin -t 8 -n 256 --repeat_penalty 1.0 --color -i -r "User:" \
- -p \
-"Transcript of a dialog, where the User interacts with an Assistant named Bob. Bob is helpful, kind, honest, good at writing, and never fails to answer the User's requests immediately and with precision.
+# any of these will work
+curl -o ggml-alpaca-7b-q4.bin -C - https://gateway.estuary.tech/gw/ipfs/QmQ1bf2BTnYxq73MFJWu1B7bQ2UD6qG7D7YDCxhTndVkPC
+curl -o ggml-alpaca-7b-q4.bin -C - https://ipfs.io/ipfs/QmQ1bf2BTnYxq73MFJWu1B7bQ2UD6qG7D7YDCxhTndVkPC
+curl -o ggml-alpaca-7b-q4.bin -C - https://cloudflare-ipfs.com/ipfs/QmQ1bf2BTnYxq73MFJWu1B7bQ2UD6qG7D7YDCxhTndVkPC
+```
-User: Hello, Bob.
-Bob: Hello. How may I help you today?
-User: Please tell me the largest city in Europe.
-Bob: Sure. The largest city in Europe is Moscow, the capital of Russia.
-User:"
+Save the `ggml-alpaca-7b-q4.bin` file in the same directory as your `./chat` executable.
-```
-Note the use of `--color` to distinguish between user input and generated text.
+The weights are based on the published fine-tunes from `alpaca-lora`, converted back into a pytorch checkpoint with a [modified script](https://github.com/tloen/alpaca-lora/pull/19) and then quantized with llama.cpp the regular way.
-
+## Windows Setup
-### Android
+- Download and install CMake:
+- Download and install `git`. If you've never used git before, consider a GUI client like
+- Clone this repo using your git client of choice (for GitHub Desktop, go to File -> Clone repository -> From URL and paste `https://github.com/antimatter15/alpaca.cpp` in as the URL)
+- Open a Windows Terminal inside the folder you cloned the repository to
+- Run the following commands one by one:
-You can easily run `llama.cpp` on Android device with [termux](https://play.google.com/store/apps/details?id=com.termux).
-First, obtain the [Android NDK](https://developer.android.com/ndk) and then build with CMake:
+```ps1
+cmake .
+cmake --build . --config Release
```
-$ mkdir build-android
-$ cd build-android
-$ export NDK=
-$ cmake -DCMAKE_TOOLCHAIN_FILE=$NDK/build/cmake/android.toolchain.cmake -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-23 -DCMAKE_C_FLAGS=-march=armv8.4a+dotprod ..
-$ make
+
+- Download the weights via any of the links in "Get started" above, and save the file as `ggml-alpaca-7b-q4.bin` in the main Alpaca directory.
+- In the terminal window, run this command:
+```ps1
+.\Release\chat.exe
```
-Install [termux](https://play.google.com/store/apps/details?id=com.termux) on your device and run `termux-setup-storage` to get access to your SD card.
-Finally, copy the `llama` binary and the model files to your device storage. Here is a demo of an interactive session running on Pixel 5 phone:
+- (You can add other launch options like `--n 8` as preferred onto the same line)
+- You can now type to the AI in the terminal and it will reply. Enjoy!
+
+## 13B
+
+TODO: write more docs here (PRs welcome)
-https://user-images.githubusercontent.com/271616/225014776-1d567049-ad71-4ef2-b050-55b0b3b9274c.mp4
+Torrent: `magnet:?xt=urn:btih:053b3d54d2e77ff020ebddf51dad681f2a651071&dn=ggml-alpaca-13b-q4.bin&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337%2Fannounce&tr=udp%3A%2F%2Fopentracker.i2p.rocks%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A6969%2Fannounce&tr=udp%3A%2F%2F9.rarbg.com%3A2810%2Fannounce`
-## Limitations
+```
+./chat -m ggml-alpaca-13b-q4.bin
+```
-- We don't know yet how much the quantization affects the quality of the generated text
-- Probably the token sampling can be improved
-- The Accelerate framework is actually currently unused since I found that for tensor shapes typical for the Decoder,
- there is no benefit compared to the ARM_NEON intrinsics implementation. Of course, it's possible that I simply don't
- know how to utilize it properly. But in any case, you can even disable it with `LLAMA_NO_ACCELERATE=1 make` and the
- performance will be the same, since no BLAS calls are invoked by the current implementation
+## Credit
-### Contributing
+This combines [Facebook's LLaMA](https://github.com/facebookresearch/llama), [Stanford Alpaca](https://crfm.stanford.edu/2023/03/13/alpaca.html), [alpaca-lora](https://github.com/tloen/alpaca-lora) and [corresponding weights](https://huggingface.co/tloen/alpaca-lora-7b/tree/main) by Eric Wang (which uses [Jason Phang's implementation of LLaMA](https://github.com/huggingface/transformers/pull/21955) on top of Hugging Face Transformers), and [llama.cpp](https://github.com/ggerganov/llama.cpp) by Georgi Gerganov. The chat implementation is based on Matvey Soloviev's [Interactive Mode](https://github.com/ggerganov/llama.cpp/pull/61) for llama.cpp. Inspired by [Simon Willison's](https://til.simonwillison.net/llms/llama-7b-m2) getting started guide for LLaMA. [Andy Matuschak](https://twitter.com/andy_matuschak/status/1636769182066053120)'s thread on adapting this to 13B, using fine tuning weights by [Sam Witteveen](https://huggingface.co/samwit/alpaca13B-lora).
-- Contributors can open PRs
-- Collaborators can push to branches in the `llama.cpp` repo
-- Collaborators will be invited based on contributions
-### Coding guidelines
+## Disclaimer
-- Avoid adding third-party dependencies, extra files, extra headers, etc.
-- Always consider cross-compatibility with other operating systems and architectures
-- Avoid fancy looking modern STL constructs, use basic `for` loops, avoid templates, keep it simple
-- There are no strict rules for the code style, but try to follow the patterns in the code (indentation, spaces, etc.). Vertical alignment makes things more readable and easier to batch edit
-- Clean-up any trailing whitespaces, use 4 spaces indentation, brackets on same line, `void * ptr`, `int & a`
-- See [good first issues](https://github.com/ggerganov/llama.cpp/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) for tasks suitable for first contributions
+Note that the model weights are only to be used for research purposes, as they are derivative of LLaMA, and uses the published instruction data from the Stanford Alpaca project which is generated by OpenAI, which itself disallows the usage of its outputs to train competing models.
-### Misc
-- Practice your C++ typing skills: https://typing-battles.ggerganov.com
diff --git a/main.cpp b/chat.cpp
similarity index 88%
rename from main.cpp
rename to chat.cpp
index ca0fca8b364..38b39771ad9 100644
--- a/main.cpp
+++ b/chat.cpp
@@ -16,6 +16,7 @@
#include
#elif defined (_WIN32)
#include
+#include
#endif
#define ANSI_COLOR_RED "\x1b[31m"
@@ -30,7 +31,7 @@
// determine number of model parts based on the dimension
static const std::map LLAMA_N_PARTS = {
{ 4096, 1 },
- { 5120, 2 },
+ { 5120, 1 },
{ 6656, 4 },
{ 8192, 8 },
};
@@ -129,16 +130,16 @@ bool llama_model_load(const std::string & fname, llama_model & model, gpt_vocab
n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
n_parts = LLAMA_N_PARTS.at(hparams.n_embd);
- fprintf(stderr, "%s: n_vocab = %d\n", __func__, hparams.n_vocab);
- fprintf(stderr, "%s: n_ctx = %d\n", __func__, hparams.n_ctx);
- fprintf(stderr, "%s: n_embd = %d\n", __func__, hparams.n_embd);
- fprintf(stderr, "%s: n_mult = %d\n", __func__, hparams.n_mult);
- fprintf(stderr, "%s: n_head = %d\n", __func__, hparams.n_head);
- fprintf(stderr, "%s: n_layer = %d\n", __func__, hparams.n_layer);
- fprintf(stderr, "%s: n_rot = %d\n", __func__, hparams.n_rot);
- fprintf(stderr, "%s: f16 = %d\n", __func__, hparams.f16);
- fprintf(stderr, "%s: n_ff = %d\n", __func__, n_ff);
- fprintf(stderr, "%s: n_parts = %d\n", __func__, n_parts);
+ // fprintf(stderr, "%s: n_vocab = %d\n", __func__, hparams.n_vocab);
+ // fprintf(stderr, "%s: n_ctx = %d\n", __func__, hparams.n_ctx);
+ // fprintf(stderr, "%s: n_embd = %d\n", __func__, hparams.n_embd);
+ // fprintf(stderr, "%s: n_mult = %d\n", __func__, hparams.n_mult);
+ // fprintf(stderr, "%s: n_head = %d\n", __func__, hparams.n_head);
+ // fprintf(stderr, "%s: n_layer = %d\n", __func__, hparams.n_layer);
+ // fprintf(stderr, "%s: n_rot = %d\n", __func__, hparams.n_rot);
+ // fprintf(stderr, "%s: f16 = %d\n", __func__, hparams.f16);
+ // fprintf(stderr, "%s: n_ff = %d\n", __func__, n_ff);
+ // fprintf(stderr, "%s: n_parts = %d\n", __func__, n_parts);
}
// load vocab
@@ -795,7 +796,14 @@ int main(int argc, char ** argv) {
const int64_t t_main_start_us = ggml_time_us();
gpt_params params;
- params.model = "models/llama-7B/ggml-model.bin";
+
+ params.temp = 0.1f;
+ params.top_p = 0.95f;
+ params.n_ctx = 2048;
+ params.interactive = true;
+ params.interactive_start = true;
+ params.use_color = true;
+ params.model = "ggml-alpaca-7b-q4.bin";
if (gpt_params_parse(argc, argv, params) == false) {
return 1;
@@ -808,9 +816,9 @@ int main(int argc, char ** argv) {
fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
std::mt19937 rng(params.seed);
- if (params.prompt.empty()) {
- params.prompt = gpt_random_prompt(rng);
- }
+ // if (params.prompt.empty()) {
+ // params.prompt = gpt_random_prompt(rng);
+ // }
// params.prompt = R"(// this function checks if the number n is prime
//bool is_prime(int n) {)";
@@ -845,21 +853,31 @@ int main(int argc, char ** argv) {
std::vector logits;
+ // Add a space in front of the first character to match OG llama tokenizer behavior
+ // params.prompt.insert(0, 1, ' ');
// tokenize the prompt
- std::vector embd_inp = ::llama_tokenize(vocab, params.prompt, true);
+ std::vector embd_inp;// = ::llama_tokenize(vocab, params.prompt, true);
- params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
+ // params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
+
+ // // tokenize the reverse prompt
+ // std::vector antiprompt_inp = ::llama_tokenize(vocab, params.antiprompt, false);
+
+ // fprintf(stderr, "\n");
+ // fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
+ // fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
+ // for (int i = 0; i < (int) embd_inp.size(); i++) {
+ // fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], vocab.id_to_token.at(embd_inp[i]).c_str());
+ // }
+ // fprintf(stderr, "\n");
+
+ std::vector instruct_inp = ::llama_tokenize(vocab, " Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n", true);
+ std::vector prompt_inp = ::llama_tokenize(vocab, "### Instruction:\n\n", true);
+ std::vector response_inp = ::llama_tokenize(vocab, "### Response:\n\n", false);
+
+ embd_inp.insert(embd_inp.end(), instruct_inp.begin(), instruct_inp.end());
- // tokenize the reverse prompt
- std::vector antiprompt_inp = ::llama_tokenize(vocab, params.antiprompt, false);
- fprintf(stderr, "\n");
- fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
- fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
- for (int i = 0; i < (int) embd_inp.size(); i++) {
- fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], vocab.id_to_token.at(embd_inp[i]).c_str());
- }
- fprintf(stderr, "\n");
if (params.interactive) {
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
struct sigaction sigint_action;
@@ -869,18 +887,24 @@ int main(int argc, char ** argv) {
sigaction(SIGINT, &sigint_action, NULL);
#elif defined (_WIN32)
signal(SIGINT, sigint_handler);
+
+ // Windows console ANSI color fix
+ DWORD mode = 0;
+ HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
+ if (hConsole && hConsole != INVALID_HANDLE_VALUE && GetConsoleMode(hConsole, &mode))
+ SetConsoleMode(hConsole, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
fprintf(stderr, "%s: interactive mode on.\n", __func__);
- if(antiprompt_inp.size()) {
- fprintf(stderr, "%s: reverse prompt: '%s'\n", __func__, params.antiprompt.c_str());
- fprintf(stderr, "%s: number of tokens in reverse prompt = %zu\n", __func__, antiprompt_inp.size());
- for (int i = 0; i < (int) antiprompt_inp.size(); i++) {
- fprintf(stderr, "%6d -> '%s'\n", antiprompt_inp[i], vocab.id_to_token.at(antiprompt_inp[i]).c_str());
- }
- fprintf(stderr, "\n");
- }
+ // if(antiprompt_inp.size()) {
+ // fprintf(stderr, "%s: reverse prompt: '%s'\n", __func__, params.antiprompt.c_str());
+ // fprintf(stderr, "%s: number of tokens in reverse prompt = %zu\n", __func__, antiprompt_inp.size());
+ // for (int i = 0; i < (int) antiprompt_inp.size(); i++) {
+ // fprintf(stderr, "%6d -> '%s'\n", antiprompt_inp[i], vocab.id_to_token.at(antiprompt_inp[i]).c_str());
+ // }
+ // fprintf(stderr, "\n");
+ // }
}
fprintf(stderr, "sampling parameters: temp = %f, top_k = %d, top_p = %f, repeat_last_n = %i, repeat_penalty = %f\n", params.temp, params.top_k, params.top_p, params.repeat_last_n, params.repeat_penalty);
fprintf(stderr, "\n\n");
@@ -897,17 +921,18 @@ int main(int argc, char ** argv) {
if (params.interactive) {
- fprintf(stderr, "== Running in interactive mode. ==\n"
+ fprintf(stderr, "== Running in chat mode. ==\n"
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
" - Press Ctrl+C to interject at any time.\n"
#endif
- " - Press Return to return control to LLaMa.\n"
+ " - Press Return to return control to LLaMA.\n"
" - If you want to submit another line, end your input in '\\'.\n");
}
- int remaining_tokens = params.n_predict;
+ // we may want to slide the input window along with the context, but for now we restrict to the context length
+ int remaining_tokens = model.hparams.n_ctx - embd_inp.size();
int input_consumed = 0;
- bool input_noecho = false;
+ bool input_noecho = true;
// prompt user immediately after the starting prompt has been loaded
if (params.interactive_start) {
@@ -919,6 +944,8 @@ int main(int argc, char ** argv) {
printf(ANSI_COLOR_YELLOW);
}
+
+
while (remaining_tokens > 0) {
// predict
if (embd.size() > 0) {
@@ -935,7 +962,7 @@ int main(int argc, char ** argv) {
n_past += embd.size();
embd.clear();
- if (embd_inp.size() <= input_consumed) {
+ if (embd_inp.size() <= input_consumed && !is_interacting) {
// out of user input, sample next token
const float top_k = params.top_k;
const float top_p = params.top_p;
@@ -968,6 +995,8 @@ int main(int argc, char ** argv) {
} else {
// some user input remains from prompt or interaction, forward it to processing
while (embd_inp.size() > input_consumed) {
+ // fprintf(stderr, "%6d -> '%s'\n", embd_inp[input_consumed], vocab.id_to_token.at(embd_inp[input_consumed]).c_str());
+
embd.push_back(embd_inp[input_consumed]);
last_n_tokens.erase(last_n_tokens.begin());
last_n_tokens.push_back(embd_inp[input_consumed]);
@@ -995,11 +1024,19 @@ int main(int argc, char ** argv) {
// check if we should prompt the user for more
if (params.interactive && embd_inp.size() <= input_consumed) {
// check for reverse prompt
- if (antiprompt_inp.size() && std::equal(antiprompt_inp.rbegin(), antiprompt_inp.rend(), last_n_tokens.rbegin())) {
- // reverse prompt found
- is_interacting = true;
- }
+ // if (antiprompt_inp.size() && std::equal(antiprompt_inp.rbegin(), antiprompt_inp.rend(), last_n_tokens.rbegin())) {
+ // // reverse prompt found
+ // is_interacting = true;
+ // }
if (is_interacting) {
+ // input_consumed = 0;
+ // embd_inp.erase(embd_inp.begin());
+ input_consumed = embd_inp.size();
+ embd_inp.insert(embd_inp.end(), prompt_inp.begin(), prompt_inp.end());
+
+
+ printf("\n> ");
+
// currently being interactive
bool another_line=true;
while (another_line) {
@@ -1009,7 +1046,7 @@ int main(int argc, char ** argv) {
if(params.use_color) printf(ANSI_BOLD ANSI_COLOR_GREEN);
if (scanf("%255[^\n]%n%*c", buf, &n_read) <= 0) {
// presumable empty line, consume the newline
- scanf("%*c");
+ if (scanf("%*c") <= 0) { /*ignore*/ }
n_read=0;
}
if(params.use_color) printf(ANSI_COLOR_RESET);
@@ -1026,8 +1063,9 @@ int main(int argc, char ** argv) {
std::vector line_inp = ::llama_tokenize(vocab, buf, false);
embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
+ embd_inp.insert(embd_inp.end(), response_inp.begin(), response_inp.end());
- remaining_tokens -= line_inp.size();
+ remaining_tokens -= prompt_inp.size() + line_inp.size() + response_inp.size();
input_noecho = true; // do not echo this again
}
@@ -1038,8 +1076,9 @@ int main(int argc, char ** argv) {
// end of text token
if (embd.back() == 2) {
- fprintf(stderr, " [end of text]\n");
- break;
+ // fprintf(stderr, " [end of text]\n");
+ is_interacting = true;
+ continue;
}
}
diff --git a/screencast.gif b/screencast.gif
new file mode 100644
index 00000000000..7792f1622d0
Binary files /dev/null and b/screencast.gif differ
diff --git a/utils.cpp b/utils.cpp
index aa3ad1053da..d739b5d4892 100644
--- a/utils.cpp
+++ b/utils.cpp
@@ -275,41 +275,57 @@ std::vector gpt_tokenize(const gpt_vocab & vocab, const std::stri
return tokens;
}
+// TODO: Calculate this constant from the vocabulary
+#define MAX_TOKEN_LEN 18
+// SentencePiece implementation after https://guillaume-be.github.io/2020-05-30/sentence_piece
std::vector llama_tokenize(const gpt_vocab & vocab, const std::string & text, bool bos) {
- //auto res = gpt_tokenize(vocab, text);
-
- //if (bos) {
- // res.insert(res.begin(), 1); // TODO: replace with vocab.bos
- //}
-
std::vector res;
-
- if (bos) {
- res.push_back(1); // TODO: replace with vocab.bos
- }
-
- //find the longest token that matches the text
- int pos = 0;
- while (true) {
- int l = 0;
- int t = 0;
- for (const auto & kv : vocab.id_to_token) {
- if (kv.second.size() < l) continue;
- if (kv.second.size() > text.size() - pos) continue;
- if (text.substr(pos, kv.second.size()) == kv.second) {
- l = kv.second.size();
- t = kv.first;
+ std::vector score;
+ std::vector prev;
+ int len = text.length();
+
+ score.resize(len + 1);
+ prev.resize(len + 1);
+
+ // Forward pass
+ for (int i = 0; i < len; i++) {
+ int max_len = std::min(len - i, MAX_TOKEN_LEN);
+ for (int sub_len = 1; sub_len <= len - i; sub_len++) {
+ auto sub = text.substr(i, sub_len);
+ auto token = vocab.token_to_id.find(sub);
+ if (token != vocab.token_to_id.end()) {
+ int token_score = sub.length() * sub.length();
+ int local_score = score[i] + token_score;
+ int next = i + sub_len;
+ if (score[next] < local_score) {
+ score[next] = local_score;
+ prev[next] = (*token).second;
+ }
}
}
+ }
- if (l == 0) {
- break;
+ // Backward pass
+ int i = len;
+ while (i > 0) {
+ gpt_vocab::id token_id = prev[i];
+ if (token_id == 0) {
+ // TODO: Return error or something more meaningful
+ printf("failed to tokenize string!\n");
+ break;
}
+ res.push_back(token_id);
+ auto token = (*vocab.id_to_token.find(token_id)).second;
+ i -= token.length();
+ }
- res.push_back(t);
- pos += l;
+ if (bos) {
+ res.push_back(1); // TODO: replace with vocab.bos
}
+ // Pieces are in reverse order so correct that
+ std::reverse(res.begin(), res.end());
+
return res;
}