goavinash5 commited on
Commit
e97665c
1 Parent(s): a575d7a

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env +28 -0
  2. .gitattributes +1 -0
  3. .github/workflows/branch.yml +60 -0
  4. .github/workflows/release.yml +30 -0
  5. .github/workflows/update_space.yml +28 -0
  6. .gitignore +10 -0
  7. CONTRIBUTING.md +90 -0
  8. LICENSE +21 -0
  9. README.md +379 -8
  10. app.py +418 -0
  11. benchmark.py +145 -0
  12. code_completion.py +216 -0
  13. colab/Llama_2_7b_Chat_GPTQ.ipynb +0 -0
  14. colab/ggmlv3_q4_0.ipynb +109 -0
  15. colab/webui_CodeLlama_7B_Instruct_GPTQ.ipynb +514 -0
  16. docs/issues.md +0 -0
  17. docs/news.md +38 -0
  18. docs/performance.md +32 -0
  19. docs/pypi.md +187 -0
  20. env_examples/.env.13b_example +13 -0
  21. env_examples/.env.7b_8bit_example +13 -0
  22. env_examples/.env.7b_ggmlv3_q4_0_example +18 -0
  23. env_examples/.env.7b_gptq_example +18 -0
  24. llama2_wrapper/__init__.py +1 -0
  25. llama2_wrapper/__pycache__/__init__.cpython-310.pyc +0 -0
  26. llama2_wrapper/__pycache__/model.cpython-310.pyc +0 -0
  27. llama2_wrapper/__pycache__/types.cpython-310.pyc +0 -0
  28. llama2_wrapper/download/__init__.py +0 -0
  29. llama2_wrapper/download/__main__.py +59 -0
  30. llama2_wrapper/download/__pycache__/__init__.cpython-310.pyc +0 -0
  31. llama2_wrapper/download/__pycache__/__main__.cpython-310.pyc +0 -0
  32. llama2_wrapper/model.py +787 -0
  33. llama2_wrapper/server/__init__.py +0 -0
  34. llama2_wrapper/server/__main__.py +46 -0
  35. llama2_wrapper/server/__pycache__/__init__.cpython-310.pyc +0 -0
  36. llama2_wrapper/server/__pycache__/__main__.cpython-310.pyc +0 -0
  37. llama2_wrapper/server/__pycache__/app.cpython-310.pyc +0 -0
  38. llama2_wrapper/server/app.py +526 -0
  39. llama2_wrapper/types.py +115 -0
  40. models/CodeLlama-7B-Python-GPTQ/.gitattributes +35 -0
  41. models/CodeLlama-7B-Python-GPTQ/LICENSE +1 -0
  42. models/CodeLlama-7B-Python-GPTQ/LICENSE.txt +126 -0
  43. models/CodeLlama-7B-Python-GPTQ/Notice +1 -0
  44. models/CodeLlama-7B-Python-GPTQ/README.md +338 -0
  45. models/CodeLlama-7B-Python-GPTQ/USE_POLICY.md +50 -0
  46. models/CodeLlama-7B-Python-GPTQ/config.json +43 -0
  47. models/CodeLlama-7B-Python-GPTQ/configuration_llama.py +176 -0
  48. models/CodeLlama-7B-Python-GPTQ/generation_config.json +7 -0
  49. models/CodeLlama-7B-Python-GPTQ/modeling_llama.py +1020 -0
  50. models/CodeLlama-7B-Python-GPTQ/quantize_config.json +10 -0
.env ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL_PATH = ""
2
+ # if MODEL_PATH is "", default llama.cpp/gptq models
3
+ # will be downloaded to: ./models
4
+
5
+ # Example ggml path:
6
+ # MODEL_PATH = "./models/llama-2-7b-chat.ggmlv3.q4_0.bin"
7
+ # MODEL_PATH = "./models/Llama-2-7b-Chat-GPTQ"
8
+
9
+ # options: llama.cpp, gptq, transformers
10
+ BACKEND_TYPE = "llama.cpp"
11
+
12
+ # only for transformers bitsandbytes 8 bit
13
+ LOAD_IN_8BIT = False
14
+
15
+ MAX_MAX_NEW_TOKENS = 2048
16
+ DEFAULT_MAX_NEW_TOKENS = 1024
17
+ MAX_INPUT_TOKEN_LENGTH = 4000
18
+
19
+ DEFAULT_SYSTEM_PROMPT = "
20
+ You are a movie recommender chatbot. You give movie recommendations to users based on their profile. Your job now is to fully understand the user profile based on the given context and give them recommendations based on their input. Here are some rules for you to follow while generating a response:
21
+ 1: Give an explanation for why each of the recommendations is a good fit for the user
22
+ 2: Give a maximum of 5 recommendations, unless specified otherwise by the user
23
+ 3: Give a predicted rating for the movie on a scale of 1 to 5: this is a rating the user would give to the movie if they watched it
24
+ 4: Mention how popular the movie is. Choose from among High, Medium, Low: High being most popular, Low being least
25
+ 5: Avoid recommending movies already rated by the user
26
+
27
+ ''' User Context '''
28
+ "
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/llama-2-7b-chat.Q4_0.gguf filter=lfs diff=lfs merge=lfs -text
.github/workflows/branch.yml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Push
2
+ on: [push]
3
+
4
+ jobs:
5
+ test:
6
+ strategy:
7
+ fail-fast: false
8
+ matrix:
9
+ python-version: ['3.10']
10
+ poetry-version: ['1.5.1']
11
+ os: [ubuntu-latest]
12
+ runs-on: ${{ matrix.os }}
13
+ steps:
14
+ - uses: actions/checkout@v3
15
+ - uses: actions/setup-python@v3
16
+ with:
17
+ python-version: ${{ matrix.python-version }}
18
+ - name: Run image
19
+ uses: abatilo/actions-poetry@v2.1.4
20
+ with:
21
+ poetry-version: ${{ matrix.poetry-version }}
22
+ - name: Install dependencies
23
+ run: poetry install
24
+ - name: Run tests
25
+ run: poetry run pytest
26
+ - name: Upload coverage reports to Codecov
27
+ uses: codecov/codecov-action@v3
28
+ env:
29
+ CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
30
+ # - name: Upload coverage to Codecov
31
+ # uses: codecov/codecov-action@v2
32
+ code-quality:
33
+ strategy:
34
+ fail-fast: false
35
+ matrix:
36
+ python-version: ['3.10']
37
+ poetry-version: ['1.5.1']
38
+ os: [ubuntu-latest]
39
+ runs-on: ${{ matrix.os }}
40
+ steps:
41
+ - uses: actions/checkout@v3
42
+ - uses: actions/setup-python@v3
43
+ with:
44
+ python-version: ${{ matrix.python-version }}
45
+ - name: Python Poetry Action
46
+ uses: abatilo/actions-poetry@v2.1.6
47
+ with:
48
+ poetry-version: ${{ matrix.poetry-version }}
49
+ - name: Install dependencies
50
+ run: poetry install
51
+ - name: Run black
52
+ run: poetry run black . --check
53
+ # - name: Run isort
54
+ # run: poetry run isort . --check-only --profile black
55
+ # - name: Run flake8
56
+ # run: poetry run flake8 .
57
+ # - name: Run bandit
58
+ # run: poetry run bandit .
59
+ # - name: Run saftey
60
+ # run: poetry run safety check
.github/workflows/release.yml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Release
2
+ on:
3
+ release:
4
+ types:
5
+ - created
6
+
7
+ jobs:
8
+ publish:
9
+ strategy:
10
+ fail-fast: false
11
+ matrix:
12
+ python-version: ['3.10']
13
+ poetry-version: ['1.5.1']
14
+ os: [ubuntu-latest]
15
+ runs-on: ${{ matrix.os }}
16
+ steps:
17
+ - uses: actions/checkout@v3
18
+ - uses: actions/setup-python@v3
19
+ with:
20
+ python-version: ${{ matrix.python-version }}
21
+ - name: Run image
22
+ uses: abatilo/actions-poetry@v2.1.4
23
+ with:
24
+ poetry-version: ${{ matrix.poetry-version }}
25
+ - name: Publish
26
+ env:
27
+ PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
28
+ run: |
29
+ poetry config pypi-token.pypi $PYPI_TOKEN
30
+ poetry publish --build
.github/workflows/update_space.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Run Python script
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Checkout
14
+ uses: actions/checkout@v2
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: '3.9'
20
+
21
+ - name: Install Gradio
22
+ run: python -m pip install gradio
23
+
24
+ - name: Log in to Hugging Face
25
+ run: python -c 'import huggingface_hub; huggingface_hub.login(token="${{ secrets.hf_token }}")'
26
+
27
+ - name: Deploy to Spaces
28
+ run: gradio deploy
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ models
2
+ dist
3
+
4
+ .DS_Store
5
+ .vscode
6
+
7
+ __pycache__
8
+ gradio_cached_examples
9
+
10
+ .pytest_cache
CONTRIBUTING.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to [llama2-webui](https://github.com/liltom-eth/llama2-webui)
2
+
3
+ We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's:
4
+
5
+ - Reporting a bug
6
+ - Proposing new features
7
+ - Discussing the current state of the code
8
+ - Update README.md
9
+ - Submitting a PR
10
+
11
+ ## Using GitHub's [issues](https://github.com/liltom-eth/llama2-webui/issues)
12
+
13
+ We use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/liltom-eth/llama2-webui/issues). It's that easy!
14
+
15
+ Thanks for **[jlb1504](https://github.com/jlb1504)** for reporting the [first issue](https://github.com/liltom-eth/llama2-webui/issues/1)!
16
+
17
+ **Great Bug Reports** tend to have:
18
+
19
+ - A quick summary and/or background
20
+ - Steps to reproduce
21
+ - Be specific!
22
+ - Give a sample code if you can.
23
+ - What you expected would happen
24
+ - What actually happens
25
+ - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work)
26
+
27
+ Proposing new features are also welcome.
28
+
29
+ ## Pull Request
30
+
31
+ All pull requests are welcome. For example, you update the `README.md` to help users to better understand the usage.
32
+
33
+ ### Clone the repository
34
+
35
+ 1. Create a user account on GitHub if you do not already have one.
36
+
37
+ 2. Fork the project [repository](https://github.com/liltom-eth/llama2-webui): click on the *Fork* button near the top of the page. This creates a copy of the code under your account on GitHub.
38
+
39
+ 3. Clone this copy to your local disk:
40
+
41
+ ```
42
+ git clone git@github.com:liltom-eth/llama2-webui.git
43
+ cd llama2-webui
44
+ ```
45
+
46
+ ### Implement your changes
47
+
48
+ 1. Create a branch to hold your changes:
49
+
50
+ ```
51
+ git checkout -b my-feature
52
+ ```
53
+
54
+ and start making changes. Never work on the main branch!
55
+
56
+ 2. Start your work on this branch.
57
+
58
+ 3. When you’re done editing, do:
59
+
60
+ ```
61
+ git add <MODIFIED FILES>
62
+ git commit
63
+ ```
64
+
65
+ to record your changes in [git](https://git-scm.com/).
66
+
67
+ ### Submit your contribution
68
+
69
+ 1. If everything works fine, push your local branch to the remote server with:
70
+
71
+ ```
72
+ git push -u origin my-feature
73
+ ```
74
+
75
+ 2. Go to the web page of your fork and click "Create pull request" to send your changes for review.
76
+
77
+ ```{todo}
78
+ Find more detailed information in [creating a PR]. You might also want to open
79
+ the PR as a draft first and mark it as ready for review after the feedbacks
80
+ from the continuous integration (CI) system or any required fixes.
81
+ ```
82
+
83
+ ## License
84
+
85
+ By contributing, you agree that your contributions will be licensed under its MIT License.
86
+
87
+ ## Questions?
88
+
89
+ Email us at [liltom.eth@gmail.com](mailto:liltom.eth@gmail.com)
90
+
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Tom
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.
README.md CHANGED
@@ -1,12 +1,383 @@
1
  ---
2
- title: Gradio LLAMA Testing
3
- emoji: 📚
4
- colorFrom: blue
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 4.8.0
8
  app_file: app.py
9
- pinned: false
 
10
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
1
  ---
2
+ title: Gradio_LLAMA_Testing
 
 
 
 
 
3
  app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 3.37.0
6
  ---
7
+ # llama2-webui
8
+
9
+ Running Llama 2 with gradio web UI on GPU or CPU from anywhere (Linux/Windows/Mac).
10
+ - Supporting all Llama 2 models (7B, 13B, 70B, GPTQ, GGML, GGUF, [CodeLlama](https://huggingface.co/TheBloke/CodeLlama-7B-Instruct-GPTQ)) with 8-bit, 4-bit mode.
11
+ - Use [llama2-wrapper](https://pypi.org/project/llama2-wrapper/) as your local llama2 backend for Generative Agents/Apps; [colab example](./colab/Llama_2_7b_Chat_GPTQ.ipynb).
12
+ - [Run OpenAI Compatible API](#start-openai-compatible-api) on Llama2 models.
13
+
14
+ ![screenshot](./static/screenshot.png)
15
+
16
+ ![code_llama_playground](https://i.imgur.com/FgMUiT6.gif)
17
+
18
+ ## Features
19
+
20
+ - Supporting models: [Llama-2-7b](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf)/[13b](https://huggingface.co/llamaste/Llama-2-13b-chat-hf)/[70b](https://huggingface.co/llamaste/Llama-2-70b-chat-hf), [Llama-2-GPTQ](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GPTQ), [Llama-2-GGML](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML), [Llama-2-GGUF](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GGUF), [CodeLlama](https://huggingface.co/TheBloke/CodeLlama-7B-Instruct-GPTQ) ...
21
+ - Supporting model backends: [tranformers](https://github.com/huggingface/transformers), [bitsandbytes(8-bit inference)](https://github.com/TimDettmers/bitsandbytes), [AutoGPTQ(4-bit inference)](https://github.com/PanQiWei/AutoGPTQ), [llama.cpp](https://github.com/ggerganov/llama.cpp)
22
+ - Demos: [Run Llama2 on MacBook Air](https://twitter.com/liltom_eth/status/1682791729207070720?s=20); [Run Llama2 on free Colab T4 GPU](./colab/Llama_2_7b_Chat_GPTQ.ipynb)
23
+ - Use [llama2-wrapper](https://pypi.org/project/llama2-wrapper/) as your local llama2 backend for Generative Agents/Apps; [colab example](./colab/Llama_2_7b_Chat_GPTQ.ipynb).
24
+ - [Run OpenAI Compatible API](#start-openai-compatible-api) on Llama2 models.
25
+ - [News](./docs/news.md), [Benchmark](./docs/performance.md), [Issue Solutions](./docs/issues.md)
26
+
27
+ ## Contents
28
+
29
+ - [Install](#install)
30
+ - [Usage](#usage)
31
+ - [Start Chat UI](#start-chat-ui)
32
+ - [Start Code Llama UI](#start-code-llama-ui)
33
+ - [Use llama2-wrapper for Your App](#use-llama2-wrapper-for-your-app)
34
+ - [Start OpenAI Compatible API](#start-openai-compatible-api)
35
+ - [Benchmark](#benchmark)
36
+ - [Download Llama-2 Models](#download-llama-2-models)
37
+ - [Model List](#model-list)
38
+ - [Download Script](#download-script)
39
+ - [Tips](#tips)
40
+ - [Env Examples](#env-examples)
41
+ - [Run on Nvidia GPU](#run-on-nvidia-gpu)
42
+ - [Run bitsandbytes 8 bit](#run-bitsandbytes-8-bit)
43
+ - [Run GPTQ 4 bit](#run-gptq-4-bit)
44
+ - [Run on CPU](#run-on-cpu)
45
+ - [Mac Metal Acceleration](#mac-metal-acceleration)
46
+ - [AMD/Nvidia GPU Acceleration](#amdnvidia-gpu-acceleration)
47
+ - [License](#license)
48
+ - [Contributing](#contributing)
49
+
50
+
51
+
52
+ ## Install
53
+ ### Method 1: From [PyPI](https://pypi.org/project/llama2-wrapper/)
54
+ ```
55
+ pip install llama2-wrapper
56
+ ```
57
+ The newest `llama2-wrapper>=0.1.14` supports llama.cpp's `gguf` models.
58
+
59
+ If you would like to use old `ggml` models, install `llama2-wrapper<=0.1.13` or manually install `llama-cpp-python==0.1.77`.
60
+
61
+ ### Method 2: From Source:
62
+
63
+ ```
64
+ git clone https://github.com/liltom-eth/llama2-webui.git
65
+ cd llama2-webui
66
+ pip install -r requirements.txt
67
+ ```
68
+ ### Install Issues:
69
+ `bitsandbytes >= 0.39` may not work on older NVIDIA GPUs. In that case, to use `LOAD_IN_8BIT`, you may have to downgrade like this:
70
+
71
+ - `pip install bitsandbytes==0.38.1`
72
+
73
+ `bitsandbytes` also need a special install for Windows:
74
+
75
+ ```
76
+ pip uninstall bitsandbytes
77
+ pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.0-py3-none-win_amd64.whl
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ ### Start Chat UI
83
+
84
+ Run chatbot simply with web UI:
85
+
86
+ ```bash
87
+ python app.py
88
+ ```
89
+
90
+ `app.py` will load the default config `.env` which uses `llama.cpp` as the backend to run `llama-2-7b-chat.ggmlv3.q4_0.bin` model for inference. The model `llama-2-7b-chat.ggmlv3.q4_0.bin` will be automatically downloaded.
91
+
92
+ ```bash
93
+ Running on backend llama.cpp.
94
+ Use default model path: ./models/llama-2-7b-chat.Q4_0.gguf
95
+ Start downloading model to: ./models/llama-2-7b-chat.Q4_0.gguf
96
+ ```
97
+
98
+ You can also customize your `MODEL_PATH`, `BACKEND_TYPE,` and model configs in `.env` file to run different llama2 models on different backends (llama.cpp, transformers, gptq).
99
+
100
+ ### Start Code Llama UI
101
+
102
+ We provide a code completion / filling UI for Code Llama.
103
+
104
+ Base model **Code Llama** and extend model **Code Llama — Python** are not fine-tuned to follow instructions. They should be prompted so that the expected answer is the natural continuation of the prompt. That means these two models focus on code filling and code completion.
105
+
106
+ Here is an example run CodeLlama code completion on llama.cpp backend:
107
+
108
+ ```
109
+ python code_completion.py --model_path ./models/codellama-7b.Q4_0.gguf
110
+ ```
111
+
112
+ ![code_llama_playground](https://i.imgur.com/FgMUiT6.gif)
113
+
114
+ `codellama-7b.Q4_0.gguf` can be downloaded from [TheBloke/CodeLlama-7B-GGUF](https://huggingface.co/TheBloke/CodeLlama-7B-GGUF/blob/main/codellama-7b.Q4_0.gguf).
115
+
116
+ **Code Llama — Instruct** trained with “natural language instruction” inputs paired with anticipated outputs. This strategic methodology enhances the model’s capacity to grasp human expectations in prompts. That means instruct models can be used in a chatbot-like app.
117
+
118
+ Example run CodeLlama chat on gptq backend:
119
+
120
+ ```
121
+ python app.py --backend_type gptq --model_path ./models/CodeLlama-7B-Instruct-GPTQ/ --share True
122
+ ```
123
+
124
+ ![code_llama_chat](https://i.imgur.com/lQLfemB.gif)
125
+
126
+ `CodeLlama-7B-Instruct-GPTQ` can be downloaded from [TheBloke/CodeLlama-7B-Instruct-GPTQ](https://huggingface.co/TheBloke/CodeLlama-7B-Instruct-GPTQ)
127
+
128
+ ### Use llama2-wrapper for Your App
129
+
130
+ 🔥 For developers, we released `llama2-wrapper` as a llama2 backend wrapper in [PYPI](https://pypi.org/project/llama2-wrapper/).
131
+
132
+ Use `llama2-wrapper` as your local llama2 backend to answer questions and more, [colab example](./colab/ggmlv3_q4_0.ipynb):
133
+
134
+ ```python
135
+ # pip install llama2-wrapper
136
+ from llama2_wrapper import LLAMA2_WRAPPER, get_prompt
137
+ llama2_wrapper = LLAMA2_WRAPPER()
138
+ # Default running on backend llama.cpp.
139
+ # Automatically downloading model to: ./models/llama-2-7b-chat.ggmlv3.q4_0.bin
140
+ prompt = "Do you know Pytorch"
141
+ answer = llama2_wrapper(get_prompt(prompt), temperature=0.9)
142
+ ```
143
+
144
+ Run gptq llama2 model on Nvidia GPU, [colab example](./colab/Llama_2_7b_Chat_GPTQ.ipynb):
145
+
146
+ ```python
147
+ from llama2_wrapper import LLAMA2_WRAPPER
148
+ llama2_wrapper = LLAMA2_WRAPPER(backend_type="gptq")
149
+ # Automatically downloading model to: ./models/Llama-2-7b-Chat-GPTQ
150
+ ```
151
+
152
+ Run llama2 7b with bitsandbytes 8 bit with a `model_path`:
153
+
154
+ ```python
155
+ from llama2_wrapper import LLAMA2_WRAPPER
156
+ llama2_wrapper = LLAMA2_WRAPPER(
157
+ model_path = "./models/Llama-2-7b-chat-hf",
158
+ backend_type = "transformers",
159
+ load_in_8bit = True
160
+ )
161
+ ```
162
+ Check [API Document](https://pypi.org/project/llama2-wrapper/) for more usages.
163
+
164
+ ### Start OpenAI Compatible API
165
+
166
+ `llama2-wrapper` offers a web server that acts as a drop-in replacement for the OpenAI API. This allows you to use Llama2 models with any OpenAI compatible clients, libraries or services, etc.
167
+
168
+ Start Fast API:
169
+
170
+ ```
171
+ python -m llama2_wrapper.server
172
+ ```
173
+
174
+ it will use `llama.cpp` as the backend by default to run `llama-2-7b-chat.ggmlv3.q4_0.bin` model.
175
+
176
+ Start Fast API for `gptq` backend:
177
+
178
+ ```
179
+ python -m llama2_wrapper.server --backend_type gptq
180
+ ```
181
+
182
+ Navigate to http://localhost:8000/docs to see the OpenAPI documentation.
183
+
184
+ #### Basic settings
185
+
186
+ | Flag | Description |
187
+ | ---------------- | ------------------------------------------------------------ |
188
+ | `-h`, `--help` | Show this help message. |
189
+ | `--model_path` | The path to the model to use for generating completions. |
190
+ | `--backend_type` | Backend for llama2, options: llama.cpp, gptq, transformers |
191
+ | `--max_tokens` | Maximum context size. |
192
+ | `--load_in_8bit` | Whether to use bitsandbytes to run model in 8 bit mode (only for transformers models). |
193
+ | `--verbose` | Whether to print verbose output to stderr. |
194
+ | `--host` | API address |
195
+ | `--port` | API port |
196
+
197
+ ## Benchmark
198
+
199
+ Run benchmark script to compute performance on your device, `benchmark.py` will load the same `.env` as `app.py`.:
200
+
201
+ ```bash
202
+ python benchmark.py
203
+ ```
204
+
205
+ You can also select the `iter`, `backend_type` and `model_path` the benchmark will be run (overwrite .env args) :
206
+
207
+ ```bash
208
+ python benchmark.py --iter NB_OF_ITERATIONS --backend_type gptq
209
+ ```
210
+
211
+ By default, the number of iterations is 5, but if you want a faster result or a more accurate one
212
+ you can set it to whatever value you want, but please only report results with at least 5 iterations.
213
+
214
+ This [colab example](./colab/Llama_2_7b_Chat_GPTQ.ipynb) also show you how to benchmark gptq model on free Google Colab T4 GPU.
215
+
216
+ Some benchmark performance:
217
+
218
+ | Model | Precision | Device | RAM / GPU VRAM | Speed (tokens/sec) | load time (s) |
219
+ | --------------------------- | --------- | ------------------ | -------------- | ------------------ | ------------- |
220
+ | Llama-2-7b-chat-hf | 8 bit | NVIDIA RTX 2080 Ti | 7.7 GB VRAM | 3.76 | 641.36 |
221
+ | Llama-2-7b-Chat-GPTQ | 4 bit | NVIDIA RTX 2080 Ti | 5.8 GB VRAM | 18.85 | 192.91 |
222
+ | Llama-2-7b-Chat-GPTQ | 4 bit | Google Colab T4 | 5.8 GB VRAM | 18.19 | 37.44 |
223
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Apple M1 Pro CPU | 5.4 GB RAM | 17.90 | 0.18 |
224
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Apple M2 CPU | 5.4 GB RAM | 13.70 | 0.13 |
225
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Apple M2 Metal | 5.4 GB RAM | 12.60 | 0.10 |
226
+ | llama-2-7b-chat.ggmlv3.q2_K | 2 bit | Intel i7-8700 | 4.5 GB RAM | 7.88 | 31.90 |
227
+
228
+ Check/contribute the performance of your device in the full [performance doc](./docs/performance.md).
229
+
230
+ ## Download Llama-2 Models
231
+
232
+ Llama 2 is a collection of pre-trained and fine-tuned generative text models ranging in scale from 7 billion to 70 billion parameters.
233
+
234
+ Llama-2-7b-Chat-GPTQ is the GPTQ model files for [Meta's Llama 2 7b Chat](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf). GPTQ 4-bit Llama-2 model require less GPU VRAM to run it.
235
+
236
+ ### Model List
237
+
238
+ | Model Name | set MODEL_PATH in .env | Download URL |
239
+ | ----------------------------------- | ---------------------------------------- | ------------------------------------------------------------ |
240
+ | meta-llama/Llama-2-7b-chat-hf | /path-to/Llama-2-7b-chat-hf | [Link](https://huggingface.co/llamaste/Llama-2-7b-chat-hf) |
241
+ | meta-llama/Llama-2-13b-chat-hf | /path-to/Llama-2-13b-chat-hf | [Link](https://huggingface.co/llamaste/Llama-2-13b-chat-hf) |
242
+ | meta-llama/Llama-2-70b-chat-hf | /path-to/Llama-2-70b-chat-hf | [Link](https://huggingface.co/llamaste/Llama-2-70b-chat-hf) |
243
+ | meta-llama/Llama-2-7b-hf | /path-to/Llama-2-7b-hf | [Link](https://huggingface.co/meta-llama/Llama-2-7b-hf) |
244
+ | meta-llama/Llama-2-13b-hf | /path-to/Llama-2-13b-hf | [Link](https://huggingface.co/meta-llama/Llama-2-13b-hf) |
245
+ | meta-llama/Llama-2-70b-hf | /path-to/Llama-2-70b-hf | [Link](https://huggingface.co/meta-llama/Llama-2-70b-hf) |
246
+ | TheBloke/Llama-2-7b-Chat-GPTQ | /path-to/Llama-2-7b-Chat-GPTQ | [Link](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GPTQ) |
247
+ | TheBloke/Llama-2-7b-Chat-GGUF | /path-to/llama-2-7b-chat.Q4_0.gguf | [Link](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GGUF/blob/main/llama-2-7b-chat.Q4_0.gguf) |
248
+ | TheBloke/Llama-2-7B-Chat-GGML | /path-to/llama-2-7b-chat.ggmlv3.q4_0.bin | [Link](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML) |
249
+ | TheBloke/CodeLlama-7B-Instruct-GPTQ | TheBloke/CodeLlama-7B-Instruct-GPTQ | [Link](https://huggingface.co/TheBloke/CodeLlama-7B-Instruct-GPTQ) |
250
+ | ... | ... | ... |
251
+
252
+ Running 4-bit model `Llama-2-7b-Chat-GPTQ` needs GPU with 6GB VRAM.
253
+
254
+ Running 4-bit model `llama-2-7b-chat.ggmlv3.q4_0.bin` needs CPU with 6GB RAM. There is also a list of other 2, 3, 4, 5, 6, 8-bit GGML models that can be used from [TheBloke/Llama-2-7B-Chat-GGML](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML).
255
+
256
+ ### Download Script
257
+
258
+ These models can be downloaded through:
259
+
260
+ ```bash
261
+ python -m llama2_wrapper.download --repo_id TheBloke/CodeLlama-7B-Python-GPTQ
262
+
263
+ python -m llama2_wrapper.download --repo_id TheBloke/Llama-2-7b-Chat-GGUF --filename llama-2-7b-chat.Q4_0.gguf --save_dir ./models
264
+ ```
265
+
266
+ Or use CMD like:
267
+
268
+ ```bash
269
+ # Make sure you have git-lfs installed (https://git-lfs.com)
270
+ git lfs install
271
+ git clone git@hf.co:meta-llama/Llama-2-7b-chat-hf
272
+ ```
273
+
274
+ To download Llama 2 models, you need to request access from [https://ai.meta.com/llama/](https://ai.meta.com/llama/) and also enable access on repos like [meta-llama/Llama-2-7b-chat-hf](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf/tree/main). Requests will be processed in hours.
275
+
276
+ For GPTQ models like [TheBloke/Llama-2-7b-Chat-GPTQ](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GPTQ), you can directly download without requesting access.
277
+
278
+ For GGML models like [TheBloke/Llama-2-7B-Chat-GGML](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML), you can directly download without requesting access.
279
+
280
+ ## Tips
281
+
282
+ ### Env Examples
283
+
284
+ There are some examples in `./env_examples/` folder.
285
+
286
+ | Model Setup | Example .env |
287
+ | ------------------------------------------------------ | --------------------------- |
288
+ | Llama-2-7b-chat-hf 8-bit (transformers backend) | .env.7b_8bit_example |
289
+ | Llama-2-7b-Chat-GPTQ 4-bit (gptq transformers backend) | .env.7b_gptq_example |
290
+ | Llama-2-7B-Chat-GGML 4bit (llama.cpp backend) | .env.7b_ggmlv3_q4_0_example |
291
+ | Llama-2-13b-chat-hf (transformers backend) | .env.13b_example |
292
+ | ... | ... |
293
+
294
+ ### Run on Nvidia GPU
295
+
296
+ The running requires around 14GB of GPU VRAM for Llama-2-7b and 28GB of GPU VRAM for Llama-2-13b.
297
+
298
+ If you are running on multiple GPUs, the model will be loaded automatically on GPUs and split the VRAM usage. That allows you to run Llama-2-7b (requires 14GB of GPU VRAM) on a setup like 2 GPUs (11GB VRAM each).
299
+
300
+ #### Run bitsandbytes 8 bit
301
+
302
+ If you do not have enough memory, you can set up your `LOAD_IN_8BIT` as `True` in `.env`. This can reduce memory usage by around half with slightly degraded model quality. It is compatible with the CPU, GPU, and Metal backend.
303
+
304
+ Llama-2-7b with 8-bit compression can run on a single GPU with 8 GB of VRAM, like an Nvidia RTX 2080Ti, RTX 4080, T4, V100 (16GB).
305
+
306
+ #### Run GPTQ 4 bit
307
+
308
+ If you want to run 4 bit Llama-2 model like `Llama-2-7b-Chat-GPTQ`, you can set up your `BACKEND_TYPE` as `gptq` in `.env` like example `.env.7b_gptq_example`.
309
+
310
+ Make sure you have downloaded the 4-bit model from `Llama-2-7b-Chat-GPTQ` and set the `MODEL_PATH` and arguments in `.env` file.
311
+
312
+ `Llama-2-7b-Chat-GPTQ` can run on a single GPU with 6 GB of VRAM.
313
+
314
+ If you encounter issue like `NameError: name 'autogptq_cuda_256' is not defined`, please refer to [here](https://huggingface.co/TheBloke/open-llama-13b-open-instruct-GPTQ/discussions/1)
315
+ > pip install https://github.com/PanQiWei/AutoGPTQ/releases/download/v0.3.0/auto_gptq-0.3.0+cu117-cp310-cp310-linux_x86_64.whl
316
+
317
+ ### Run on CPU
318
+
319
+ Run Llama-2 model on CPU requires [llama.cpp](https://github.com/ggerganov/llama.cpp) dependency and [llama.cpp Python Bindings](https://github.com/abetlen/llama-cpp-python), which are already installed.
320
+
321
+
322
+ Download GGML models like `llama-2-7b-chat.ggmlv3.q4_0.bin` following [Download Llama-2 Models](#download-llama-2-models) section. `llama-2-7b-chat.ggmlv3.q4_0.bin` model requires at least 6 GB RAM to run on CPU.
323
+
324
+ Set up configs like `.env.7b_ggmlv3_q4_0_example` from `env_examples` as `.env`.
325
+
326
+ Run web UI `python app.py` .
327
+
328
+ #### Mac Metal Acceleration
329
+
330
+ For Mac users, you can also set up Mac Metal for acceleration, try install this dependencies:
331
+
332
+ ```bash
333
+ pip uninstall llama-cpp-python -y
334
+ CMAKE_ARGS="-DLLAMA_METAL=on" FORCE_CMAKE=1 pip install -U llama-cpp-python --no-cache-dir
335
+ pip install 'llama-cpp-python[server]'
336
+ ```
337
+
338
+ or check details:
339
+
340
+ - [MacOS Install with Metal GPU](https://github.com/abetlen/llama-cpp-python/blob/main/docs/install/macos.md)
341
+
342
+ #### AMD/Nvidia GPU Acceleration
343
+
344
+ If you would like to use AMD/Nvidia GPU for acceleration, check this:
345
+
346
+ - [Installation with OpenBLAS / cuBLAS / CLBlast / Metal](https://github.com/abetlen/llama-cpp-python#installation-with-openblas--cublas--clblast--metal)
347
+
348
+
349
+
350
+
351
+
352
+ ## License
353
+
354
+ MIT - see [MIT License](LICENSE)
355
+
356
+ This project enables users to adapt it freely for proprietary purposes without any restrictions.
357
+
358
+ ## Contributing
359
+
360
+ Kindly read our [Contributing Guide](CONTRIBUTING.md) to learn and understand our development process.
361
+
362
+ ### All Contributors
363
+
364
+ <a href="https://github.com/liltom-eth/llama2-webui/graphs/contributors">
365
+ <img src="https://contrib.rocks/image?repo=liltom-eth/llama2-webui" />
366
+ </a>
367
+
368
+ ### Review
369
+ <a href='https://github.com/repo-reviews/repo-reviews.github.io/blob/main/create.md' target="_blank"><img alt='Github' src='https://img.shields.io/badge/review-100000?style=flat&logo=Github&logoColor=white&labelColor=888888&color=555555'/></a>
370
+
371
+ ### Star History
372
+
373
+ [![Star History Chart](https://api.star-history.com/svg?repos=liltom-eth/llama2-webui&type=Date)](https://star-history.com/#liltom-eth/llama2-webui&Date)
374
+
375
+ ## Credits
376
 
377
+ - https://huggingface.co/meta-llama/Llama-2-7b-chat-hf
378
+ - https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat
379
+ - https://huggingface.co/TheBloke/Llama-2-7b-Chat-GPTQ
380
+ - [https://github.com/ggerganov/llama.cpp](https://github.com/ggerganov/llama.cpp)
381
+ - [https://github.com/TimDettmers/bitsandbytes](https://github.com/TimDettmers/bitsandbytes)
382
+ - [https://github.com/PanQiWei/AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)
383
+ - [https://github.com/abetlen/llama-cpp-python](https://github.com/abetlen/llama-cpp-python)
app.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ from typing import Iterator
4
+
5
+ import gradio as gr
6
+ from dotenv import load_dotenv
7
+ from distutils.util import strtobool
8
+
9
+ from llama2_wrapper import LLAMA2_WRAPPER
10
+
11
+ import logging
12
+
13
+ from prompts.utils import PromtsContainer
14
+
15
+
16
+ def main():
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument("--model_path", type=str, default="", help="model path")
19
+ parser.add_argument(
20
+ "--backend_type",
21
+ type=str,
22
+ default="",
23
+ help="Backend options: llama.cpp, gptq, transformers",
24
+ )
25
+ parser.add_argument(
26
+ "--load_in_8bit",
27
+ type=bool,
28
+ default=False,
29
+ help="Whether to use bitsandbytes 8 bit.",
30
+ )
31
+ parser.add_argument(
32
+ "--share",
33
+ type=bool,
34
+ default=False,
35
+ help="Whether to share public for gradio.",
36
+ )
37
+ args = parser.parse_args()
38
+
39
+ load_dotenv()
40
+
41
+ DEFAULT_SYSTEM_PROMPT = os.getenv("DEFAULT_SYSTEM_PROMPT", "")
42
+ MAX_MAX_NEW_TOKENS = int(os.getenv("MAX_MAX_NEW_TOKENS", 2048))
43
+ DEFAULT_MAX_NEW_TOKENS = int(os.getenv("DEFAULT_MAX_NEW_TOKENS", 1024))
44
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", 4000))
45
+
46
+ MODEL_PATH = os.getenv("MODEL_PATH")
47
+ assert MODEL_PATH is not None, f"MODEL_PATH is required, got: {MODEL_PATH}"
48
+ BACKEND_TYPE = os.getenv("BACKEND_TYPE")
49
+ assert BACKEND_TYPE is not None, f"BACKEND_TYPE is required, got: {BACKEND_TYPE}"
50
+
51
+ LOAD_IN_8BIT = bool(strtobool(os.getenv("LOAD_IN_8BIT", "True")))
52
+
53
+ if args.model_path != "":
54
+ MODEL_PATH = args.model_path
55
+ if args.backend_type != "":
56
+ BACKEND_TYPE = args.backend_type
57
+ if args.load_in_8bit:
58
+ LOAD_IN_8BIT = True
59
+
60
+ llama2_wrapper = LLAMA2_WRAPPER(
61
+ model_path=MODEL_PATH,
62
+ backend_type=BACKEND_TYPE,
63
+ max_tokens=MAX_INPUT_TOKEN_LENGTH,
64
+ load_in_8bit=LOAD_IN_8BIT,
65
+ # verbose=True,
66
+ )
67
+
68
+ DESCRIPTION = """
69
+ # llama2-webui
70
+ """
71
+ DESCRIPTION2 = """
72
+ - Supporting models: [Llama-2-7b](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML)/[13b](https://huggingface.co/llamaste/Llama-2-13b-chat-hf)/[70b](https://huggingface.co/llamaste/Llama-2-70b-chat-hf), [Llama-2-GPTQ](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GPTQ), [Llama-2-GGML](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML), [CodeLlama](https://huggingface.co/TheBloke/CodeLlama-7B-Instruct-GPTQ) ...
73
+ - Supporting model backends: [tranformers](https://github.com/huggingface/transformers), [bitsandbytes(8-bit inference)](https://github.com/TimDettmers/bitsandbytes), [AutoGPTQ(4-bit inference)](https://github.com/PanQiWei/AutoGPTQ), [llama.cpp](https://github.com/ggerganov/llama.cpp)
74
+ """
75
+
76
+ def clear_and_save_textbox(message: str) -> tuple[str, str]:
77
+ return "", message
78
+
79
+ def save_textbox_for_prompt(message: str) -> str:
80
+ logging.info("start save_textbox_from_prompt")
81
+ message = convert_summary_to_prompt(message)
82
+ return message
83
+
84
+ def display_input(
85
+ message: str, history: list[tuple[str, str]]
86
+ ) -> list[tuple[str, str]]:
87
+ history.append((message, ""))
88
+ return history
89
+
90
+ def delete_prev_fn(
91
+ history: list[tuple[str, str]]
92
+ ) -> tuple[list[tuple[str, str]], str]:
93
+ try:
94
+ message, _ = history.pop()
95
+ except IndexError:
96
+ message = ""
97
+ return history, message or ""
98
+
99
+ def generate(
100
+ message: str,
101
+ history_with_input: list[tuple[str, str]],
102
+ system_prompt: str,
103
+ max_new_tokens: int,
104
+ temperature: float,
105
+ top_p: float,
106
+ top_k: int,
107
+ ) -> Iterator[list[tuple[str, str]]]:
108
+ if max_new_tokens > MAX_MAX_NEW_TOKENS:
109
+ raise ValueError
110
+ try:
111
+ history = history_with_input[:-1]
112
+ generator = llama2_wrapper.run(
113
+ message,
114
+ history,
115
+ system_prompt,
116
+ max_new_tokens,
117
+ temperature,
118
+ top_p,
119
+ top_k,
120
+ )
121
+ try:
122
+ first_response = next(generator)
123
+ yield history + [(message, first_response)]
124
+ except StopIteration:
125
+ yield history + [(message, "")]
126
+ for response in generator:
127
+ yield history + [(message, response)]
128
+ except Exception as e:
129
+ logging.exception(e)
130
+
131
+ def check_input_token_length(
132
+ message: str, chat_history: list[tuple[str, str]], system_prompt: str
133
+ ) -> None:
134
+ input_token_length = llama2_wrapper.get_input_token_length(
135
+ message, chat_history, system_prompt
136
+ )
137
+ if input_token_length > MAX_INPUT_TOKEN_LENGTH:
138
+ raise gr.Error(
139
+ f"The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again."
140
+ )
141
+
142
+ prompts_container = PromtsContainer()
143
+ prompts = prompts_container.get_prompts_tab_dict()
144
+ default_prompts_checkbox = False
145
+ default_advanced_checkbox = False
146
+
147
+ def convert_summary_to_prompt(summary):
148
+ return prompts_container.get_prompt_by_summary(summary)
149
+
150
+ def two_columns_list(tab_data, chatbot):
151
+ result = []
152
+ for i in range(int(len(tab_data) / 2) + 1):
153
+ row = gr.Row()
154
+ with row:
155
+ for j in range(2):
156
+ index = 2 * i + j
157
+ if index >= len(tab_data):
158
+ break
159
+ item = tab_data[index]
160
+ with gr.Group():
161
+ gr.HTML(
162
+ f'<p style="color: black; font-weight: bold;">{item["act"]}</p>'
163
+ )
164
+ prompt_text = gr.Button(
165
+ label="",
166
+ value=f"{item['summary']}",
167
+ size="sm",
168
+ elem_classes="text-left-aligned",
169
+ )
170
+ prompt_text.click(
171
+ fn=save_textbox_for_prompt,
172
+ inputs=prompt_text,
173
+ outputs=saved_input,
174
+ api_name=False,
175
+ queue=True,
176
+ ).then(
177
+ fn=display_input,
178
+ inputs=[saved_input, chatbot],
179
+ outputs=chatbot,
180
+ api_name=False,
181
+ queue=True,
182
+ ).then(
183
+ fn=check_input_token_length,
184
+ inputs=[saved_input, chatbot, system_prompt],
185
+ api_name=False,
186
+ queue=False,
187
+ ).success(
188
+ fn=generate,
189
+ inputs=[
190
+ saved_input,
191
+ chatbot,
192
+ system_prompt,
193
+ max_new_tokens,
194
+ temperature,
195
+ top_p,
196
+ top_k,
197
+ ],
198
+ outputs=chatbot,
199
+ api_name=False,
200
+ )
201
+ result.append(row)
202
+ return result
203
+
204
+ CSS = """
205
+ .contain { display: flex; flex-direction: column;}
206
+ #component-0 #component-1 #component-2 #component-4 #component-5 { height:71vh !important; }
207
+ #component-0 #component-1 #component-24 > div:nth-child(2) { height:80vh !important; overflow-y:auto }
208
+ .text-left-aligned {text-align: left !important; font-size: 16px;}
209
+ """
210
+ with gr.Blocks(css=CSS) as demo:
211
+ with gr.Row(equal_height=True):
212
+ with gr.Column(scale=2):
213
+ gr.Markdown(DESCRIPTION)
214
+ with gr.Group():
215
+ chatbot = gr.Chatbot(label="Chatbot")
216
+ with gr.Row():
217
+ textbox = gr.Textbox(
218
+ container=False,
219
+ show_label=False,
220
+ placeholder="Type a message...",
221
+ scale=10,
222
+ )
223
+ submit_button = gr.Button(
224
+ "Submit", variant="primary", scale=1, min_width=0
225
+ )
226
+ with gr.Row():
227
+ retry_button = gr.Button("🔄 Retry", variant="secondary")
228
+ undo_button = gr.Button("↩️ Undo", variant="secondary")
229
+ clear_button = gr.Button("🗑️ Clear", variant="secondary")
230
+
231
+ saved_input = gr.State()
232
+ with gr.Row():
233
+ advanced_checkbox = gr.Checkbox(
234
+ label="Advanced",
235
+ value=default_prompts_checkbox,
236
+ container=False,
237
+ elem_classes="min_check",
238
+ )
239
+ prompts_checkbox = gr.Checkbox(
240
+ label="Prompts",
241
+ value=default_prompts_checkbox,
242
+ container=False,
243
+ elem_classes="min_check",
244
+ )
245
+ with gr.Column(visible=default_advanced_checkbox) as advanced_column:
246
+ system_prompt = gr.Textbox(
247
+ label="System prompt", value=DEFAULT_SYSTEM_PROMPT, lines=6
248
+ )
249
+ max_new_tokens = gr.Slider(
250
+ label="Max new tokens",
251
+ minimum=1,
252
+ maximum=MAX_MAX_NEW_TOKENS,
253
+ step=1,
254
+ value=DEFAULT_MAX_NEW_TOKENS,
255
+ )
256
+ temperature = gr.Slider(
257
+ label="Temperature",
258
+ minimum=0.1,
259
+ maximum=4.0,
260
+ step=0.1,
261
+ value=1.0,
262
+ )
263
+ top_p = gr.Slider(
264
+ label="Top-p (nucleus sampling)",
265
+ minimum=0.05,
266
+ maximum=1.0,
267
+ step=0.05,
268
+ value=0.95,
269
+ )
270
+ top_k = gr.Slider(
271
+ label="Top-k",
272
+ minimum=1,
273
+ maximum=1000,
274
+ step=1,
275
+ value=50,
276
+ )
277
+ with gr.Column(scale=1, visible=default_prompts_checkbox) as prompt_column:
278
+ gr.HTML(
279
+ '<p style="color: green; font-weight: bold;font-size: 16px;">\N{four leaf clover} prompts</p>'
280
+ )
281
+ for k, v in prompts.items():
282
+ with gr.Tab(k, scroll_to_output=True):
283
+ lst = two_columns_list(v, chatbot)
284
+ prompts_checkbox.change(
285
+ lambda x: gr.update(visible=x),
286
+ prompts_checkbox,
287
+ prompt_column,
288
+ queue=False,
289
+ )
290
+ advanced_checkbox.change(
291
+ lambda x: gr.update(visible=x),
292
+ advanced_checkbox,
293
+ advanced_column,
294
+ queue=False,
295
+ )
296
+
297
+ textbox.submit(
298
+ fn=clear_and_save_textbox,
299
+ inputs=textbox,
300
+ outputs=[textbox, saved_input],
301
+ api_name=False,
302
+ queue=False,
303
+ ).then(
304
+ fn=display_input,
305
+ inputs=[saved_input, chatbot],
306
+ outputs=chatbot,
307
+ api_name=False,
308
+ queue=False,
309
+ ).then(
310
+ fn=check_input_token_length,
311
+ inputs=[saved_input, chatbot, system_prompt],
312
+ api_name=False,
313
+ queue=False,
314
+ ).success(
315
+ fn=generate,
316
+ inputs=[
317
+ saved_input,
318
+ chatbot,
319
+ system_prompt,
320
+ max_new_tokens,
321
+ temperature,
322
+ top_p,
323
+ top_k,
324
+ ],
325
+ outputs=chatbot,
326
+ api_name=False,
327
+ )
328
+
329
+ button_event_preprocess = (
330
+ submit_button.click(
331
+ fn=clear_and_save_textbox,
332
+ inputs=textbox,
333
+ outputs=[textbox, saved_input],
334
+ api_name=False,
335
+ queue=False,
336
+ )
337
+ .then(
338
+ fn=display_input,
339
+ inputs=[saved_input, chatbot],
340
+ outputs=chatbot,
341
+ api_name=False,
342
+ queue=False,
343
+ )
344
+ .then(
345
+ fn=check_input_token_length,
346
+ inputs=[saved_input, chatbot, system_prompt],
347
+ api_name=False,
348
+ queue=False,
349
+ )
350
+ .success(
351
+ fn=generate,
352
+ inputs=[
353
+ saved_input,
354
+ chatbot,
355
+ system_prompt,
356
+ max_new_tokens,
357
+ temperature,
358
+ top_p,
359
+ top_k,
360
+ ],
361
+ outputs=chatbot,
362
+ api_name=False,
363
+ )
364
+ )
365
+
366
+ retry_button.click(
367
+ fn=delete_prev_fn,
368
+ inputs=chatbot,
369
+ outputs=[chatbot, saved_input],
370
+ api_name=False,
371
+ queue=False,
372
+ ).then(
373
+ fn=display_input,
374
+ inputs=[saved_input, chatbot],
375
+ outputs=chatbot,
376
+ api_name=False,
377
+ queue=False,
378
+ ).then(
379
+ fn=generate,
380
+ inputs=[
381
+ saved_input,
382
+ chatbot,
383
+ system_prompt,
384
+ max_new_tokens,
385
+ temperature,
386
+ top_p,
387
+ top_k,
388
+ ],
389
+ outputs=chatbot,
390
+ api_name=False,
391
+ )
392
+
393
+ undo_button.click(
394
+ fn=delete_prev_fn,
395
+ inputs=chatbot,
396
+ outputs=[chatbot, saved_input],
397
+ api_name=False,
398
+ queue=False,
399
+ ).then(
400
+ fn=lambda x: x,
401
+ inputs=[saved_input],
402
+ outputs=textbox,
403
+ api_name=False,
404
+ queue=False,
405
+ )
406
+
407
+ clear_button.click(
408
+ fn=lambda: ([], ""),
409
+ outputs=[chatbot, saved_input],
410
+ queue=False,
411
+ api_name=False,
412
+ )
413
+
414
+ demo.queue(max_size=20).launch(share=args.share)
415
+
416
+
417
+ if __name__ == "__main__":
418
+ main()
benchmark.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import argparse
4
+
5
+ from dotenv import load_dotenv
6
+ from distutils.util import strtobool
7
+ from memory_profiler import memory_usage
8
+ from tqdm import tqdm
9
+
10
+ from llama2_wrapper import LLAMA2_WRAPPER
11
+
12
+
13
+ def run_iteration(
14
+ llama2_wrapper, prompt_example, DEFAULT_SYSTEM_PROMPT, DEFAULT_MAX_NEW_TOKENS
15
+ ):
16
+ def generation():
17
+ generator = llama2_wrapper.run(
18
+ prompt_example,
19
+ [],
20
+ DEFAULT_SYSTEM_PROMPT,
21
+ DEFAULT_MAX_NEW_TOKENS,
22
+ 1,
23
+ 0.95,
24
+ 50,
25
+ )
26
+ model_response = None
27
+ try:
28
+ first_model_response = next(generator)
29
+ except StopIteration:
30
+ pass
31
+ for model_response in generator:
32
+ pass
33
+ return llama2_wrapper.get_token_length(model_response), model_response
34
+
35
+ tic = time.perf_counter()
36
+ mem_usage, (output_token_length, model_response) = memory_usage(
37
+ (generation,), max_usage=True, retval=True
38
+ )
39
+ toc = time.perf_counter()
40
+
41
+ generation_time = toc - tic
42
+ tokens_per_second = output_token_length / generation_time
43
+
44
+ return generation_time, tokens_per_second, mem_usage, model_response
45
+
46
+
47
+ def main():
48
+ parser = argparse.ArgumentParser()
49
+ parser.add_argument("--iter", type=int, default=5, help="Number of iterations")
50
+ parser.add_argument("--model_path", type=str, default="", help="model path")
51
+ parser.add_argument(
52
+ "--backend_type",
53
+ type=str,
54
+ default="",
55
+ help="Backend options: llama.cpp, gptq, transformers",
56
+ )
57
+ parser.add_argument(
58
+ "--load_in_8bit",
59
+ type=bool,
60
+ default=False,
61
+ help="Whether to use bitsandbytes 8 bit.",
62
+ )
63
+
64
+ args = parser.parse_args()
65
+
66
+ load_dotenv()
67
+
68
+ DEFAULT_SYSTEM_PROMPT = os.getenv("DEFAULT_SYSTEM_PROMPT", "")
69
+ MAX_MAX_NEW_TOKENS = int(os.getenv("MAX_MAX_NEW_TOKENS", 2048))
70
+ DEFAULT_MAX_NEW_TOKENS = int(os.getenv("DEFAULT_MAX_NEW_TOKENS", 1024))
71
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", 4000))
72
+
73
+ MODEL_PATH = os.getenv("MODEL_PATH")
74
+ assert MODEL_PATH is not None, f"MODEL_PATH is required, got: {MODEL_PATH}"
75
+ BACKEND_TYPE = os.getenv("BACKEND_TYPE")
76
+ assert BACKEND_TYPE is not None, f"BACKEND_TYPE is required, got: {BACKEND_TYPE}"
77
+
78
+ LOAD_IN_8BIT = bool(strtobool(os.getenv("LOAD_IN_8BIT", "True")))
79
+
80
+ if args.model_path != "":
81
+ MODEL_PATH = args.model_path
82
+ if args.backend_type != "":
83
+ BACKEND_TYPE = args.backend_type
84
+ if args.load_in_8bit:
85
+ LOAD_IN_8BIT = True
86
+
87
+ # Initialization
88
+ init_tic = time.perf_counter()
89
+ llama2_wrapper = LLAMA2_WRAPPER(
90
+ model_path=MODEL_PATH,
91
+ backend_type=BACKEND_TYPE,
92
+ max_tokens=MAX_INPUT_TOKEN_LENGTH,
93
+ load_in_8bit=LOAD_IN_8BIT,
94
+ # verbose=True,
95
+ )
96
+
97
+ init_toc = time.perf_counter()
98
+ initialization_time = init_toc - init_tic
99
+
100
+ total_time = 0
101
+ total_tokens_per_second = 0
102
+ total_memory_gen = 0
103
+
104
+ prompt_example = (
105
+ "Can you explain briefly to me what is the Python programming language?"
106
+ )
107
+
108
+ # Cold run
109
+ print("Performing cold run...")
110
+ run_iteration(
111
+ llama2_wrapper, prompt_example, DEFAULT_SYSTEM_PROMPT, DEFAULT_MAX_NEW_TOKENS
112
+ )
113
+
114
+ # Timed runs
115
+ print(f"Performing {args.iter} timed runs...")
116
+ for i in tqdm(range(args.iter)):
117
+ try:
118
+ gen_time, tokens_per_sec, mem_gen, model_response = run_iteration(
119
+ llama2_wrapper,
120
+ prompt_example,
121
+ DEFAULT_SYSTEM_PROMPT,
122
+ DEFAULT_MAX_NEW_TOKENS,
123
+ )
124
+ total_time += gen_time
125
+ total_tokens_per_second += tokens_per_sec
126
+ total_memory_gen += mem_gen
127
+ except:
128
+ break
129
+ avg_time = total_time / (i + 1)
130
+ avg_tokens_per_second = total_tokens_per_second / (i + 1)
131
+ avg_memory_gen = total_memory_gen / (i + 1)
132
+
133
+ print(f"Last model response: {model_response}")
134
+ print(f"Initialization time: {initialization_time:0.4f} seconds.")
135
+ print(
136
+ f"Average generation time over {(i + 1)} iterations: {avg_time:0.4f} seconds."
137
+ )
138
+ print(
139
+ f"Average speed over {(i + 1)} iterations: {avg_tokens_per_second:0.4f} tokens/sec."
140
+ )
141
+ print(f"Average memory usage during generation: {avg_memory_gen:.2f} MiB")
142
+
143
+
144
+ if __name__ == "__main__":
145
+ main()
code_completion.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import gradio as gr
4
+ from llama2_wrapper import LLAMA2_WRAPPER
5
+
6
+ FIM_PREFIX = "<PRE> "
7
+ FIM_MIDDLE = " <MID>"
8
+ FIM_SUFFIX = " <SUF>"
9
+
10
+ FIM_INDICATOR = "<FILL_ME>"
11
+
12
+ EOS_STRING = "</s>"
13
+ EOT_STRING = "<EOT>"
14
+
15
+
16
+ def main():
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument(
19
+ "--model_path",
20
+ type=str,
21
+ default="./models/codellama-7b-instruct.ggmlv3.Q4_0.bin",
22
+ help="model path",
23
+ )
24
+ parser.add_argument(
25
+ "--backend_type",
26
+ type=str,
27
+ default="llama.cpp",
28
+ help="Backend options: llama.cpp, gptq, transformers",
29
+ )
30
+ parser.add_argument(
31
+ "--max_tokens",
32
+ type=int,
33
+ default=4000,
34
+ help="Maximum context size.",
35
+ )
36
+ parser.add_argument(
37
+ "--load_in_8bit",
38
+ type=bool,
39
+ default=False,
40
+ help="Whether to use bitsandbytes 8 bit.",
41
+ )
42
+ parser.add_argument(
43
+ "--share",
44
+ type=bool,
45
+ default=False,
46
+ help="Whether to share public for gradio.",
47
+ )
48
+ args = parser.parse_args()
49
+
50
+ llama2_wrapper = LLAMA2_WRAPPER(
51
+ model_path=args.model_path,
52
+ backend_type=args.backend_type,
53
+ max_tokens=args.max_tokens,
54
+ load_in_8bit=args.load_in_8bit,
55
+ )
56
+
57
+ def generate(
58
+ prompt,
59
+ temperature=0.9,
60
+ max_new_tokens=256,
61
+ top_p=0.95,
62
+ repetition_penalty=1.0,
63
+ ):
64
+ temperature = float(temperature)
65
+ if temperature < 1e-2:
66
+ temperature = 1e-2
67
+ top_p = float(top_p)
68
+ fim_mode = False
69
+
70
+ generate_kwargs = dict(
71
+ temperature=temperature,
72
+ max_new_tokens=max_new_tokens,
73
+ top_p=top_p,
74
+ repetition_penalty=repetition_penalty,
75
+ stream=True,
76
+ )
77
+
78
+ if FIM_INDICATOR in prompt:
79
+ fim_mode = True
80
+ try:
81
+ prefix, suffix = prompt.split(FIM_INDICATOR)
82
+ except:
83
+ raise ValueError(f"Only one {FIM_INDICATOR} allowed in prompt!")
84
+ prompt = f"{FIM_PREFIX}{prefix}{FIM_SUFFIX}{suffix}{FIM_MIDDLE}"
85
+
86
+ stream = llama2_wrapper.__call__(prompt, **generate_kwargs)
87
+
88
+ if fim_mode:
89
+ output = prefix
90
+ else:
91
+ output = prompt
92
+
93
+ # for response in stream:
94
+ # output += response
95
+ # yield output
96
+ # return output
97
+
98
+ previous_token = ""
99
+ for response in stream:
100
+ if any([end_token in response for end_token in [EOS_STRING, EOT_STRING]]):
101
+ if fim_mode:
102
+ output += suffix
103
+ yield output
104
+ return output
105
+ print("output", output)
106
+ else:
107
+ return output
108
+ else:
109
+ output += response
110
+ previous_token = response
111
+ yield output
112
+ return output
113
+
114
+ examples = [
115
+ 'def remove_non_ascii(s: str) -> str:\n """ <FILL_ME>\nprint(remove_non_ascii(\'afkdj$$(\'))',
116
+ "X_train, y_train, X_test, y_test = train_test_split(X, y, test_size=0.1)\n\n# Train a logistic regression model, predict the labels on the test set and compute the accuracy score",
117
+ "// Returns every other value in the array as a new array.\nfunction everyOther(arr) {",
118
+ "Poor English: She no went to the market. Corrected English:",
119
+ "def alternating(list1, list2):\n results = []\n for i in range(min(len(list1), len(list2))):\n results.append(list1[i])\n results.append(list2[i])\n if len(list1) > len(list2):\n <FILL_ME>\n else:\n results.extend(list2[i+1:])\n return results",
120
+ ]
121
+
122
+ def process_example(args):
123
+ for x in generate(args):
124
+ pass
125
+ return x
126
+
127
+ description = """
128
+ <div style="text-align: center;">
129
+ <h1>Code Llama Playground</h1>
130
+
131
+ </div>
132
+ <div style="text-align: center;">
133
+ <p>This is a demo to complete code with Code Llama. For instruction purposes, please use llama2-webui app.py with CodeLlama-Instruct models. </p>
134
+ </div>
135
+ """
136
+ with gr.Blocks() as demo:
137
+ with gr.Column():
138
+ gr.Markdown(description)
139
+ with gr.Row():
140
+ with gr.Column():
141
+ instruction = gr.Textbox(
142
+ placeholder="Enter your code here",
143
+ lines=5,
144
+ label="Input",
145
+ elem_id="q-input",
146
+ )
147
+ submit = gr.Button("Generate", variant="primary")
148
+ output = gr.Code(elem_id="q-output", lines=30, label="Output")
149
+ with gr.Row():
150
+ with gr.Column():
151
+ with gr.Accordion("Advanced settings", open=False):
152
+ with gr.Row():
153
+ column_1, column_2 = gr.Column(), gr.Column()
154
+ with column_1:
155
+ temperature = gr.Slider(
156
+ label="Temperature",
157
+ value=0.1,
158
+ minimum=0.0,
159
+ maximum=1.0,
160
+ step=0.05,
161
+ interactive=True,
162
+ info="Higher values produce more diverse outputs",
163
+ )
164
+ max_new_tokens = gr.Slider(
165
+ label="Max new tokens",
166
+ value=256,
167
+ minimum=0,
168
+ maximum=8192,
169
+ step=64,
170
+ interactive=True,
171
+ info="The maximum numbers of new tokens",
172
+ )
173
+ with column_2:
174
+ top_p = gr.Slider(
175
+ label="Top-p (nucleus sampling)",
176
+ value=0.90,
177
+ minimum=0.0,
178
+ maximum=1,
179
+ step=0.05,
180
+ interactive=True,
181
+ info="Higher values sample more low-probability tokens",
182
+ )
183
+ repetition_penalty = gr.Slider(
184
+ label="Repetition penalty",
185
+ value=1.05,
186
+ minimum=1.0,
187
+ maximum=2.0,
188
+ step=0.05,
189
+ interactive=True,
190
+ info="Penalize repeated tokens",
191
+ )
192
+
193
+ gr.Examples(
194
+ examples=examples,
195
+ inputs=[instruction],
196
+ cache_examples=False,
197
+ fn=process_example,
198
+ outputs=[output],
199
+ )
200
+
201
+ submit.click(
202
+ generate,
203
+ inputs=[
204
+ instruction,
205
+ temperature,
206
+ max_new_tokens,
207
+ top_p,
208
+ repetition_penalty,
209
+ ],
210
+ outputs=[output],
211
+ )
212
+ demo.queue(concurrency_count=16).launch(share=args.share)
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()
colab/Llama_2_7b_Chat_GPTQ.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
colab/ggmlv3_q4_0.ipynb ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "toc_visible": true,
8
+ "authorship_tag": "ABX9TyM9WbudQYrVFksXUrt4Opt3",
9
+ "include_colab_link": true
10
+ },
11
+ "kernelspec": {
12
+ "name": "python3",
13
+ "display_name": "Python 3"
14
+ },
15
+ "language_info": {
16
+ "name": "python"
17
+ }
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {
23
+ "id": "view-in-github",
24
+ "colab_type": "text"
25
+ },
26
+ "source": [
27
+ "<a href=\"https://colab.research.google.com/github/liltom-eth/llama2-webui/blob/main/colab/ggmlv3_q4_0.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": null,
33
+ "metadata": {
34
+ "id": "7O5JSosg5-rx"
35
+ },
36
+ "outputs": [],
37
+ "source": [
38
+ "%cd /content\n",
39
+ "!pip install llama2-wrapper\n"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "source": [
45
+ "from llama2_wrapper import LLAMA2_WRAPPER, get_prompt\n",
46
+ "\n",
47
+ "llama2_wrapper = LLAMA2_WRAPPER()"
48
+ ],
49
+ "metadata": {
50
+ "colab": {
51
+ "base_uri": "https://localhost:8080/"
52
+ },
53
+ "id": "8rgb1ckl72wC",
54
+ "outputId": "d9ca2e20-26a5-490b-86f2-1a182e533b20"
55
+ },
56
+ "execution_count": 5,
57
+ "outputs": [
58
+ {
59
+ "output_type": "stream",
60
+ "name": "stdout",
61
+ "text": [
62
+ "Running on backend llama.cpp.\n",
63
+ "Use default model path: ./models/llama-2-7b-chat.ggmlv3.q4_0.bin\n",
64
+ "Start downloading model to: ./models/llama-2-7b-chat.ggmlv3.q4_0.bin\n"
65
+ ]
66
+ }
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "source": [
72
+ "prompt = get_prompt(\"Hi do you know Pytorch?\")\n",
73
+ "print(llama2_wrapper(prompt))"
74
+ ],
75
+ "metadata": {
76
+ "id": "Qz2xAqozTIf6",
77
+ "colab": {
78
+ "base_uri": "https://localhost:8080/"
79
+ },
80
+ "outputId": "1380fa52-3d4a-4ac5-ed02-7faefe7ec2f6"
81
+ },
82
+ "execution_count": 3,
83
+ "outputs": [
84
+ {
85
+ "output_type": "stream",
86
+ "name": "stdout",
87
+ "text": [
88
+ " Yes, I'm familiar with PyTorch! PyTorch is an open-source deep learning framework that is widely used for building and training neural networks. It was originally developed by Facebook and is now maintained by the PyTorch Foundation.\n",
89
+ "\n",
90
+ "Here are some key features and capabilities of PyTorch:\n",
91
+ "\n",
92
+ "1. **Tensor Computation**: PyTorch provides a powerful tensor computation engine that allows for complex mathematical operations on large datasets.\n",
93
+ "2. **Autograd**: PyTorch's autograd system automatically computes gradients, which can save a lot of time and effort during training.\n",
94
+ "3. **Dynamic Compute**: PyTorch's dynamic compute system allows for more efficient computation by only computing the necessary computations at runtime.\n",
95
+ "4. **Memory-efficient**: PyTorch is designed to be memory-efficient, which is important for training large models that require a lot of memory.\n",
96
+ "5. **Accelerators**: PyTorch supports a wide range of accelerators, including GPUs, TPUs, and FPGAs, which can significantly speed up training times.\n",
97
+ "6. **Modules**: PyTorch provides a wide range of pre-built modules for common tasks, such as convolutional layers, recurrent neural networks, and more.\n",
98
+ "7. **Extensive Community**: PyTorch has a large and active community of developers and users, which can be helpful for getting support and staying up-to-date with the latest developments.\n",
99
+ "8. **Easy Integration**: PyTorch can be easily integrated with other popular deep learning frameworks, such as TensorFlow and Keras.\n",
100
+ "9. **Pythonic**: PyTorch is written in Python, which is a popular and easy-to-learn programming language.\n",
101
+ "10. **Flexible**: PyTorch allows for a wide range of customization options, which can be useful for building and training unique models.\n",
102
+ "\n",
103
+ "Overall, PyTorch is a powerful and flexible deep learning framework that can be used for a wide range of applications, including computer vision, natural language processing, and more.\n"
104
+ ]
105
+ }
106
+ ]
107
+ }
108
+ ]
109
+ }
colab/webui_CodeLlama_7B_Instruct_GPTQ.ipynb ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4",
8
+ "authorship_tag": "ABX9TyOZhPcZe61RhDjhEFQv0vrl",
9
+ "include_colab_link": true
10
+ },
11
+ "kernelspec": {
12
+ "name": "python3",
13
+ "display_name": "Python 3"
14
+ },
15
+ "language_info": {
16
+ "name": "python"
17
+ },
18
+ "accelerator": "GPU"
19
+ },
20
+ "cells": [
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "view-in-github",
25
+ "colab_type": "text"
26
+ },
27
+ "source": [
28
+ "<a href=\"https://colab.research.google.com/github/liltom-eth/llama2-webui/blob/main/colab/webui_CodeLlama_7B_Instruct_GPTQ.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": null,
34
+ "metadata": {
35
+ "id": "7O5JSosg5-rx"
36
+ },
37
+ "outputs": [],
38
+ "source": [
39
+ "!pip install -U llama2-wrapper==0.1.12"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "source": [
45
+ "%cd /content\n",
46
+ "!git clone https://github.com/liltom-eth/llama2-webui\n",
47
+ "\n",
48
+ "%cd /content/llama2-webui\n",
49
+ "!python -m llama2_wrapper.download --repo_id TheBloke/CodeLlama-7B-Instruct-GPTQ\n",
50
+ "\n",
51
+ "%cd /content/llama2-webui\n",
52
+ "!python app.py --backend_type gptq --model_path ./models/CodeLlama-7B-Instruct-GPTQ/ --share True"
53
+ ],
54
+ "metadata": {
55
+ "colab": {
56
+ "base_uri": "https://localhost:8080/"
57
+ },
58
+ "id": "Y6A7bJdkmzY8",
59
+ "outputId": "0d702a7d-68ab-4747-f012-246d4dee3718"
60
+ },
61
+ "execution_count": 4,
62
+ "outputs": [
63
+ {
64
+ "output_type": "stream",
65
+ "name": "stdout",
66
+ "text": [
67
+ "/content\n",
68
+ "fatal: destination path 'llama2-webui' already exists and is not an empty directory.\n",
69
+ "/content/llama2-webui\n",
70
+ "Start downloading model TheBloke/CodeLlama-7B-Instruct-GPTQ to: ./models/CodeLlama-7B-Instruct-GPTQ\n",
71
+ "Fetching 15 files: 0% 0/15 [00:00<?, ?it/s]\n",
72
+ "Downloading (…)d0d05/.gitattributes: 100% 1.52k/1.52k [00:00<00:00, 7.94MB/s]\n",
73
+ "Fetching 15 files: 7% 1/15 [00:01<00:16, 1.15s/it]\n",
74
+ "Downloading (…)478d0d05/LICENSE.txt: 100% 7.02k/7.02k [00:00<00:00, 31.6MB/s]\n",
75
+ "\n",
76
+ "Downloading (…)478d0d05/config.json: 100% 1.25k/1.25k [00:00<00:00, 7.95MB/s]\n",
77
+ "\n",
78
+ "Downloading (…)nfiguration_llama.py: 100% 8.56k/8.56k [00:00<00:00, 41.7MB/s]\n",
79
+ "\n",
80
+ "Downloading (…)81b84478d0d05/Notice: 100% 112/112 [00:00<00:00, 750kB/s]\n",
81
+ "\n",
82
+ "Downloading (…)neration_config.json: 100% 132/132 [00:00<00:00, 836kB/s]\n",
83
+ "\n",
84
+ "Downloading (…)8d0d05/USE_POLICY.md: 100% 105/105 [00:00<00:00, 686kB/s]\n",
85
+ "\n",
86
+ "Downloading (…)84478d0d05/README.md: 100% 22.0k/22.0k [00:00<00:00, 59.5MB/s]\n",
87
+ "\n",
88
+ "Downloading (…)05/modeling_llama.py: 100% 45.9k/45.9k [00:00<00:00, 27.5MB/s]\n",
89
+ "\n",
90
+ "Downloading (…)quantize_config.json: 100% 187/187 [00:00<00:00, 1.34MB/s]\n",
91
+ "\n",
92
+ "Downloading (…)cial_tokens_map.json: 100% 411/411 [00:00<00:00, 2.82MB/s]\n",
93
+ "\n",
94
+ "Downloading (…)d0d05/tokenizer.json: 0% 0.00/1.84M [00:00<?, ?B/s]\u001b[A\n",
95
+ "\n",
96
+ "Downloading (…)okenizer_config.json: 100% 824/824 [00:00<00:00, 5.75MB/s]\n",
97
+ "\n",
98
+ "\n",
99
+ "Downloading model.safetensors: 0% 0.00/3.90G [00:00<?, ?B/s]\u001b[A\u001b[A\n",
100
+ "\n",
101
+ "\n",
102
+ "Downloading tokenizer.model: 100% 500k/500k [00:00<00:00, 16.3MB/s]\n",
103
+ "\n",
104
+ "Downloading (…)d0d05/tokenizer.json: 100% 1.84M/1.84M [00:00<00:00, 5.47MB/s]\n",
105
+ "\n",
106
+ "\n",
107
+ "Downloading model.safetensors: 0% 10.5M/3.90G [00:00<01:08, 56.4MB/s]\u001b[A\u001b[A\n",
108
+ "\n",
109
+ "Downloading model.safetensors: 1% 21.0M/3.90G [00:00<00:57, 67.1MB/s]\u001b[A\u001b[A\n",
110
+ "\n",
111
+ "Downloading model.safetensors: 1% 31.5M/3.90G [00:00<00:51, 75.5MB/s]\u001b[A\u001b[A\n",
112
+ "\n",
113
+ "Downloading model.safetensors: 1% 52.4M/3.90G [00:00<00:40, 94.5MB/s]\u001b[A\u001b[A\n",
114
+ "\n",
115
+ "Downloading model.safetensors: 2% 73.4M/3.90G [00:00<00:33, 113MB/s] \u001b[A\u001b[A\n",
116
+ "\n",
117
+ "Downloading model.safetensors: 2% 94.4M/3.90G [00:00<00:28, 133MB/s]\u001b[A\u001b[A\n",
118
+ "\n",
119
+ "Downloading model.safetensors: 3% 115M/3.90G [00:00<00:25, 148MB/s] \u001b[A\u001b[A\n",
120
+ "\n",
121
+ "Downloading model.safetensors: 3% 136M/3.90G [00:01<00:24, 156MB/s]\u001b[A\u001b[A\n",
122
+ "\n",
123
+ "Downloading model.safetensors: 4% 157M/3.90G [00:01<00:22, 167MB/s]\u001b[A\u001b[A\n",
124
+ "\n",
125
+ "Downloading model.safetensors: 5% 178M/3.90G [00:01<00:22, 168MB/s]\u001b[A\u001b[A\n",
126
+ "\n",
127
+ "Downloading model.safetensors: 5% 199M/3.90G [00:01<00:21, 169MB/s]\u001b[A\u001b[A\n",
128
+ "\n",
129
+ "Downloading model.safetensors: 6% 220M/3.90G [00:01<00:21, 170MB/s]\u001b[A\u001b[A\n",
130
+ "\n",
131
+ "Downloading model.safetensors: 6% 241M/3.90G [00:01<00:21, 174MB/s]\u001b[A\u001b[A\n",
132
+ "\n",
133
+ "Downloading model.safetensors: 7% 262M/3.90G [00:01<00:20, 177MB/s]\u001b[A\u001b[A\n",
134
+ "\n",
135
+ "Downloading model.safetensors: 7% 283M/3.90G [00:02<01:08, 52.9MB/s]\u001b[A\u001b[A\n",
136
+ "\n",
137
+ "Downloading model.safetensors: 8% 315M/3.90G [00:02<00:47, 75.6MB/s]\u001b[A\u001b[A\n",
138
+ "\n",
139
+ "Downloading model.safetensors: 9% 346M/3.90G [00:03<00:36, 97.8MB/s]\u001b[A\u001b[A\n",
140
+ "\n",
141
+ "Downloading model.safetensors: 9% 367M/3.90G [00:03<00:31, 111MB/s] \u001b[A\u001b[A\n",
142
+ "\n",
143
+ "Downloading model.safetensors: 10% 388M/3.90G [00:03<00:28, 122MB/s]\u001b[A\u001b[A\n",
144
+ "\n",
145
+ "Downloading model.safetensors: 10% 409M/3.90G [00:03<00:26, 134MB/s]\u001b[A\u001b[A\n",
146
+ "\n",
147
+ "Downloading model.safetensors: 11% 430M/3.90G [00:03<00:24, 141MB/s]\u001b[A\u001b[A\n",
148
+ "\n",
149
+ "Downloading model.safetensors: 12% 461M/3.90G [00:03<00:21, 160MB/s]\u001b[A\u001b[A\n",
150
+ "\n",
151
+ "Downloading model.safetensors: 12% 482M/3.90G [00:03<00:20, 165MB/s]\u001b[A\u001b[A\n",
152
+ "\n",
153
+ "Downloading model.safetensors: 13% 503M/3.90G [00:04<00:20, 166MB/s]\u001b[A\u001b[A\n",
154
+ "\n",
155
+ "Downloading model.safetensors: 13% 524M/3.90G [00:04<00:19, 170MB/s]\u001b[A\u001b[A\n",
156
+ "\n",
157
+ "Downloading model.safetensors: 14% 556M/3.90G [00:04<00:18, 181MB/s]\u001b[A\u001b[A\n",
158
+ "\n",
159
+ "Downloading model.safetensors: 15% 577M/3.90G [00:04<00:18, 182MB/s]\u001b[A\u001b[A\n",
160
+ "\n",
161
+ "Downloading model.safetensors: 15% 598M/3.90G [00:04<00:18, 183MB/s]\u001b[A\u001b[A\n",
162
+ "\n",
163
+ "Downloading model.safetensors: 16% 619M/3.90G [00:04<00:17, 184MB/s]\u001b[A\u001b[A\n",
164
+ "\n",
165
+ "Downloading model.safetensors: 16% 640M/3.90G [00:04<00:17, 184MB/s]\u001b[A\u001b[A\n",
166
+ "\n",
167
+ "Downloading model.safetensors: 17% 661M/3.90G [00:04<00:18, 178MB/s]\u001b[A\u001b[A\n",
168
+ "\n",
169
+ "Downloading model.safetensors: 17% 682M/3.90G [00:04<00:17, 180MB/s]\u001b[A\u001b[A\n",
170
+ "\n",
171
+ "Downloading model.safetensors: 18% 703M/3.90G [00:05<00:17, 180MB/s]\u001b[A\u001b[A\n",
172
+ "\n",
173
+ "Downloading model.safetensors: 19% 724M/3.90G [00:05<00:17, 181MB/s]\u001b[A\u001b[A\n",
174
+ "\n",
175
+ "Downloading model.safetensors: 19% 744M/3.90G [00:05<00:18, 171MB/s]\u001b[A\u001b[A\n",
176
+ "\n",
177
+ "Downloading model.safetensors: 20% 765M/3.90G [00:05<00:18, 173MB/s]\u001b[A\u001b[A\n",
178
+ "\n",
179
+ "Downloading model.safetensors: 20% 786M/3.90G [00:05<00:17, 175MB/s]\u001b[A\u001b[A\n",
180
+ "\n",
181
+ "Downloading model.safetensors: 21% 807M/3.90G [00:05<00:17, 178MB/s]\u001b[A\u001b[A\n",
182
+ "\n",
183
+ "Downloading model.safetensors: 21% 828M/3.90G [00:05<00:17, 180MB/s]\u001b[A\u001b[A\n",
184
+ "\n",
185
+ "Downloading model.safetensors: 22% 849M/3.90G [00:05<00:16, 182MB/s]\u001b[A\u001b[A\n",
186
+ "\n",
187
+ "Downloading model.safetensors: 22% 870M/3.90G [00:07<01:37, 30.9MB/s]\u001b[A\u001b[A\n",
188
+ "\n",
189
+ "Downloading model.safetensors: 23% 891M/3.90G [00:08<01:13, 40.8MB/s]\u001b[A\u001b[A\n",
190
+ "\n",
191
+ "Downloading model.safetensors: 24% 923M/3.90G [00:08<00:50, 59.3MB/s]\u001b[A\u001b[A\n",
192
+ "\n",
193
+ "Downloading model.safetensors: 24% 944M/3.90G [00:08<00:42, 70.2MB/s]\u001b[A\u001b[A\n",
194
+ "\n",
195
+ "Downloading model.safetensors: 25% 975M/3.90G [00:08<00:30, 94.3MB/s]\u001b[A\u001b[A\n",
196
+ "\n",
197
+ "Downloading model.safetensors: 26% 996M/3.90G [00:08<00:27, 107MB/s] \u001b[A\u001b[A\n",
198
+ "\n",
199
+ "Downloading model.safetensors: 26% 1.02G/3.90G [00:08<00:23, 121MB/s]\u001b[A\u001b[A\n",
200
+ "\n",
201
+ "Downloading model.safetensors: 27% 1.04G/3.90G [00:08<00:21, 134MB/s]\u001b[A\u001b[A\n",
202
+ "\n",
203
+ "Downloading model.safetensors: 27% 1.06G/3.90G [00:08<00:20, 141MB/s]\u001b[A\u001b[A\n",
204
+ "\n",
205
+ "Downloading model.safetensors: 28% 1.08G/3.90G [00:09<00:18, 151MB/s]\u001b[A\u001b[A\n",
206
+ "\n",
207
+ "Downloading model.safetensors: 28% 1.10G/3.90G [00:09<00:17, 160MB/s]\u001b[A\u001b[A\n",
208
+ "\n",
209
+ "Downloading model.safetensors: 29% 1.12G/3.90G [00:09<00:16, 166MB/s]\u001b[A\u001b[A\n",
210
+ "\n",
211
+ "Downloading model.safetensors: 29% 1.14G/3.90G [00:09<00:16, 171MB/s]\u001b[A\u001b[A\n",
212
+ "\n",
213
+ "Downloading model.safetensors: 30% 1.16G/3.90G [00:09<00:15, 175MB/s]\u001b[A\u001b[A\n",
214
+ "\n",
215
+ "Downloading model.safetensors: 30% 1.18G/3.90G [00:09<00:15, 178MB/s]\u001b[A\u001b[A\n",
216
+ "\n",
217
+ "Downloading model.safetensors: 31% 1.21G/3.90G [00:09<00:15, 179MB/s]\u001b[A\u001b[A\n",
218
+ "\n",
219
+ "Downloading model.safetensors: 31% 1.23G/3.90G [00:09<00:14, 181MB/s]\u001b[A\u001b[A\n",
220
+ "\n",
221
+ "Downloading model.safetensors: 32% 1.25G/3.90G [00:09<00:14, 182MB/s]\u001b[A\u001b[A\n",
222
+ "\n",
223
+ "Downloading model.safetensors: 33% 1.27G/3.90G [00:10<00:23, 113MB/s]\u001b[A\u001b[A\n",
224
+ "\n",
225
+ "Downloading model.safetensors: 33% 1.29G/3.90G [00:10<00:20, 128MB/s]\u001b[A\u001b[A\n",
226
+ "\n",
227
+ "Downloading model.safetensors: 34% 1.31G/3.90G [00:10<00:18, 139MB/s]\u001b[A\u001b[A\n",
228
+ "\n",
229
+ "Downloading model.safetensors: 34% 1.33G/3.90G [00:10<00:17, 150MB/s]\u001b[A\u001b[A\n",
230
+ "\n",
231
+ "Downloading model.safetensors: 35% 1.35G/3.90G [00:10<00:16, 158MB/s]\u001b[A\u001b[A\n",
232
+ "\n",
233
+ "Downloading model.safetensors: 35% 1.37G/3.90G [00:12<01:24, 29.9MB/s]\u001b[A\u001b[A\n",
234
+ "\n",
235
+ "Downloading model.safetensors: 36% 1.41G/3.90G [00:12<00:55, 45.3MB/s]\u001b[A\u001b[A\n",
236
+ "\n",
237
+ "Downloading model.safetensors: 37% 1.44G/3.90G [00:13<00:39, 63.0MB/s]\u001b[A\u001b[A\n",
238
+ "\n",
239
+ "Downloading model.safetensors: 37% 1.46G/3.90G [00:13<00:33, 72.6MB/s]\u001b[A\u001b[A\n",
240
+ "\n",
241
+ "Downloading model.safetensors: 38% 1.48G/3.90G [00:13<00:29, 82.0MB/s]\u001b[A\u001b[A\n",
242
+ "\n",
243
+ "Downloading model.safetensors: 38% 1.50G/3.90G [00:13<00:24, 98.6MB/s]\u001b[A\u001b[A\n",
244
+ "\n",
245
+ "Downloading model.safetensors: 39% 1.53G/3.90G [00:13<00:19, 124MB/s] \u001b[A\u001b[A\n",
246
+ "\n",
247
+ "Downloading model.safetensors: 40% 1.55G/3.90G [00:13<00:17, 132MB/s]\u001b[A\u001b[A\n",
248
+ "\n",
249
+ "Downloading model.safetensors: 40% 1.57G/3.90G [00:13<00:16, 143MB/s]\u001b[A\u001b[A\n",
250
+ "\n",
251
+ "Downloading model.safetensors: 41% 1.59G/3.90G [00:14<00:15, 153MB/s]\u001b[A\u001b[A\n",
252
+ "\n",
253
+ "Downloading model.safetensors: 41% 1.61G/3.90G [00:14<00:14, 160MB/s]\u001b[A\u001b[A\n",
254
+ "\n",
255
+ "Downloading model.safetensors: 42% 1.64G/3.90G [00:14<00:13, 167MB/s]\u001b[A\u001b[A\n",
256
+ "\n",
257
+ "Downloading model.safetensors: 43% 1.66G/3.90G [00:14<00:13, 171MB/s]\u001b[A\u001b[A\n",
258
+ "\n",
259
+ "Downloading model.safetensors: 43% 1.68G/3.90G [00:14<00:12, 177MB/s]\u001b[A\u001b[A\n",
260
+ "\n",
261
+ "Downloading model.safetensors: 44% 1.70G/3.90G [00:14<00:12, 174MB/s]\u001b[A\u001b[A\n",
262
+ "\n",
263
+ "Downloading model.safetensors: 44% 1.72G/3.90G [00:14<00:12, 173MB/s]\u001b[A\u001b[A\n",
264
+ "\n",
265
+ "Downloading model.safetensors: 45% 1.74G/3.90G [00:14<00:12, 175MB/s]\u001b[A\u001b[A\n",
266
+ "\n",
267
+ "Downloading model.safetensors: 45% 1.76G/3.90G [00:14<00:11, 179MB/s]\u001b[A\u001b[A\n",
268
+ "\n",
269
+ "Downloading model.safetensors: 46% 1.78G/3.90G [00:15<00:12, 172MB/s]\u001b[A\u001b[A\n",
270
+ "\n",
271
+ "Downloading model.safetensors: 46% 1.80G/3.90G [00:15<00:12, 174MB/s]\u001b[A\u001b[A\n",
272
+ "\n",
273
+ "Downloading model.safetensors: 47% 1.82G/3.90G [00:15<00:11, 177MB/s]\u001b[A\u001b[A\n",
274
+ "\n",
275
+ "Downloading model.safetensors: 47% 1.85G/3.90G [00:16<00:28, 71.9MB/s]\u001b[A\u001b[A\n",
276
+ "\n",
277
+ "Downloading model.safetensors: 48% 1.87G/3.90G [00:16<00:23, 87.4MB/s]\u001b[A\u001b[A\n",
278
+ "\n",
279
+ "Downloading model.safetensors: 49% 1.90G/3.90G [00:16<00:16, 118MB/s] \u001b[A\u001b[A\n",
280
+ "\n",
281
+ "Downloading model.safetensors: 49% 1.92G/3.90G [00:16<00:14, 132MB/s]\u001b[A\u001b[A\n",
282
+ "\n",
283
+ "Downloading model.safetensors: 50% 1.94G/3.90G [00:16<00:13, 143MB/s]\u001b[A\u001b[A\n",
284
+ "\n",
285
+ "Downloading model.safetensors: 50% 1.96G/3.90G [00:16<00:12, 152MB/s]\u001b[A\u001b[A\n",
286
+ "\n",
287
+ "Downloading model.safetensors: 51% 1.98G/3.90G [00:16<00:13, 142MB/s]\u001b[A\u001b[A\n",
288
+ "\n",
289
+ "Downloading model.safetensors: 51% 2.00G/3.90G [00:16<00:13, 144MB/s]\u001b[A\u001b[A\n",
290
+ "\n",
291
+ "Downloading model.safetensors: 52% 2.02G/3.90G [00:17<00:12, 144MB/s]\u001b[A\u001b[A\n",
292
+ "\n",
293
+ "Downloading model.safetensors: 52% 2.04G/3.90G [00:17<00:12, 148MB/s]\u001b[A\u001b[A\n",
294
+ "\n",
295
+ "Downloading model.safetensors: 53% 2.07G/3.90G [00:17<00:12, 152MB/s]\u001b[A\u001b[A\n",
296
+ "\n",
297
+ "Downloading model.safetensors: 54% 2.09G/3.90G [00:17<00:22, 81.2MB/s]\u001b[A\u001b[A\n",
298
+ "\n",
299
+ "Downloading model.safetensors: 54% 2.12G/3.90G [00:18<00:16, 107MB/s] \u001b[A\u001b[A\n",
300
+ "\n",
301
+ "Downloading model.safetensors: 55% 2.14G/3.90G [00:18<00:14, 119MB/s]\u001b[A\u001b[A\n",
302
+ "\n",
303
+ "Downloading model.safetensors: 55% 2.16G/3.90G [00:18<00:14, 123MB/s]\u001b[A\u001b[A\n",
304
+ "\n",
305
+ "Downloading model.safetensors: 56% 2.18G/3.90G [00:18<00:13, 131MB/s]\u001b[A\u001b[A\n",
306
+ "\n",
307
+ "Downloading model.safetensors: 57% 2.21G/3.90G [00:18<00:10, 156MB/s]\u001b[A\u001b[A\n",
308
+ "\n",
309
+ "Downloading model.safetensors: 57% 2.23G/3.90G [00:18<00:10, 162MB/s]\u001b[A\u001b[A\n",
310
+ "\n",
311
+ "Downloading model.safetensors: 58% 2.25G/3.90G [00:18<00:10, 160MB/s]\u001b[A\u001b[A\n",
312
+ "\n",
313
+ "Downloading model.safetensors: 59% 2.29G/3.90G [00:18<00:09, 174MB/s]\u001b[A\u001b[A\n",
314
+ "\n",
315
+ "Downloading model.safetensors: 59% 2.31G/3.90G [00:19<00:08, 178MB/s]\u001b[A\u001b[A\n",
316
+ "\n",
317
+ "Downloading model.safetensors: 60% 2.33G/3.90G [00:19<00:08, 180MB/s]\u001b[A\u001b[A\n",
318
+ "\n",
319
+ "Downloading model.safetensors: 60% 2.35G/3.90G [00:19<00:08, 181MB/s]\u001b[A\u001b[A\n",
320
+ "\n",
321
+ "Downloading model.safetensors: 61% 2.37G/3.90G [00:19<00:08, 181MB/s]\u001b[A\u001b[A\n",
322
+ "\n",
323
+ "Downloading model.safetensors: 61% 2.39G/3.90G [00:19<00:08, 181MB/s]\u001b[A\u001b[A\n",
324
+ "\n",
325
+ "Downloading model.safetensors: 62% 2.41G/3.90G [00:19<00:08, 182MB/s]\u001b[A\u001b[A\n",
326
+ "\n",
327
+ "Downloading model.safetensors: 62% 2.43G/3.90G [00:19<00:08, 182MB/s]\u001b[A\u001b[A\n",
328
+ "\n",
329
+ "Downloading model.safetensors: 63% 2.45G/3.90G [00:19<00:08, 177MB/s]\u001b[A\u001b[A\n",
330
+ "\n",
331
+ "Downloading model.safetensors: 64% 2.47G/3.90G [00:20<00:11, 124MB/s]\u001b[A\u001b[A\n",
332
+ "\n",
333
+ "Downloading model.safetensors: 64% 2.51G/3.90G [00:20<00:09, 149MB/s]\u001b[A\u001b[A\n",
334
+ "\n",
335
+ "Downloading model.safetensors: 65% 2.53G/3.90G [00:22<00:40, 34.2MB/s]\u001b[A\u001b[A\n",
336
+ "\n",
337
+ "Downloading model.safetensors: 66% 2.56G/3.90G [00:22<00:26, 50.1MB/s]\u001b[A\u001b[A\n",
338
+ "\n",
339
+ "Downloading model.safetensors: 66% 2.58G/3.90G [00:22<00:21, 60.1MB/s]\u001b[A\u001b[A\n",
340
+ "\n",
341
+ "Downloading model.safetensors: 67% 2.60G/3.90G [00:22<00:18, 69.4MB/s]\u001b[A\u001b[A\n",
342
+ "\n",
343
+ "Downloading model.safetensors: 67% 2.62G/3.90G [00:22<00:15, 84.0MB/s]\u001b[A\u001b[A\n",
344
+ "\n",
345
+ "Downloading model.safetensors: 68% 2.64G/3.90G [00:22<00:12, 99.4MB/s]\u001b[A\u001b[A\n",
346
+ "\n",
347
+ "Downloading model.safetensors: 68% 2.66G/3.90G [00:23<00:12, 96.0MB/s]\u001b[A\u001b[A\n",
348
+ "\n",
349
+ "Downloading model.safetensors: 69% 2.68G/3.90G [00:23<00:12, 95.4MB/s]\u001b[A\u001b[A\n",
350
+ "\n",
351
+ "Downloading model.safetensors: 69% 2.71G/3.90G [00:23<00:14, 84.2MB/s]\u001b[A\u001b[A\n",
352
+ "\n",
353
+ "Downloading model.safetensors: 70% 2.73G/3.90G [00:23<00:14, 82.0MB/s]\u001b[A\u001b[A\n",
354
+ "\n",
355
+ "Downloading model.safetensors: 70% 2.74G/3.90G [00:24<00:14, 80.9MB/s]\u001b[A\u001b[A\n",
356
+ "\n",
357
+ "Downloading model.safetensors: 70% 2.75G/3.90G [00:24<00:15, 75.8MB/s]\u001b[A\u001b[A\n",
358
+ "\n",
359
+ "Downloading model.safetensors: 71% 2.76G/3.90G [00:24<00:15, 75.3MB/s]\u001b[A\u001b[A\n",
360
+ "\n",
361
+ "Downloading model.safetensors: 71% 2.77G/3.90G [00:24<00:15, 72.2MB/s]\u001b[A\u001b[A\n",
362
+ "\n",
363
+ "Downloading model.safetensors: 71% 2.78G/3.90G [00:24<00:14, 74.9MB/s]\u001b[A\u001b[A\n",
364
+ "\n",
365
+ "Downloading model.safetensors: 72% 2.79G/3.90G [00:24<00:14, 74.7MB/s]\u001b[A\u001b[A\n",
366
+ "\n",
367
+ "Downloading model.safetensors: 72% 2.80G/3.90G [00:25<00:15, 69.4MB/s]\u001b[A\u001b[A\n",
368
+ "\n",
369
+ "Downloading model.safetensors: 72% 2.81G/3.90G [00:25<00:15, 71.3MB/s]\u001b[A\u001b[A\n",
370
+ "\n",
371
+ "Downloading model.safetensors: 72% 2.82G/3.90G [00:25<00:13, 77.5MB/s]\u001b[A\u001b[A\n",
372
+ "\n",
373
+ "Downloading model.safetensors: 73% 2.84G/3.90G [00:25<00:12, 84.6MB/s]\u001b[A\u001b[A\n",
374
+ "\n",
375
+ "Downloading model.safetensors: 73% 2.85G/3.90G [00:25<00:12, 83.8MB/s]\u001b[A\u001b[A\n",
376
+ "\n",
377
+ "Downloading model.safetensors: 73% 2.86G/3.90G [00:25<00:12, 81.6MB/s]\u001b[A\u001b[A\n",
378
+ "\n",
379
+ "Downloading model.safetensors: 74% 2.88G/3.90G [00:25<00:10, 97.2MB/s]\u001b[A\u001b[A\n",
380
+ "\n",
381
+ "Downloading model.safetensors: 75% 2.90G/3.90G [00:26<00:08, 118MB/s] \u001b[A\u001b[A\n",
382
+ "\n",
383
+ "Downloading model.safetensors: 75% 2.93G/3.90G [00:26<00:07, 134MB/s]\u001b[A\u001b[A\n",
384
+ "\n",
385
+ "Downloading model.safetensors: 76% 2.95G/3.90G [00:26<00:06, 149MB/s]\u001b[A\u001b[A\n",
386
+ "\n",
387
+ "Downloading model.safetensors: 76% 2.97G/3.90G [00:26<00:05, 159MB/s]\u001b[A\u001b[A\n",
388
+ "\n",
389
+ "Downloading model.safetensors: 77% 2.99G/3.90G [00:27<00:23, 37.9MB/s]\u001b[A\u001b[A\n",
390
+ "\n",
391
+ "Downloading model.safetensors: 77% 3.02G/3.90G [00:27<00:15, 57.4MB/s]\u001b[A\u001b[A\n",
392
+ "\n",
393
+ "Downloading model.safetensors: 78% 3.04G/3.90G [00:28<00:12, 67.9MB/s]\u001b[A\u001b[A\n",
394
+ "\n",
395
+ "Downloading model.safetensors: 79% 3.06G/3.90G [00:28<00:10, 78.8MB/s]\u001b[A\u001b[A\n",
396
+ "\n",
397
+ "Downloading model.safetensors: 79% 3.08G/3.90G [00:28<00:08, 92.9MB/s]\u001b[A\u001b[A\n",
398
+ "\n",
399
+ "Downloading model.safetensors: 80% 3.10G/3.90G [00:28<00:07, 109MB/s] \u001b[A\u001b[A\n",
400
+ "\n",
401
+ "Downloading model.safetensors: 80% 3.14G/3.90G [00:28<00:05, 138MB/s]\u001b[A\u001b[A\n",
402
+ "\n",
403
+ "Downloading model.safetensors: 81% 3.16G/3.90G [00:28<00:05, 146MB/s]\u001b[A\u001b[A\n",
404
+ "\n",
405
+ "Downloading model.safetensors: 82% 3.18G/3.90G [00:28<00:04, 152MB/s]\u001b[A\u001b[A\n",
406
+ "\n",
407
+ "Downloading model.safetensors: 82% 3.20G/3.90G [00:29<00:04, 161MB/s]\u001b[A\u001b[A\n",
408
+ "\n",
409
+ "Downloading model.safetensors: 83% 3.22G/3.90G [00:29<00:03, 170MB/s]\u001b[A\u001b[A\n",
410
+ "\n",
411
+ "Downloading model.safetensors: 83% 3.24G/3.90G [00:29<00:04, 158MB/s]\u001b[A\u001b[A\n",
412
+ "\n",
413
+ "Downloading model.safetensors: 84% 3.26G/3.90G [00:29<00:04, 156MB/s]\u001b[A\u001b[A\n",
414
+ "\n",
415
+ "Downloading model.safetensors: 84% 3.28G/3.90G [00:29<00:03, 160MB/s]\u001b[A\u001b[A\n",
416
+ "\n",
417
+ "Downloading model.safetensors: 85% 3.30G/3.90G [00:29<00:03, 162MB/s]\u001b[A\u001b[A\n",
418
+ "\n",
419
+ "Downloading model.safetensors: 85% 3.32G/3.90G [00:29<00:03, 160MB/s]\u001b[A\u001b[A\n",
420
+ "\n",
421
+ "Downloading model.safetensors: 86% 3.34G/3.90G [00:29<00:03, 171MB/s]\u001b[A\u001b[A\n",
422
+ "\n",
423
+ "Downloading model.safetensors: 87% 3.38G/3.90G [00:30<00:02, 191MB/s]\u001b[A\u001b[A\n",
424
+ "\n",
425
+ "Downloading model.safetensors: 87% 3.40G/3.90G [00:30<00:02, 188MB/s]\u001b[A\u001b[A\n",
426
+ "\n",
427
+ "Downloading model.safetensors: 88% 3.42G/3.90G [00:30<00:02, 187MB/s]\u001b[A\u001b[A\n",
428
+ "\n",
429
+ "Downloading model.safetensors: 88% 3.44G/3.90G [00:30<00:02, 182MB/s]\u001b[A\u001b[A\n",
430
+ "\n",
431
+ "Downloading model.safetensors: 89% 3.46G/3.90G [00:30<00:02, 183MB/s]\u001b[A\u001b[A\n",
432
+ "\n",
433
+ "Downloading model.safetensors: 89% 3.48G/3.90G [00:30<00:02, 183MB/s]\u001b[A\u001b[A\n",
434
+ "\n",
435
+ "Downloading model.safetensors: 90% 3.50G/3.90G [00:30<00:02, 184MB/s]\u001b[A\u001b[A\n",
436
+ "\n",
437
+ "Downloading model.safetensors: 90% 3.52G/3.90G [00:30<00:02, 185MB/s]\u001b[A\u001b[A\n",
438
+ "\n",
439
+ "Downloading model.safetensors: 91% 3.54G/3.90G [00:30<00:01, 183MB/s]\u001b[A\u001b[A\n",
440
+ "\n",
441
+ "Downloading model.safetensors: 91% 3.57G/3.90G [00:31<00:05, 55.5MB/s]\u001b[A\u001b[A\n",
442
+ "\n",
443
+ "Downloading model.safetensors: 92% 3.59G/3.90G [00:32<00:08, 38.3MB/s]\u001b[A\u001b[A\n",
444
+ "\n",
445
+ "Downloading model.safetensors: 93% 3.61G/3.90G [00:32<00:05, 50.7MB/s]\u001b[A\u001b[A\n",
446
+ "\n",
447
+ "Downloading model.safetensors: 93% 3.63G/3.90G [00:33<00:04, 65.0MB/s]\u001b[A\u001b[A\n",
448
+ "\n",
449
+ "Downloading model.safetensors: 94% 3.65G/3.90G [00:33<00:03, 80.3MB/s]\u001b[A\u001b[A\n",
450
+ "\n",
451
+ "Downloading model.safetensors: 94% 3.67G/3.90G [00:33<00:02, 97.3MB/s]\u001b[A\u001b[A\n",
452
+ "\n",
453
+ "Downloading model.safetensors: 95% 3.69G/3.90G [00:33<00:01, 113MB/s] \u001b[A\u001b[A\n",
454
+ "\n",
455
+ "Downloading model.safetensors: 95% 3.71G/3.90G [00:33<00:01, 128MB/s]\u001b[A\u001b[A\n",
456
+ "\n",
457
+ "Downloading model.safetensors: 96% 3.73G/3.90G [00:33<00:01, 139MB/s]\u001b[A\u001b[A\n",
458
+ "\n",
459
+ "Downloading model.safetensors: 96% 3.75G/3.90G [00:33<00:00, 153MB/s]\u001b[A\u001b[A\n",
460
+ "\n",
461
+ "Downloading model.safetensors: 97% 3.77G/3.90G [00:33<00:00, 158MB/s]\u001b[A\u001b[A\n",
462
+ "\n",
463
+ "Downloading model.safetensors: 97% 3.80G/3.90G [00:34<00:00, 165MB/s]\u001b[A\u001b[A\n",
464
+ "\n",
465
+ "Downloading model.safetensors: 98% 3.82G/3.90G [00:34<00:00, 167MB/s]\u001b[A\u001b[A\n",
466
+ "\n",
467
+ "Downloading model.safetensors: 98% 3.84G/3.90G [00:34<00:00, 169MB/s]\u001b[A\u001b[A\n",
468
+ "\n",
469
+ "Downloading model.safetensors: 99% 3.86G/3.90G [00:34<00:00, 174MB/s]\u001b[A\u001b[A\n",
470
+ "\n",
471
+ "Downloading model.safetensors: 100% 3.90G/3.90G [00:34<00:00, 113MB/s]\n",
472
+ "Fetching 15 files: 100% 15/15 [00:36<00:00, 2.41s/it]\n",
473
+ "/content/llama2-webui\n",
474
+ "Running on GPU with backend torch transformers.\n",
475
+ "2023-08-26 07:14:25.222792: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
476
+ "skip module injection for FusedLlamaMLPForQuantizedModel not support integrate without triton yet.\n",
477
+ "Caching examples at: '/content/llama2-webui/gradio_cached_examples/19'\n",
478
+ "Caching example 1/5\n",
479
+ "Caching example 2/5\n",
480
+ "Caching example 3/5\n",
481
+ "Caching example 4/5\n",
482
+ "Caching example 5/5\n",
483
+ "Caching complete\n",
484
+ "\n",
485
+ "Running on local URL: http://127.0.0.1:7860\n",
486
+ "Running on public URL: https://71c3606942c440e7dd.gradio.live\n",
487
+ "\n",
488
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n",
489
+ "Keyboard interruption in main thread... closing server.\n",
490
+ "Traceback (most recent call last):\n",
491
+ " File \"/usr/local/lib/python3.10/dist-packages/gradio/blocks.py\", line 2130, in block_thread\n",
492
+ " time.sleep(0.1)\n",
493
+ "KeyboardInterrupt\n",
494
+ "\n",
495
+ "During handling of the above exception, another exception occurred:\n",
496
+ "\n",
497
+ "Traceback (most recent call last):\n",
498
+ " File \"/content/llama2-webui/app.py\", line 322, in <module>\n",
499
+ " main()\n",
500
+ " File \"/content/llama2-webui/app.py\", line 318, in main\n",
501
+ " demo.queue(max_size=20).launch(share=args.share)\n",
502
+ " File \"/usr/local/lib/python3.10/dist-packages/gradio/blocks.py\", line 2046, in launch\n",
503
+ " self.block_thread()\n",
504
+ " File \"/usr/local/lib/python3.10/dist-packages/gradio/blocks.py\", line 2132, in block_thread\n",
505
+ " print(\"Keyboard interruption in main thread... closing server.\")\n",
506
+ "KeyboardInterrupt\n",
507
+ "Killing tunnel 127.0.0.1:7860 <> https://71c3606942c440e7dd.gradio.live\n",
508
+ "terminate called without an active exception\n"
509
+ ]
510
+ }
511
+ ]
512
+ }
513
+ ]
514
+ }
docs/issues.md ADDED
File without changes
docs/news.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # News
2
+ - [2023/09] The newest `llama2-wrapper>=0.1.14` supports llama.cpp's `gguf` models.
3
+
4
+ - [2023/08] 🔥 For developers, we offer a web server that acts as a drop-in replacement for the OpenAI API.
5
+
6
+ - Usage:
7
+
8
+ ```
9
+ python3 -m llama2_wrapper.server
10
+ ```
11
+
12
+
13
+
14
+ - [2023/08] 🔥 For developers, we released `llama2-wrapper` as a llama2 backend wrapper in [PYPI](https://pypi.org/project/llama2-wrapper/).
15
+
16
+ - Install: `pip install llama2-wrapper`
17
+
18
+ - Usage:
19
+
20
+ ```python
21
+ from llama2_wrapper import LLAMA2_WRAPPER, get_prompt
22
+ llama2_wrapper = LLAMA2_WRAPPER(
23
+ model_path="./models/Llama-2-7B-Chat-GGML/llama-2-7b-chat.ggmlv3.q4_0.bin",
24
+ backend_type="llama.cpp", #options: llama.cpp, transformers, gptq
25
+ )
26
+ prompt = "Do you know Pytorch"
27
+ llama2_promt = get_prompt(prompt)
28
+ answer = llama2_wrapper(llama2_promt, temperature=0.9)
29
+ ```
30
+
31
+ - [2023/08] 🔥 We added `benchmark.py` for users to benchmark llama2 models on their local devices.
32
+
33
+ - Check/contribute the performance of your device in the full [performance doc](https://github.com/liltom-eth/llama2-webui/blob/main/docs/performance.md).
34
+
35
+ - [2023/07] We released **[llama2-webui](https://github.com/liltom-eth/llama2-webui)**, a gradio web UI to run Llama 2 on GPU or CPU from anywhere (Linux/Windows/Mac).
36
+
37
+ - Supporting models: [Llama-2-7b](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf)/[13b](https://huggingface.co/llamaste/Llama-2-13b-chat-hf)/[70b](https://huggingface.co/llamaste/Llama-2-70b-chat-hf), all [Llama-2-GPTQ](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GPTQ), all [Llama-2-GGML](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML) ...
38
+ - Supporting model backends: [tranformers](https://github.com/huggingface/transformers), [bitsandbytes(8-bit inference)](https://github.com/TimDettmers/bitsandbytes), [AutoGPTQ(4-bit inference)](https://github.com/PanQiWei/AutoGPTQ), [llama.cpp](https://github.com/ggerganov/llama.cpp)
docs/performance.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Benchmark Performance
2
+
3
+ ## Performance on Nvidia GPU
4
+
5
+ | Model | Precision | Device | GPU VRAM | Speed (tokens/sec) | load time (s) |
6
+ | --------------------------------- | --------- | ---------- | ---------------------- | ---------------- | ---------------- |
7
+ | Llama-2-7b-chat-hf | 16 bit | | | | |
8
+ | Llama-2-7b-chat-hf | 8bit | NVIDIA RTX 2080 Ti | 7.7 GB VRAM | 3.76 | 641.36 |
9
+ | Llama-2-7b-Chat-GPTQ | 4bit | NVIDIA RTX 2080 Ti | 5.8 GB VRAM | 18.85 | 192.91 |
10
+ | Llama-2-7b-Chat-GPTQ | 4bit | NVIDIA GTX 1660 Super | 4.8 GB VRAM | 8.5 | 262.74 |
11
+ | Llama-2-7b-Chat-GPTQ | 4 bit | Google Colab T4 | 5.8 GB VRAM | 18.19 | 37.44 |
12
+ | Llama-2-13b-chat-hf | 16 bit | | | | |
13
+ | | | | | | |
14
+
15
+ ## Performance on CPU / OpenBLAS / cuBLAS / CLBlast / Metal
16
+
17
+ | Model | Precision | Device | RAM / GPU VRAM | Speed (tokens/sec) | load time (s) |
18
+ | --------------------------------- | --------- | ---------- | ---------------------- | ---------------- | ---------------- |
19
+ | llama-2-7b-chat.ggmlv3.q2_K | 2 bit | Intel i7-8700 | 4.5 GB RAM | 7.88 | 31.90 |
20
+ | llama-2-7b-chat.ggmlv3.q2_K | 2 bit | Apple M2 CPU | 4.5 GB RAM | 11.10 | 0.10 |
21
+ | llama-2-7b-chat.ggmlv3.q2_K | 2 bit | Apple M2 Metal | 4.5 GB RAM | 12.10 | 0.12 |
22
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Intel i7-8700 | 5.4 GB RAM | 6.27 | 173.15 |
23
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Intel i7-9700 | 4.8 GB RAM | 4.2 | 87.9 |
24
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Apple M1 Pro CPU | 5.4 GB RAM | 17.90 | 0.18 |
25
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Apple M2 CPU | 5.4 GB RAM | 13.70 | 0.13 |
26
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Apple M2 Metal | 5.4 GB RAM | 12.60 | 0.10 |
27
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | AMD Ryzen 9 5900HS | 4.1 GB RAM | 6.01 | 0.15 |
28
+ | llama-2-7b-chat.ggmlv3.q4_0 | 4 bit | Intel vServer 4 threads, eth services | 8 GB RAM | 1.31 | 0.5|
29
+ | llama-2-7b-chat.ggmlv3.q8_0 | 8 bit | Intel i7-8700 | 8.6 GB RAM | 2.63 | 336.57 |
30
+ | llama-2-7b-chat.ggmlv3.q8_0 | 8 bit | Intel i7-9700 | 7.6 GB RAM | 2.05 | 302.9 |
31
+ | | | | | | |
32
+
docs/pypi.md ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # llama2-wrapper
2
+
3
+ - Use [llama2-wrapper](https://pypi.org/project/llama2-wrapper/) as your local llama2 backend for Generative Agents/Apps, [colab example](https://github.com/liltom-eth/llama2-webui/blob/main/colab/Llama_2_7b_Chat_GPTQ.ipynb).
4
+
5
+ - [Run OpenAI Compatible API](https://github.com/liltom-eth/llama2-webui#start-openai-compatible-api) on Llama2 models.
6
+
7
+ ## Features
8
+
9
+ - Supporting models: [Llama-2-7b](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf)/[13b](https://huggingface.co/llamaste/Llama-2-13b-chat-hf)/[70b](https://huggingface.co/llamaste/Llama-2-70b-chat-hf), [Llama-2-GPTQ](https://huggingface.co/TheBloke/Llama-2-7b-Chat-GPTQ), [Llama-2-GGML](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGML), [CodeLlama](https://huggingface.co/TheBloke/CodeLlama-7B-Instruct-GPTQ)...
10
+ - Supporting model backends: [tranformers](https://github.com/huggingface/transformers), [bitsandbytes(8-bit inference)](https://github.com/TimDettmers/bitsandbytes), [AutoGPTQ(4-bit inference)](https://github.com/PanQiWei/AutoGPTQ), [llama.cpp](https://github.com/ggerganov/llama.cpp)
11
+ - Demos: [Run Llama2 on MacBook Air](https://twitter.com/liltom_eth/status/1682791729207070720?s=20); [Run Llama2 on Colab T4 GPU](https://github.com/liltom-eth/llama2-webui/blob/main/colab/Llama_2_7b_Chat_GPTQ.ipynb)
12
+ - Use [llama2-wrapper](https://pypi.org/project/llama2-wrapper/) as your local llama2 backend for Generative Agents/Apps; [colab example](./colab/Llama_2_7b_Chat_GPTQ.ipynb).
13
+ - [Run OpenAI Compatible API](https://github.com/liltom-eth/llama2-webui#start-openai-compatible-api) on Llama2 models.
14
+ - [News](https://github.com/liltom-eth/llama2-webui/blob/main/docs/news.md), [Benchmark](https://github.com/liltom-eth/llama2-webui/blob/main/docs/performance.md), [Issue Solutions](https://github.com/liltom-eth/llama2-webui/blob/main/docs/issues.md)
15
+
16
+ [llama2-wrapper](https://pypi.org/project/llama2-wrapper/) is the backend and part of [llama2-webui](https://github.com/liltom-eth/llama2-webui), which can run any Llama 2 locally with gradio UI on GPU or CPU from anywhere (Linux/Windows/Mac).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install llama2-wrapper
22
+ ```
23
+
24
+ ## Start OpenAI Compatible API
25
+
26
+ ```
27
+ python -m llama2_wrapper.server
28
+ ```
29
+
30
+ it will use `llama.cpp` as the backend by default to run `llama-2-7b-chat.ggmlv3.q4_0.bin` model.
31
+
32
+ Start Fast API for `gptq` backend:
33
+
34
+ ```
35
+ python -m llama2_wrapper.server --backend_type gptq
36
+ ```
37
+
38
+ Navigate to http://localhost:8000/docs to see the OpenAPI documentation.
39
+
40
+ ## API Usage
41
+
42
+ ### `__call__`
43
+
44
+ `__call__()` is the function to generate text from a prompt.
45
+
46
+ For example, run ggml llama2 model on CPU, [colab example](https://github.com/liltom-eth/llama2-webui/blob/main/colab/ggmlv3_q4_0.ipynb):
47
+
48
+ ```python
49
+ from llama2_wrapper import LLAMA2_WRAPPER, get_prompt
50
+ llama2_wrapper = LLAMA2_WRAPPER()
51
+ # Default running on backend llama.cpp.
52
+ # Automatically downloading model to: ./models/llama-2-7b-chat.ggmlv3.q4_0.bin
53
+ prompt = "Do you know Pytorch"
54
+ # llama2_wrapper() will run __call__()
55
+ answer = llama2_wrapper(get_prompt(prompt), temperature=0.9)
56
+ ```
57
+
58
+ Run gptq llama2 model on Nvidia GPU, [colab example](https://github.com/liltom-eth/llama2-webui/blob/main/colab/Llama_2_7b_Chat_GPTQ.ipynb):
59
+
60
+ ```python
61
+ from llama2_wrapper import LLAMA2_WRAPPER
62
+ llama2_wrapper = LLAMA2_WRAPPER(backend_type="gptq")
63
+ # Automatically downloading model to: ./models/Llama-2-7b-Chat-GPTQ
64
+ ```
65
+
66
+ Run llama2 7b with bitsandbytes 8 bit with a `model_path`:
67
+
68
+ ```python
69
+ from llama2_wrapper import LLAMA2_WRAPPER
70
+ llama2_wrapper = LLAMA2_WRAPPER(
71
+ model_path = "./models/Llama-2-7b-chat-hf",
72
+ backend_type = "transformers",
73
+ load_in_8bit = True
74
+ )
75
+ ```
76
+
77
+ ### completion
78
+
79
+ `completion()` is the function to generate text from a prompt for OpenAI compatible API `/v1/completions`.
80
+
81
+ ```python
82
+ llama2_wrapper = LLAMA2_WRAPPER()
83
+ prompt = get_prompt("Hi do you know Pytorch?")
84
+ print(llm.completion(prompt))
85
+ ```
86
+
87
+ ### chat_completion
88
+
89
+ `chat_completion()` is the function to generate text from a dialog (chat history) for OpenAI compatible API `/v1/chat/completions`.
90
+
91
+ ```python
92
+ llama2_wrapper = LLAMA2_WRAPPER()
93
+ dialog = [
94
+ {
95
+ "role":"system",
96
+ "content":"You are a helpful, respectful and honest assistant. "
97
+ },{
98
+ "role":"user",
99
+ "content":"Hi do you know Pytorch?",
100
+ },
101
+ ]
102
+ print(llm.chat_completion(dialog))
103
+ ```
104
+
105
+ ### generate
106
+
107
+ `generate()` is the function to create a generator of response from a prompt.
108
+
109
+ This is useful when you want to stream the output like typing in the chatbot.
110
+
111
+ ```python
112
+ llama2_wrapper = LLAMA2_WRAPPER()
113
+ prompt = get_prompt("Hi do you know Pytorch?")
114
+ for response in llama2_wrapper.generate(prompt):
115
+ print(response)
116
+
117
+ ```
118
+
119
+ The response will be like:
120
+
121
+ ```
122
+ Yes,
123
+ Yes, I'm
124
+ Yes, I'm familiar
125
+ Yes, I'm familiar with
126
+ Yes, I'm familiar with PyTorch!
127
+ ...
128
+ ```
129
+
130
+ ### run
131
+
132
+ `run()` is similar to `generate()`, but `run()`can also accept `chat_history`and `system_prompt` from the users.
133
+
134
+ It will process the input message to llama2 prompt template with `chat_history` and `system_prompt` for a chatbot-like app.
135
+
136
+ ### get_prompt
137
+
138
+ `get_prompt()` will process the input message to llama2 prompt with `chat_history` and `system_prompt`for chatbot.
139
+
140
+ By default, `chat_history` and `system_prompt` are empty and `get_prompt()` will add llama2 prompt template to your message:
141
+
142
+ ```python
143
+ prompt = get_prompt("Hi do you know Pytorch?")
144
+ ```
145
+
146
+ prompt will be:
147
+
148
+ ```
149
+ [INST] <<SYS>>
150
+
151
+ <</SYS>>
152
+
153
+ Hi do you know Pytorch? [/INST]
154
+ ```
155
+
156
+ If use `get_prompt("Hi do you know Pytorch?", system_prompt="You are a helpful...")`:
157
+
158
+ ```
159
+ [INST] <<SYS>>
160
+ You are a helpful, respectful and honest assistant.
161
+ <</SYS>>
162
+
163
+ Hi do you know Pytorch? [/INST]
164
+ ```
165
+
166
+ ### get_prompt_for_dialog
167
+
168
+ `get_prompt_for_dialog()` will process dialog (chat history) to llama2 prompt for OpenAI compatible API `/v1/chat/completions`.
169
+
170
+ ```python
171
+ dialog = [
172
+ {
173
+ "role":"system",
174
+ "content":"You are a helpful, respectful and honest assistant. "
175
+ },{
176
+ "role":"user",
177
+ "content":"Hi do you know Pytorch?",
178
+ },
179
+ ]
180
+ prompt = get_prompt_for_dialog("Hi do you know Pytorch?")
181
+ # [INST] <<SYS>>
182
+ # You are a helpful, respectful and honest assistant.
183
+ # <</SYS>>
184
+ #
185
+ # Hi do you know Pytorch? [/INST]
186
+ ```
187
+
env_examples/.env.13b_example ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL_PATH = "./models/Llama-2-13b-chat-hf"
2
+
3
+ # options: llama.cpp, gptq, transformers
4
+ BACKEND_TYPE = "transformers"
5
+
6
+ # only for transformers bitsandbytes 8 bit
7
+ LOAD_IN_8BIT = True
8
+
9
+ MAX_MAX_NEW_TOKENS = 2048
10
+ DEFAULT_MAX_NEW_TOKENS = 1024
11
+ MAX_INPUT_TOKEN_LENGTH = 4000
12
+
13
+ DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
env_examples/.env.7b_8bit_example ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL_PATH = "./models/Llama-2-7b-chat-hf"
2
+
3
+ # options: llama.cpp, gptq, transformers
4
+ BACKEND_TYPE = "transformers"
5
+
6
+ # only for transformers bitsandbytes 8 bit
7
+ LOAD_IN_8BIT = True
8
+
9
+ MAX_MAX_NEW_TOKENS = 2048
10
+ DEFAULT_MAX_NEW_TOKENS = 1024
11
+ MAX_INPUT_TOKEN_LENGTH = 4000
12
+
13
+ DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
env_examples/.env.7b_ggmlv3_q4_0_example ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL_PATH = ""
2
+ # if MODEL_PATH is "", default llama.cpp/gptq models
3
+ # will be downloaded to: ./models
4
+
5
+ # Example ggml path:
6
+ # MODEL_PATH = "./models/llama-2-7b-chat.ggmlv3.q4_0.bin"
7
+
8
+ # options: llama.cpp, gptq, transformers
9
+ BACKEND_TYPE = "llama.cpp"
10
+
11
+ # only for transformers bitsandbytes 8 bit
12
+ LOAD_IN_8BIT = False
13
+
14
+ MAX_MAX_NEW_TOKENS = 2048
15
+ DEFAULT_MAX_NEW_TOKENS = 1024
16
+ MAX_INPUT_TOKEN_LENGTH = 4000
17
+
18
+ DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
env_examples/.env.7b_gptq_example ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MODEL_PATH = "./models/Llama-2-7b-Chat-GPTQ"
2
+ # if MODEL_PATH is "", default llama.cpp/gptq models
3
+ # will be downloaded to: ./models
4
+
5
+ # Example gptq path:
6
+ # MODEL_PATH = "./models/Llama-2-7b-Chat-GPTQ"
7
+
8
+ # options: llama.cpp, gptq, transformers
9
+ BACKEND_TYPE = "gptq"
10
+
11
+ # only for transformers bitsandbytes 8 bit
12
+ LOAD_IN_8BIT = False
13
+
14
+ MAX_MAX_NEW_TOKENS = 2048
15
+ DEFAULT_MAX_NEW_TOKENS = 1024
16
+ MAX_INPUT_TOKEN_LENGTH = 4000
17
+
18
+ DEFAULT_SYSTEM_PROMPT = "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
llama2_wrapper/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .model import LLAMA2_WRAPPER, get_prompt, get_prompt_for_dialog
llama2_wrapper/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (294 Bytes). View file
 
llama2_wrapper/__pycache__/model.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
llama2_wrapper/__pycache__/types.cpython-310.pyc ADDED
Binary file (4.1 kB). View file
 
llama2_wrapper/download/__init__.py ADDED
File without changes
llama2_wrapper/download/__main__.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+
4
+
5
+ def main():
6
+ parser = argparse.ArgumentParser()
7
+ parser.add_argument(
8
+ "--repo_id",
9
+ type=str,
10
+ default="",
11
+ required=True,
12
+ help="Repo ID like 'TheBloke/Llama-2-7B-Chat-GGML' ",
13
+ )
14
+ parser.add_argument(
15
+ "--filename",
16
+ type=str,
17
+ default=None,
18
+ help="Filename like llama-2-7b-chat.ggmlv3.q4_0.bin",
19
+ )
20
+ parser.add_argument(
21
+ "--save_dir", type=str, default="./models", help="Directory to save models"
22
+ )
23
+
24
+ args = parser.parse_args()
25
+
26
+ repo_id = args.repo_id
27
+ save_dir = args.save_dir
28
+
29
+ if not os.path.exists(save_dir):
30
+ os.makedirs(save_dir)
31
+
32
+ if args.filename:
33
+ filename = args.filename
34
+ from huggingface_hub import hf_hub_download
35
+
36
+ print(f"Start downloading model {repo_id} {filename} to: {save_dir}")
37
+
38
+ hf_hub_download(
39
+ repo_id=repo_id,
40
+ filename=filename,
41
+ local_dir=save_dir,
42
+ )
43
+ else:
44
+ repo_name = repo_id.split("/")[1]
45
+ save_path = os.path.join(save_dir, repo_name)
46
+ if not os.path.exists(save_path):
47
+ os.makedirs(save_path)
48
+ print(f"Start downloading model {repo_id} to: {save_path}")
49
+
50
+ from huggingface_hub import snapshot_download
51
+
52
+ snapshot_download(
53
+ repo_id=repo_id,
54
+ local_dir=save_path,
55
+ )
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
llama2_wrapper/download/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (206 Bytes). View file
 
llama2_wrapper/download/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (1.29 kB). View file
 
llama2_wrapper/model.py ADDED
@@ -0,0 +1,787 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import uuid
4
+ from enum import Enum
5
+ from threading import Thread
6
+ from typing import Any, Iterator, Union, List
7
+ from llama2_wrapper.types import (
8
+ Completion,
9
+ CompletionChunk,
10
+ ChatCompletion,
11
+ ChatCompletionChunk,
12
+ # ChatCompletionMessage,
13
+ Message,
14
+ B_INST,
15
+ E_INST,
16
+ B_SYS,
17
+ E_SYS,
18
+ )
19
+
20
+
21
+ class LLAMA2_WRAPPER:
22
+ def __init__(
23
+ self,
24
+ model_path: str = "",
25
+ backend_type: str = "llama.cpp",
26
+ max_tokens: int = 4000,
27
+ load_in_8bit: bool = True,
28
+ verbose: bool = False,
29
+ ):
30
+ """Load a llama2 model from `model_path`.
31
+
32
+ Args:
33
+ model_path: Path to the model.
34
+ backend_type: Backend for llama2, options: llama.cpp, gptq, transformers
35
+ max_tokens: Maximum context size.
36
+ load_in_8bit: Use bitsandbytes to run model in 8 bit mode (only for transformers models).
37
+ verbose: Print verbose output to stderr.
38
+
39
+ Raises:
40
+ ValueError: If the model path does not exist.
41
+
42
+ Returns:
43
+ A LLAMA2_WRAPPER instance.
44
+ """
45
+ self.model_path = model_path
46
+ self.backend_type = BackendType.get_type(backend_type)
47
+ self.max_tokens = max_tokens
48
+ self.load_in_8bit = load_in_8bit
49
+
50
+ self.model = None
51
+ self.tokenizer = None
52
+
53
+ self.verbose = verbose
54
+
55
+ if self.backend_type is BackendType.LLAMA_CPP:
56
+ print("Running on backend llama.cpp.")
57
+ else:
58
+ import torch
59
+
60
+ if torch.cuda.is_available():
61
+ print("Running on GPU with backend torch transformers.")
62
+ else:
63
+ print("GPU CUDA not found.")
64
+
65
+ self.default_llamacpp_path = "./models/llama-2-7b-chat.Q4_0.gguf"
66
+ self.default_gptq_path = "./models/Llama-2-7b-Chat-GPTQ"
67
+ # Download default ggml/gptq model
68
+ if self.model_path == "":
69
+ print("Model path is empty.")
70
+ if self.backend_type is BackendType.LLAMA_CPP:
71
+ print("Use default llama.cpp model path: " + self.default_llamacpp_path)
72
+ if not os.path.exists(self.default_llamacpp_path):
73
+ print("Start downloading model to: " + self.default_llamacpp_path)
74
+ from huggingface_hub import hf_hub_download
75
+
76
+ hf_hub_download(
77
+ repo_id="TheBloke/Llama-2-7b-Chat-GGUF",
78
+ filename="llama-2-7b-chat.Q4_0.gguf",
79
+ local_dir="./models/",
80
+ )
81
+ else:
82
+ print("Model exists in ./models/llama-2-7b-chat.Q4_0.gguf.")
83
+ self.model_path = self.default_llamacpp_path
84
+ elif self.backend_type is BackendType.GPTQ:
85
+ print("Use default gptq model path: " + self.default_gptq_path)
86
+ if not os.path.exists(self.default_gptq_path):
87
+ print("Start downloading model to: " + self.default_gptq_path)
88
+ from huggingface_hub import snapshot_download
89
+
90
+ snapshot_download(
91
+ "TheBloke/Llama-2-7b-Chat-GPTQ",
92
+ local_dir=self.default_gptq_path,
93
+ )
94
+ else:
95
+ print("Model exists in " + self.default_gptq_path)
96
+ self.model_path = self.default_gptq_path
97
+
98
+ self.init_tokenizer()
99
+ self.init_model()
100
+
101
+ def init_model(self):
102
+ if self.model is None:
103
+ self.model = LLAMA2_WRAPPER.create_llama2_model(
104
+ self.model_path,
105
+ self.backend_type,
106
+ self.max_tokens,
107
+ self.load_in_8bit,
108
+ self.verbose,
109
+ )
110
+ if self.backend_type is not BackendType.LLAMA_CPP:
111
+ self.model.eval()
112
+
113
+ def init_tokenizer(self):
114
+ if self.backend_type is not BackendType.LLAMA_CPP:
115
+ if self.tokenizer is None:
116
+ self.tokenizer = LLAMA2_WRAPPER.create_llama2_tokenizer(self.model_path)
117
+
118
+ @classmethod
119
+ def create_llama2_model(
120
+ cls, model_path, backend_type, max_tokens, load_in_8bit, verbose
121
+ ):
122
+ if backend_type is BackendType.LLAMA_CPP:
123
+ from llama_cpp import Llama
124
+
125
+ model = Llama(
126
+ model_path=model_path,
127
+ n_ctx=max_tokens,
128
+ n_batch=max_tokens,
129
+ verbose=verbose,
130
+ )
131
+ elif backend_type is BackendType.GPTQ:
132
+ from auto_gptq import AutoGPTQForCausalLM
133
+
134
+ model = AutoGPTQForCausalLM.from_quantized(
135
+ model_path,
136
+ use_safetensors=True,
137
+ trust_remote_code=True,
138
+ device="cuda:0",
139
+ use_triton=False,
140
+ quantize_config=None,
141
+ )
142
+ elif backend_type is BackendType.TRANSFORMERS:
143
+ import torch
144
+ from transformers import AutoModelForCausalLM
145
+
146
+ model = AutoModelForCausalLM.from_pretrained(
147
+ model_path,
148
+ device_map="auto",
149
+ torch_dtype=torch.float16,
150
+ load_in_8bit=load_in_8bit,
151
+ )
152
+ else:
153
+ print(backend_type + "not implemented.")
154
+ return model
155
+
156
+ @classmethod
157
+ def create_llama2_tokenizer(cls, model_path):
158
+ from transformers import AutoTokenizer
159
+
160
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
161
+ return tokenizer
162
+
163
+ def get_token_length(
164
+ self,
165
+ prompt: str,
166
+ ) -> int:
167
+ if self.backend_type is BackendType.LLAMA_CPP:
168
+ input_ids = self.model.tokenize(bytes(prompt, "utf-8"))
169
+ return len(input_ids)
170
+ else:
171
+ input_ids = self.tokenizer([prompt], return_tensors="np")["input_ids"]
172
+ return input_ids.shape[-1]
173
+
174
+ def get_input_token_length(
175
+ self,
176
+ message: str,
177
+ chat_history: list[tuple[str, str]] = [],
178
+ system_prompt: str = "",
179
+ ) -> int:
180
+ prompt = get_prompt(message, chat_history, system_prompt)
181
+
182
+ return self.get_token_length(prompt)
183
+
184
+ def generate(
185
+ self,
186
+ prompt: str,
187
+ max_new_tokens: int = 1000,
188
+ temperature: float = 0.9,
189
+ top_p: float = 1.0,
190
+ top_k: int = 40,
191
+ repetition_penalty: float = 1.0,
192
+ **kwargs: Any,
193
+ ) -> Iterator[str]:
194
+ """Create a generator of response from a prompt.
195
+
196
+ Examples:
197
+ >>> llama2_wrapper = LLAMA2_WRAPPER()
198
+ >>> prompt = get_prompt("Hi do you know Pytorch?")
199
+ >>> for response in llama2_wrapper.generate(prompt):
200
+ ... print(response)
201
+
202
+ Args:
203
+ prompt: The prompt to generate text from.
204
+ max_new_tokens: The maximum number of tokens to generate.
205
+ temperature: The temperature to use for sampling.
206
+ top_p: The top-p value to use for sampling.
207
+ top_k: The top-k value to use for sampling.
208
+ repetition_penalty: The penalty to apply to repeated tokens.
209
+ kwargs: all other arguments.
210
+
211
+ Yields:
212
+ The generated text.
213
+ """
214
+ if self.backend_type is BackendType.LLAMA_CPP:
215
+ result = self.model(
216
+ prompt=prompt,
217
+ stream=True,
218
+ max_tokens=max_new_tokens,
219
+ top_k=top_k,
220
+ top_p=top_p,
221
+ temperature=temperature,
222
+ repeat_penalty=repetition_penalty,
223
+ **kwargs,
224
+ )
225
+ outputs = []
226
+ for part in result:
227
+ text = part["choices"][0]["text"]
228
+ outputs.append(text)
229
+ yield "".join(outputs)
230
+ else:
231
+ from transformers import TextIteratorStreamer
232
+
233
+ inputs = self.tokenizer([prompt], return_tensors="pt").to("cuda")
234
+
235
+ streamer = TextIteratorStreamer(
236
+ self.tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True
237
+ )
238
+ generate_kwargs = dict(
239
+ inputs,
240
+ streamer=streamer,
241
+ max_new_tokens=max_new_tokens,
242
+ temperature=temperature,
243
+ top_p=top_p,
244
+ top_k=top_k,
245
+ repetition_penalty=repetition_penalty,
246
+ # num_beams=1,
247
+ )
248
+ generate_kwargs = (
249
+ generate_kwargs if kwargs is None else {**generate_kwargs, **kwargs}
250
+ )
251
+ t = Thread(target=self.model.generate, kwargs=generate_kwargs)
252
+ t.start()
253
+
254
+ outputs = []
255
+ for text in streamer:
256
+ outputs.append(text)
257
+ yield "".join(outputs)
258
+
259
+ def run(
260
+ self,
261
+ message: str,
262
+ chat_history: list[tuple[str, str]] = [],
263
+ system_prompt: str = "",
264
+ max_new_tokens: int = 1000,
265
+ temperature: float = 0.9,
266
+ top_p: float = 1.0,
267
+ top_k: int = 40,
268
+ repetition_penalty: float = 1.0,
269
+ ) -> Iterator[str]:
270
+ """Create a generator of response from a chat message.
271
+ Process message to llama2 prompt with chat history
272
+ and system_prompt for chatbot.
273
+
274
+ Args:
275
+ message: The origianl chat message to generate text from.
276
+ chat_history: Chat history list from chatbot.
277
+ system_prompt: System prompt for chatbot.
278
+ max_new_tokens: The maximum number of tokens to generate.
279
+ temperature: The temperature to use for sampling.
280
+ top_p: The top-p value to use for sampling.
281
+ top_k: The top-k value to use for sampling.
282
+ repetition_penalty: The penalty to apply to repeated tokens.
283
+ kwargs: all other arguments.
284
+
285
+ Yields:
286
+ The generated text.
287
+ """
288
+ prompt = get_prompt(message, chat_history, system_prompt)
289
+ return self.generate(
290
+ prompt, max_new_tokens, temperature, top_p, top_k, repetition_penalty
291
+ )
292
+
293
+ def __call__(
294
+ self,
295
+ prompt: str,
296
+ stream: bool = False,
297
+ max_new_tokens: int = 1000,
298
+ temperature: float = 0.9,
299
+ top_p: float = 1.0,
300
+ top_k: int = 40,
301
+ repetition_penalty: float = 1.0,
302
+ **kwargs: Any,
303
+ ) -> Union[str, Iterator[str]]:
304
+ """Generate text from a prompt.
305
+
306
+ Examples:
307
+ >>> llama2_wrapper = LLAMA2_WRAPPER()
308
+ >>> prompt = get_prompt("Hi do you know Pytorch?")
309
+ >>> print(llama2_wrapper(prompt))
310
+
311
+ Args:
312
+ prompt: The prompt to generate text from.
313
+ stream: Whether to stream the results.
314
+ max_new_tokens: The maximum number of tokens to generate.
315
+ temperature: The temperature to use for sampling.
316
+ top_p: The top-p value to use for sampling.
317
+ top_k: The top-k value to use for sampling.
318
+ repetition_penalty: The penalty to apply to repeated tokens.
319
+ kwargs: all other arguments.
320
+
321
+ Raises:
322
+ ValueError: If the requested tokens exceed the context window.
323
+ RuntimeError: If the prompt fails to tokenize or the model fails to evaluate the prompt.
324
+
325
+ Returns:
326
+ Generated text.
327
+ """
328
+ if self.backend_type is BackendType.LLAMA_CPP:
329
+ completion_or_chunks = self.model.__call__(
330
+ prompt,
331
+ stream=stream,
332
+ max_tokens=max_new_tokens,
333
+ temperature=temperature,
334
+ top_p=top_p,
335
+ top_k=top_k,
336
+ repeat_penalty=repetition_penalty,
337
+ **kwargs,
338
+ )
339
+ if stream:
340
+
341
+ def chunk_generator(chunks):
342
+ for part in chunks:
343
+ chunk = part["choices"][0]["text"]
344
+ yield chunk
345
+
346
+ chunks: Iterator[str] = chunk_generator(completion_or_chunks)
347
+ return chunks
348
+ return completion_or_chunks["choices"][0]["text"]
349
+ else:
350
+ inputs = self.tokenizer([prompt], return_tensors="pt").input_ids
351
+ prompt_tokens_len = len(inputs[0])
352
+ inputs = inputs.to("cuda")
353
+ generate_kwargs = dict(
354
+ inputs=inputs,
355
+ max_new_tokens=max_new_tokens,
356
+ temperature=temperature,
357
+ top_p=top_p,
358
+ top_k=top_k,
359
+ repetition_penalty=repetition_penalty,
360
+ # num_beams=1,
361
+ )
362
+ generate_kwargs = (
363
+ generate_kwargs if kwargs is None else {**generate_kwargs, **kwargs}
364
+ )
365
+ if stream:
366
+ from transformers import TextIteratorStreamer
367
+
368
+ streamer = TextIteratorStreamer(
369
+ self.tokenizer,
370
+ timeout=10.0,
371
+ skip_prompt=True,
372
+ skip_special_tokens=True,
373
+ )
374
+ generate_kwargs["streamer"] = streamer
375
+
376
+ t = Thread(target=self.model.generate, kwargs=generate_kwargs)
377
+ t.start()
378
+ return streamer
379
+ else:
380
+ output_ids = self.model.generate(
381
+ **generate_kwargs,
382
+ )
383
+ # skip prompt, skip special tokens
384
+ output = self.tokenizer.decode(
385
+ output_ids[0][prompt_tokens_len:], skip_special_tokens=True
386
+ )
387
+ return output
388
+
389
+ def completion(
390
+ self,
391
+ prompt: str,
392
+ stream: bool = False,
393
+ max_new_tokens: int = 1000,
394
+ temperature: float = 0.9,
395
+ top_p: float = 1.0,
396
+ top_k: int = 40,
397
+ repetition_penalty: float = 1.0,
398
+ **kwargs: Any,
399
+ ) -> Union[Completion, Iterator[CompletionChunk]]:
400
+ """For OpenAI compatible API /v1/completions
401
+ Generate text from a prompt.
402
+
403
+ Examples:
404
+ >>> llama2_wrapper = LLAMA2_WRAPPER()
405
+ >>> prompt = get_prompt("Hi do you know Pytorch?")
406
+ >>> print(llm.completion(prompt))
407
+
408
+ Args:
409
+ prompt: The prompt to generate text from.
410
+ stream: Whether to stream the results.
411
+ max_new_tokens: The maximum number of tokens to generate.
412
+ temperature: The temperature to use for sampling.
413
+ top_p: The top-p value to use for sampling.
414
+ top_k: The top-k value to use for sampling.
415
+ repetition_penalty: The penalty to apply to repeated tokens.
416
+ kwargs: all other arguments.
417
+
418
+ Raises:
419
+ ValueError: If the requested tokens exceed the context window.
420
+ RuntimeError: If the prompt fails to tokenize or the model fails to evaluate the prompt.
421
+
422
+ Returns:
423
+ Response object containing the generated text.
424
+ """
425
+ completion_id: str = f"cmpl-{str(uuid.uuid4())}"
426
+ created: int = int(time.time())
427
+ model_name: str = (
428
+ self.backend_type + " default model"
429
+ if self.model_path == ""
430
+ else self.model_path
431
+ )
432
+ if self.backend_type is BackendType.LLAMA_CPP:
433
+ completion_or_chunks = self.model.__call__(
434
+ prompt,
435
+ stream=stream,
436
+ max_tokens=max_new_tokens,
437
+ temperature=temperature,
438
+ top_p=top_p,
439
+ top_k=top_k,
440
+ repeat_penalty=repetition_penalty,
441
+ **kwargs,
442
+ )
443
+ if stream:
444
+ chunks: Iterator[CompletionChunk] = completion_or_chunks
445
+ return chunks
446
+ return completion_or_chunks
447
+ else:
448
+ inputs = self.tokenizer([prompt], return_tensors="pt").input_ids
449
+ prompt_tokens_len = len(inputs[0])
450
+ inputs = inputs.to("cuda")
451
+ generate_kwargs = dict(
452
+ inputs=inputs,
453
+ max_new_tokens=max_new_tokens,
454
+ temperature=temperature,
455
+ top_p=top_p,
456
+ top_k=top_k,
457
+ repetition_penalty=repetition_penalty,
458
+ # num_beams=1,
459
+ )
460
+ generate_kwargs = (
461
+ generate_kwargs if kwargs is None else {**generate_kwargs, **kwargs}
462
+ )
463
+ if stream:
464
+ from transformers import TextIteratorStreamer
465
+
466
+ streamer = TextIteratorStreamer(
467
+ self.tokenizer,
468
+ timeout=10.0,
469
+ skip_prompt=True,
470
+ skip_special_tokens=True,
471
+ )
472
+ generate_kwargs["streamer"] = streamer
473
+
474
+ t = Thread(target=self.model.generate, kwargs=generate_kwargs)
475
+ t.start()
476
+
477
+ def chunk_generator(chunks):
478
+ for part in chunks:
479
+ yield {
480
+ "id": completion_id,
481
+ "object": "text_completion",
482
+ "created": created,
483
+ "model": model_name,
484
+ "choices": [
485
+ {
486
+ "text": part,
487
+ "index": 0,
488
+ "logprobs": None,
489
+ "finish_reason": None,
490
+ }
491
+ ],
492
+ }
493
+
494
+ chunks: Iterator[CompletionChunk] = chunk_generator(streamer)
495
+ return chunks
496
+
497
+ else:
498
+ output_ids = self.model.generate(
499
+ **generate_kwargs,
500
+ )
501
+ total_tokens_len = len(output_ids[0])
502
+ output = self.tokenizer.decode(
503
+ output_ids[0][prompt_tokens_len:], skip_special_tokens=True
504
+ )
505
+ completion: Completion = {
506
+ "id": completion_id,
507
+ "object": "text_completion",
508
+ "created": created,
509
+ "model": model_name,
510
+ "choices": [
511
+ {
512
+ "text": output,
513
+ "index": 0,
514
+ "logprobs": None,
515
+ "finish_reason": None,
516
+ }
517
+ ],
518
+ "usage": {
519
+ "prompt_tokens": prompt_tokens_len,
520
+ "completion_tokens": total_tokens_len - prompt_tokens_len,
521
+ "total_tokens": total_tokens_len,
522
+ },
523
+ }
524
+ return completion
525
+
526
+ def chat_completion(
527
+ self,
528
+ messages: List[Message],
529
+ stream: bool = False,
530
+ max_new_tokens: int = 1000,
531
+ temperature: float = 0.9,
532
+ top_p: float = 1.0,
533
+ top_k: int = 40,
534
+ repetition_penalty: float = 1.0,
535
+ **kwargs: Any,
536
+ ) -> Union[ChatCompletion, Iterator[ChatCompletionChunk]]:
537
+ """For OpenAI compatible API /v1/chat/completions
538
+ Generate text from a dialog (chat history).
539
+
540
+ Examples:
541
+ >>> llama2_wrapper = LLAMA2_WRAPPER()
542
+ >>> dialog = [
543
+ {
544
+ "role":"system",
545
+ "content":"You are a helpful, respectful and honest assistant. "
546
+ },{
547
+ "role":"user",
548
+ "content":"Hi do you know Pytorch?",
549
+ },
550
+ ]
551
+ >>> print(llm.chat_completion(dialog))
552
+
553
+ Args:
554
+ dialog: The dialog (chat history) to generate text from.
555
+ stream: Whether to stream the results.
556
+ max_new_tokens: The maximum number of tokens to generate.
557
+ temperature: The temperature to use for sampling.
558
+ top_p: The top-p value to use for sampling.
559
+ top_k: The top-k value to use for sampling.
560
+ repetition_penalty: The penalty to apply to repeated tokens.
561
+ kwargs: all other arguments.
562
+
563
+ Raises:
564
+ ValueError: If the requested tokens exceed the context window.
565
+ RuntimeError: If the prompt fails to tokenize or the model fails to evaluate the prompt.
566
+
567
+ Returns:
568
+ Response object containing the generated text.
569
+ """
570
+ completion_id: str = f"cmpl-{str(uuid.uuid4())}"
571
+ created: int = int(time.time())
572
+ model_name: str = (
573
+ self.backend_type + " default model"
574
+ if self.model_path == ""
575
+ else self.model_path
576
+ )
577
+ if self.backend_type is BackendType.LLAMA_CPP:
578
+ completion_or_chunks = self.model.create_chat_completion(
579
+ messages,
580
+ stream=stream,
581
+ max_tokens=max_new_tokens,
582
+ temperature=temperature,
583
+ top_p=top_p,
584
+ top_k=top_k,
585
+ repeat_penalty=repetition_penalty,
586
+ **kwargs,
587
+ )
588
+ if stream:
589
+ chunks: Iterator[ChatCompletionChunk] = completion_or_chunks
590
+ return chunks
591
+ return completion_or_chunks
592
+ else:
593
+ prompt = get_prompt_for_dialog(messages)
594
+ inputs = self.tokenizer([prompt], return_tensors="pt").input_ids
595
+ prompt_tokens_len = len(inputs[0])
596
+ inputs = inputs.to("cuda")
597
+ generate_kwargs = dict(
598
+ inputs=inputs,
599
+ max_new_tokens=max_new_tokens,
600
+ temperature=temperature,
601
+ top_p=top_p,
602
+ top_k=top_k,
603
+ repetition_penalty=repetition_penalty,
604
+ # num_beams=1,
605
+ )
606
+ generate_kwargs = (
607
+ generate_kwargs if kwargs is None else {**generate_kwargs, **kwargs}
608
+ )
609
+ if stream:
610
+ from transformers import TextIteratorStreamer
611
+
612
+ streamer = TextIteratorStreamer(
613
+ self.tokenizer,
614
+ timeout=10.0,
615
+ skip_prompt=True,
616
+ skip_special_tokens=True,
617
+ )
618
+ generate_kwargs["streamer"] = streamer
619
+ t = Thread(target=self.model.generate, kwargs=generate_kwargs)
620
+ t.start()
621
+
622
+ def chunk_generator(chunks):
623
+ yield {
624
+ "id": "chat" + completion_id,
625
+ "model": model_name,
626
+ "created": created,
627
+ "object": "chat.completion.chunk",
628
+ "choices": [
629
+ {
630
+ "index": 0,
631
+ "delta": {
632
+ "role": "assistant",
633
+ },
634
+ "finish_reason": None,
635
+ }
636
+ ],
637
+ }
638
+ for part in enumerate(chunks):
639
+ yield {
640
+ "id": "chat" + completion_id,
641
+ "model": model_name,
642
+ "created": created,
643
+ "object": "chat.completion.chunk",
644
+ "choices": [
645
+ {
646
+ "index": 0,
647
+ "delta": {
648
+ "content": part,
649
+ },
650
+ "finish_reason": None,
651
+ }
652
+ ],
653
+ }
654
+
655
+ chunks: Iterator[ChatCompletionChunk] = chunk_generator(streamer)
656
+ return chunks
657
+
658
+ else:
659
+ output_ids = self.model.generate(
660
+ **generate_kwargs,
661
+ )
662
+ total_tokens_len = len(output_ids[0])
663
+ output = self.tokenizer.decode(
664
+ output_ids[0][prompt_tokens_len:], skip_special_tokens=True
665
+ )
666
+ chatcompletion: ChatCompletion = {
667
+ "id": "chat" + completion_id,
668
+ "object": "chat.completion",
669
+ "created": created,
670
+ "model": model_name,
671
+ "choices": [
672
+ {
673
+ "index": 0,
674
+ "message": {
675
+ "role": "assistant",
676
+ "content": output,
677
+ },
678
+ "finish_reason": None,
679
+ }
680
+ ],
681
+ "usage": {
682
+ "prompt_tokens": prompt_tokens_len,
683
+ "completion_tokens": total_tokens_len - prompt_tokens_len,
684
+ "total_tokens": total_tokens_len,
685
+ },
686
+ }
687
+ return chatcompletion
688
+
689
+
690
+ def get_prompt_for_dialog(dialog: List[Message]) -> str:
691
+ """Process dialog (chat history) to llama2 prompt for
692
+ OpenAI compatible API /v1/chat/completions.
693
+
694
+ Examples:
695
+ >>> dialog = [
696
+ {
697
+ "role":"system",
698
+ "content":"You are a helpful, respectful and honest assistant. "
699
+ },{
700
+ "role":"user",
701
+ "content":"Hi do you know Pytorch?",
702
+ },
703
+ ]
704
+ >>> prompt = get_prompt_for_dialog("Hi do you know Pytorch?")
705
+
706
+ Args:
707
+ dialog: The dialog (chat history) to generate text from.
708
+
709
+ Yields:
710
+ prompt string.
711
+ """
712
+ # add "<<SYS>>\n{system_prompt}\n<</SYS>>\n\n" in first dialog
713
+ if dialog[0]["role"] == "system":
714
+ dialog = [
715
+ {
716
+ "role": dialog[1]["role"],
717
+ "content": B_SYS + dialog[0]["content"] + E_SYS + dialog[1]["content"],
718
+ }
719
+ ] + dialog[2:]
720
+ # check roles
721
+ assert all([msg["role"] == "user" for msg in dialog[::2]]) and all(
722
+ [msg["role"] == "assistant" for msg in dialog[1::2]]
723
+ ), (
724
+ "model only supports 'system', 'user' and 'assistant' roles, "
725
+ "starting with 'system', then 'user' and alternating (u/a/u/a/u...)"
726
+ )
727
+ # add chat history
728
+ texts = []
729
+ for prompt, answer in zip(
730
+ dialog[::2],
731
+ dialog[1::2],
732
+ ):
733
+ texts.append(
734
+ f"{B_INST} {(prompt['content']).strip()} {E_INST} {(answer['content']).strip()} "
735
+ )
736
+ # check last message if role is user, then add it to prompt text
737
+ assert (
738
+ dialog[-1]["role"] == "user"
739
+ ), f"Last message must be from user, got {dialog[-1]['role']}"
740
+ texts.append(f"{B_INST} {(dialog[-1]['content']).strip()} {E_INST}")
741
+ return "".join(texts)
742
+
743
+
744
+ def get_prompt(
745
+ message: str, chat_history: list[tuple[str, str]] = [], system_prompt: str = ""
746
+ ) -> str:
747
+ """Process message to llama2 prompt with chat history
748
+ and system_prompt for chatbot.
749
+
750
+ Examples:
751
+ >>> prompt = get_prompt("Hi do you know Pytorch?")
752
+
753
+ Args:
754
+ message: The origianl chat message to generate text from.
755
+ chat_history: Chat history list from chatbot.
756
+ system_prompt: System prompt for chatbot.
757
+
758
+ Yields:
759
+ prompt string.
760
+ """
761
+ texts = [f"[INST] <<SYS>>\n{system_prompt}\n<</SYS>>\n\n"]
762
+ for user_input, response in chat_history:
763
+ texts.append(f"{user_input.strip()} [/INST] {response.strip()} </s><s> [INST] ")
764
+ texts.append(f"{message.strip()} [/INST]")
765
+ return "".join(texts)
766
+
767
+
768
+ class BackendType(Enum):
769
+ UNKNOWN = 0
770
+ TRANSFORMERS = 1
771
+ GPTQ = 2
772
+ LLAMA_CPP = 3
773
+
774
+ @classmethod
775
+ def get_type(cls, backend_name: str):
776
+ backend_type = None
777
+ backend_name_lower = backend_name.lower()
778
+ if "transformers" in backend_name_lower:
779
+ backend_type = BackendType.TRANSFORMERS
780
+ elif "gptq" in backend_name_lower:
781
+ backend_type = BackendType.GPTQ
782
+ elif "cpp" in backend_name_lower:
783
+ backend_type = BackendType.LLAMA_CPP
784
+ else:
785
+ raise Exception("Unknown backend: " + backend_name)
786
+ # backend_type = BackendType.UNKNOWN
787
+ return backend_type
llama2_wrapper/server/__init__.py ADDED
File without changes
llama2_wrapper/server/__main__.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example FastAPI server for llama2_wrapper.
2
+
3
+ To run this example:
4
+
5
+ ```
6
+ python3 -m llama2_wrapper.server
7
+ ```
8
+
9
+ or
10
+
11
+ ```
12
+ uvicorn llama2_wrapper.server.app:app --reload
13
+ ```
14
+
15
+ Then visit http://localhost:8000/docs to see the interactive API docs.
16
+
17
+ """
18
+ import os
19
+ import argparse
20
+
21
+ import uvicorn
22
+
23
+ from llama2_wrapper.server.app import create_app, Settings
24
+
25
+ if __name__ == "__main__":
26
+ parser = argparse.ArgumentParser()
27
+ for name, field in Settings.model_fields.items():
28
+ description = field.description
29
+ if field.default is not None and description is not None:
30
+ description += f" (default: {field.default})"
31
+ parser.add_argument(
32
+ f"--{name}",
33
+ dest=name,
34
+ type=field.annotation if field.annotation is not None else str,
35
+ help=description,
36
+ )
37
+
38
+ args = parser.parse_args()
39
+ settings = Settings(**{k: v for k, v in vars(args).items() if v is not None})
40
+ app = create_app(settings=settings)
41
+
42
+ uvicorn.run(
43
+ app,
44
+ host=os.getenv("HOST", settings.host),
45
+ port=int(os.getenv("PORT", settings.port)),
46
+ )
llama2_wrapper/server/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (204 Bytes). View file
 
llama2_wrapper/server/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (1.25 kB). View file
 
llama2_wrapper/server/__pycache__/app.cpython-310.pyc ADDED
Binary file (13 kB). View file
 
llama2_wrapper/server/app.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import multiprocessing
3
+ from re import compile, Match, Pattern
4
+ from threading import Lock
5
+ from functools import partial
6
+ from typing import Callable, Coroutine, Iterator, List, Optional, Tuple, Union, Dict
7
+ from typing_extensions import TypedDict, Literal
8
+
9
+ import anyio
10
+ from anyio.streams.memory import MemoryObjectSendStream
11
+ from starlette.concurrency import run_in_threadpool, iterate_in_threadpool
12
+ from fastapi import Depends, FastAPI, APIRouter, Request, Response
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ from fastapi.responses import JSONResponse
15
+ from fastapi.routing import APIRoute
16
+ from pydantic import BaseModel, Field
17
+ from pydantic_settings import BaseSettings
18
+ from sse_starlette.sse import EventSourceResponse
19
+
20
+ from llama2_wrapper.model import LLAMA2_WRAPPER
21
+ from llama2_wrapper.types import (
22
+ Completion,
23
+ CompletionChunk,
24
+ ChatCompletion,
25
+ ChatCompletionChunk,
26
+ )
27
+
28
+
29
+ class Settings(BaseSettings):
30
+ model_path: str = Field(
31
+ default="",
32
+ description="The path to the model to use for generating completions.",
33
+ )
34
+ backend_type: str = Field(
35
+ default="llama.cpp",
36
+ description="Backend for llama2, options: llama.cpp, gptq, transformers",
37
+ )
38
+ max_tokens: int = Field(default=4000, ge=1, description="Maximum context size.")
39
+ load_in_8bit: bool = Field(
40
+ default=False,
41
+ description="`Whether to use bitsandbytes to run model in 8 bit mode (only for transformers models).",
42
+ )
43
+ verbose: bool = Field(
44
+ default=False,
45
+ description="Whether to print verbose output to stderr.",
46
+ )
47
+ host: str = Field(default="localhost", description="API address")
48
+ port: int = Field(default=8000, description="API port")
49
+ interrupt_requests: bool = Field(
50
+ default=True,
51
+ description="Whether to interrupt requests when a new request is received.",
52
+ )
53
+
54
+
55
+ class ErrorResponse(TypedDict):
56
+ """OpenAI style error response"""
57
+
58
+ message: str
59
+ type: str
60
+ param: Optional[str]
61
+ code: Optional[str]
62
+
63
+
64
+ class ErrorResponseFormatters:
65
+ """Collection of formatters for error responses.
66
+
67
+ Args:
68
+ request (Union[CreateCompletionRequest, CreateChatCompletionRequest]):
69
+ Request body
70
+ match (Match[str]): Match object from regex pattern
71
+
72
+ Returns:
73
+ Tuple[int, ErrorResponse]: Status code and error response
74
+ """
75
+
76
+ @staticmethod
77
+ def context_length_exceeded(
78
+ request: Union["CreateCompletionRequest", "CreateChatCompletionRequest"],
79
+ match, # type: Match[str] # type: ignore
80
+ ) -> Tuple[int, ErrorResponse]:
81
+ """Formatter for context length exceeded error"""
82
+
83
+ context_window = int(match.group(2))
84
+ prompt_tokens = int(match.group(1))
85
+ completion_tokens = request.max_new_tokens
86
+ if hasattr(request, "messages"):
87
+ # Chat completion
88
+ message = (
89
+ "This model's maximum context length is {} tokens. "
90
+ "However, you requested {} tokens "
91
+ "({} in the messages, {} in the completion). "
92
+ "Please reduce the length of the messages or completion."
93
+ )
94
+ else:
95
+ # Text completion
96
+ message = (
97
+ "This model's maximum context length is {} tokens, "
98
+ "however you requested {} tokens "
99
+ "({} in your prompt; {} for the completion). "
100
+ "Please reduce your prompt; or completion length."
101
+ )
102
+ return 400, ErrorResponse(
103
+ message=message.format(
104
+ context_window,
105
+ completion_tokens + prompt_tokens,
106
+ prompt_tokens,
107
+ completion_tokens,
108
+ ),
109
+ type="invalid_request_error",
110
+ param="messages",
111
+ code="context_length_exceeded",
112
+ )
113
+
114
+ @staticmethod
115
+ def model_not_found(
116
+ request: Union["CreateCompletionRequest", "CreateChatCompletionRequest"],
117
+ match, # type: Match[str] # type: ignore
118
+ ) -> Tuple[int, ErrorResponse]:
119
+ """Formatter for model_not_found error"""
120
+
121
+ model_path = str(match.group(1))
122
+ message = f"The model `{model_path}` does not exist"
123
+ return 400, ErrorResponse(
124
+ message=message,
125
+ type="invalid_request_error",
126
+ param=None,
127
+ code="model_not_found",
128
+ )
129
+
130
+
131
+ class RouteErrorHandler(APIRoute):
132
+ """Custom APIRoute that handles application errors and exceptions"""
133
+
134
+ # key: regex pattern for original error message from llama_cpp
135
+ # value: formatter function
136
+ pattern_and_formatters: Dict[
137
+ "Pattern",
138
+ Callable[
139
+ [
140
+ Union["CreateCompletionRequest", "CreateChatCompletionRequest"],
141
+ "Match[str]",
142
+ ],
143
+ Tuple[int, ErrorResponse],
144
+ ],
145
+ ] = {
146
+ compile(
147
+ r"Requested tokens \((\d+)\) exceed context window of (\d+)"
148
+ ): ErrorResponseFormatters.context_length_exceeded,
149
+ compile(
150
+ r"Model path does not exist: (.+)"
151
+ ): ErrorResponseFormatters.model_not_found,
152
+ }
153
+
154
+ def error_message_wrapper(
155
+ self,
156
+ error: Exception,
157
+ body: Optional[
158
+ Union[
159
+ "CreateChatCompletionRequest",
160
+ "CreateCompletionRequest",
161
+ ]
162
+ ] = None,
163
+ ) -> Tuple[int, ErrorResponse]:
164
+ """Wraps error message in OpenAI style error response"""
165
+
166
+ if body is not None and isinstance(
167
+ body,
168
+ (
169
+ CreateCompletionRequest,
170
+ CreateChatCompletionRequest,
171
+ ),
172
+ ):
173
+ # When text completion or chat completion
174
+ for pattern, callback in self.pattern_and_formatters.items():
175
+ match = pattern.search(str(error))
176
+ if match is not None:
177
+ return callback(body, match)
178
+
179
+ # Wrap other errors as internal server error
180
+ return 500, ErrorResponse(
181
+ message=str(error),
182
+ type="internal_server_error",
183
+ param=None,
184
+ code=None,
185
+ )
186
+
187
+ def get_route_handler(
188
+ self,
189
+ ) -> Callable[[Request], Coroutine[None, None, Response]]:
190
+ """Defines custom route handler that catches exceptions and formats
191
+ in OpenAI style error response"""
192
+
193
+ original_route_handler = super().get_route_handler()
194
+
195
+ async def custom_route_handler(request: Request) -> Response:
196
+ try:
197
+ return await original_route_handler(request)
198
+ except Exception as exc:
199
+ json_body = await request.json()
200
+ try:
201
+ if "messages" in json_body:
202
+ # Chat completion
203
+ body: Optional[
204
+ Union[
205
+ CreateChatCompletionRequest,
206
+ CreateCompletionRequest,
207
+ ]
208
+ ] = CreateChatCompletionRequest(**json_body)
209
+ elif "prompt" in json_body:
210
+ # Text completion
211
+ body = CreateCompletionRequest(**json_body)
212
+ # else:
213
+ # # Embedding
214
+ # body = CreateEmbeddingRequest(**json_body)
215
+ except Exception:
216
+ # Invalid request body
217
+ body = None
218
+
219
+ # Get proper error message from the exception
220
+ (
221
+ status_code,
222
+ error_message,
223
+ ) = self.error_message_wrapper(error=exc, body=body)
224
+ return JSONResponse(
225
+ {"error": error_message},
226
+ status_code=status_code,
227
+ )
228
+
229
+ return custom_route_handler
230
+
231
+
232
+ router = APIRouter(route_class=RouteErrorHandler)
233
+
234
+ settings: Optional[Settings] = None
235
+ llama2: Optional[LLAMA2_WRAPPER] = None
236
+
237
+
238
+ def create_app(settings: Optional[Settings] = None):
239
+ if settings is None:
240
+ settings = Settings()
241
+ app = FastAPI(
242
+ title="llama2-wrapper Fast API",
243
+ version="0.0.1",
244
+ )
245
+ app.add_middleware(
246
+ CORSMiddleware,
247
+ allow_origins=["*"],
248
+ allow_credentials=True,
249
+ allow_methods=["*"],
250
+ allow_headers=["*"],
251
+ )
252
+ app.include_router(router)
253
+ global llama2
254
+ llama2 = LLAMA2_WRAPPER(
255
+ model_path=settings.model_path,
256
+ backend_type=settings.backend_type,
257
+ max_tokens=settings.max_tokens,
258
+ load_in_8bit=settings.load_in_8bit,
259
+ verbose=settings.load_in_8bit,
260
+ )
261
+
262
+ def set_settings(_settings: Settings):
263
+ global settings
264
+ settings = _settings
265
+
266
+ set_settings(settings)
267
+ return app
268
+
269
+
270
+ llama_outer_lock = Lock()
271
+ llama_inner_lock = Lock()
272
+
273
+
274
+ def get_llama():
275
+ # NOTE: This double lock allows the currently streaming llama model to
276
+ # check if any other requests are pending in the same thread and cancel
277
+ # the stream if so.
278
+ llama_outer_lock.acquire()
279
+ release_outer_lock = True
280
+ try:
281
+ llama_inner_lock.acquire()
282
+ try:
283
+ llama_outer_lock.release()
284
+ release_outer_lock = False
285
+ yield llama2
286
+ finally:
287
+ llama_inner_lock.release()
288
+ finally:
289
+ if release_outer_lock:
290
+ llama_outer_lock.release()
291
+
292
+
293
+ def get_settings():
294
+ yield settings
295
+
296
+
297
+ async def get_event_publisher(
298
+ request: Request,
299
+ inner_send_chan: MemoryObjectSendStream,
300
+ iterator: Iterator,
301
+ ):
302
+ async with inner_send_chan:
303
+ try:
304
+ async for chunk in iterate_in_threadpool(iterator):
305
+ await inner_send_chan.send(dict(data=json.dumps(chunk)))
306
+ if await request.is_disconnected():
307
+ raise anyio.get_cancelled_exc_class()()
308
+ if settings.interrupt_requests and llama_outer_lock.locked():
309
+ await inner_send_chan.send(dict(data="[DONE]"))
310
+ raise anyio.get_cancelled_exc_class()()
311
+ await inner_send_chan.send(dict(data="[DONE]"))
312
+ except anyio.get_cancelled_exc_class() as e:
313
+ print("disconnected")
314
+ with anyio.move_on_after(1, shield=True):
315
+ print(f"Disconnected from client (via refresh/close) {request.client}")
316
+ raise e
317
+
318
+
319
+ stream_field = Field(
320
+ default=False,
321
+ description="Whether to stream the results as they are generated. Useful for chatbots.",
322
+ )
323
+ max_new_tokens_field = Field(
324
+ default=1000, ge=1, description="The maximum number of tokens to generate."
325
+ )
326
+
327
+ temperature_field = Field(
328
+ default=0.9,
329
+ ge=0.0,
330
+ le=2.0,
331
+ description="The temperature to use for sampling.",
332
+ )
333
+
334
+ top_p_field = Field(
335
+ default=1.0,
336
+ ge=0.0,
337
+ le=1.0,
338
+ description="The top-p value to use for sampling.",
339
+ )
340
+ top_k_field = Field(
341
+ default=40,
342
+ ge=0,
343
+ description="The top-k value to use for sampling.",
344
+ )
345
+ repetition_penalty_field = Field(
346
+ default=1.0,
347
+ ge=0.0,
348
+ description="The penalty to apply to repeated tokens.",
349
+ )
350
+ # stop_field = Field(
351
+ # default=None,
352
+ # description="A list of tokens at which to stop generation. If None, no stop tokens are used.",
353
+ # )
354
+
355
+
356
+ class CreateCompletionRequest(BaseModel):
357
+ prompt: Union[str, List[str]] = Field(
358
+ default="", description="The prompt to generate text from."
359
+ )
360
+ stream: bool = stream_field
361
+ max_new_tokens: int = max_new_tokens_field
362
+ temperature: float = temperature_field
363
+ top_p: float = top_p_field
364
+ top_k: int = top_k_field
365
+ repetition_penalty: float = repetition_penalty_field
366
+ # stop: Optional[Union[str, List[str]]] = stop_field
367
+
368
+ model_config = {
369
+ "json_schema_extra": {
370
+ "examples": [
371
+ {
372
+ "prompt": "\n\n### Instructions:\nWhat is the capital of France?\n\n### Response:\n",
373
+ # "stop": ["\n", "###"],
374
+ }
375
+ ]
376
+ }
377
+ }
378
+
379
+
380
+ @router.post(
381
+ "/v1/completions",
382
+ )
383
+ async def create_completion(
384
+ request: Request,
385
+ body: CreateCompletionRequest,
386
+ llama2: LLAMA2_WRAPPER = Depends(get_llama),
387
+ ) -> Completion:
388
+ if isinstance(body.prompt, list):
389
+ assert len(body.prompt) <= 1
390
+ body.prompt = body.prompt[0] if len(body.prompt) > 0 else ""
391
+
392
+ kwargs = body.model_dump()
393
+
394
+ iterator_or_completion: Union[
395
+ Completion, Iterator[CompletionChunk]
396
+ ] = await run_in_threadpool(llama2.completion, **kwargs)
397
+
398
+ if isinstance(iterator_or_completion, Iterator):
399
+ first_response = await run_in_threadpool(next, iterator_or_completion)
400
+
401
+ # If no exception was raised from first_response, we can assume that
402
+ # the iterator is valid and we can use it to stream the response.
403
+ def iterator() -> Iterator[CompletionChunk]:
404
+ yield first_response
405
+ yield from iterator_or_completion
406
+
407
+ send_chan, recv_chan = anyio.create_memory_object_stream(10)
408
+ return EventSourceResponse(
409
+ recv_chan,
410
+ data_sender_callable=partial( # type: ignore
411
+ get_event_publisher,
412
+ request=request,
413
+ inner_send_chan=send_chan,
414
+ iterator=iterator(),
415
+ ),
416
+ )
417
+ else:
418
+ return iterator_or_completion
419
+
420
+
421
+ class ChatCompletionRequestMessage(BaseModel):
422
+ role: Literal["system", "user", "assistant"] = Field(
423
+ default="user", description="The role of the message."
424
+ )
425
+ content: str = Field(default="", description="The content of the message.")
426
+
427
+
428
+ class CreateChatCompletionRequest(BaseModel):
429
+ messages: List[ChatCompletionRequestMessage] = Field(
430
+ default=[], description="A list of messages to generate completions for."
431
+ )
432
+ stream: bool = stream_field
433
+ max_new_tokens: int = max_new_tokens_field
434
+ temperature: float = temperature_field
435
+ top_p: float = top_p_field
436
+ top_k: int = top_k_field
437
+ repetition_penalty: float = repetition_penalty_field
438
+ # stop: Optional[List[str]] = stop_field
439
+
440
+ model_config = {
441
+ "json_schema_extra": {
442
+ "examples": [
443
+ {
444
+ "messages": [
445
+ ChatCompletionRequestMessage(
446
+ role="system", content="You are a helpful assistant."
447
+ ).model_dump(),
448
+ ChatCompletionRequestMessage(
449
+ role="user", content="What is the capital of France?"
450
+ ).model_dump(),
451
+ ]
452
+ }
453
+ ]
454
+ }
455
+ }
456
+
457
+
458
+ @router.post(
459
+ "/v1/chat/completions",
460
+ )
461
+ async def create_chat_completion(
462
+ request: Request,
463
+ body: CreateChatCompletionRequest,
464
+ llama2: LLAMA2_WRAPPER = Depends(get_llama),
465
+ settings: Settings = Depends(get_settings),
466
+ ) -> ChatCompletion:
467
+ kwargs = body.model_dump()
468
+
469
+ iterator_or_completion: Union[
470
+ ChatCompletion, Iterator[ChatCompletionChunk]
471
+ ] = await run_in_threadpool(llama2.chat_completion, **kwargs)
472
+
473
+ if isinstance(iterator_or_completion, Iterator):
474
+ first_response = await run_in_threadpool(next, iterator_or_completion)
475
+
476
+ # If no exception was raised from first_response, we can assume that
477
+ # the iterator is valid and we can use it to stream the response.
478
+ def iterator() -> Iterator[ChatCompletionChunk]:
479
+ yield first_response
480
+ yield from iterator_or_completion
481
+
482
+ send_chan, recv_chan = anyio.create_memory_object_stream(10)
483
+ return EventSourceResponse(
484
+ recv_chan,
485
+ data_sender_callable=partial( # type: ignore
486
+ get_event_publisher,
487
+ request=request,
488
+ inner_send_chan=send_chan,
489
+ iterator=iterator(),
490
+ ),
491
+ )
492
+ else:
493
+ return iterator_or_completion
494
+
495
+
496
+ class ModelData(TypedDict):
497
+ id: str
498
+ object: Literal["model"]
499
+ owned_by: str
500
+ permissions: List[str]
501
+
502
+
503
+ class ModelList(TypedDict):
504
+ object: Literal["list"]
505
+ data: List[ModelData]
506
+
507
+
508
+ @router.get("/v1/models")
509
+ async def get_models(
510
+ settings: Settings = Depends(get_settings),
511
+ ) -> ModelList:
512
+ assert llama2 is not None
513
+
514
+ return {
515
+ "object": "list",
516
+ "data": [
517
+ {
518
+ "id": settings.backend_type + " default model"
519
+ if settings.model_path == ""
520
+ else settings.model_path,
521
+ "object": "model",
522
+ "owned_by": "me",
523
+ "permissions": [],
524
+ }
525
+ ],
526
+ }
llama2_wrapper/types.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, List, Optional, Dict, Union
2
+ from typing_extensions import TypedDict, NotRequired, Literal
3
+
4
+ B_INST, E_INST = "[INST]", "[/INST]"
5
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
6
+
7
+
8
+ # Role = Literal["system", "user", "assistant"]
9
+ # class Message(TypedDict):
10
+ # role: Role
11
+ # content: str
12
+
13
+
14
+ class ChatCompletionMessage(TypedDict):
15
+ role: Literal["assistant", "user", "system"]
16
+ content: str
17
+ user: NotRequired[str]
18
+
19
+
20
+ # transformers: Message; llama.cpp: ChatCompletionMessage
21
+ Message = ChatCompletionMessage
22
+ Dialog = List[Message]
23
+
24
+
25
+ class EmbeddingUsage(TypedDict):
26
+ prompt_tokens: int
27
+ total_tokens: int
28
+
29
+
30
+ class EmbeddingData(TypedDict):
31
+ index: int
32
+ object: str
33
+ embedding: List[float]
34
+
35
+
36
+ class Embedding(TypedDict):
37
+ object: Literal["list"]
38
+ model: str
39
+ data: List[EmbeddingData]
40
+ usage: EmbeddingUsage
41
+
42
+
43
+ class CompletionLogprobs(TypedDict):
44
+ text_offset: List[int]
45
+ token_logprobs: List[Optional[float]]
46
+ tokens: List[str]
47
+ top_logprobs: List[Optional[Dict[str, float]]]
48
+
49
+
50
+ class CompletionChoice(TypedDict):
51
+ text: str
52
+ index: int
53
+ logprobs: Optional[CompletionLogprobs]
54
+ finish_reason: Optional[str]
55
+
56
+
57
+ class CompletionUsage(TypedDict):
58
+ prompt_tokens: int
59
+ completion_tokens: int
60
+ total_tokens: int
61
+
62
+
63
+ class CompletionChunk(TypedDict):
64
+ id: str
65
+ object: Literal["text_completion"]
66
+ created: int
67
+ model: str
68
+ choices: List[CompletionChoice]
69
+
70
+
71
+ class Completion(TypedDict):
72
+ id: str
73
+ object: Literal["text_completion"]
74
+ created: int
75
+ model: str
76
+ choices: List[CompletionChoice]
77
+ usage: CompletionUsage
78
+
79
+
80
+ class ChatCompletionChoice(TypedDict):
81
+ index: int
82
+ message: ChatCompletionMessage
83
+ finish_reason: Optional[str]
84
+
85
+
86
+ class ChatCompletion(TypedDict):
87
+ id: str
88
+ object: Literal["chat.completion"]
89
+ created: int
90
+ model: str
91
+ choices: List[ChatCompletionChoice]
92
+ usage: CompletionUsage
93
+
94
+
95
+ class ChatCompletionChunkDeltaEmpty(TypedDict):
96
+ pass
97
+
98
+
99
+ class ChatCompletionChunkDelta(TypedDict):
100
+ role: NotRequired[Literal["assistant"]]
101
+ content: NotRequired[str]
102
+
103
+
104
+ class ChatCompletionChunkChoice(TypedDict):
105
+ index: int
106
+ delta: Union[ChatCompletionChunkDelta, ChatCompletionChunkDeltaEmpty]
107
+ finish_reason: Optional[str]
108
+
109
+
110
+ class ChatCompletionChunk(TypedDict):
111
+ id: str
112
+ model: str
113
+ object: Literal["chat.completion.chunk"]
114
+ created: int
115
+ choices: List[ChatCompletionChunkChoice]
models/CodeLlama-7B-Python-GPTQ/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
models/CodeLlama-7B-Python-GPTQ/LICENSE ADDED
@@ -0,0 +1 @@
 
 
1
+ Please refer to license: https://github.com/facebookresearch/llama/blob/main/LICENSE
models/CodeLlama-7B-Python-GPTQ/LICENSE.txt ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LLAMA 2 COMMUNITY LICENSE AGREEMENT
2
+ Llama 2 Version Release Date: July 18, 2023
3
+
4
+ "Agreement" means the terms and conditions for use, reproduction, distribution and
5
+ modification of the Llama Materials set forth herein.
6
+
7
+ "Documentation" means the specifications, manuals and documentation
8
+ accompanying Llama 2 distributed by Meta at ai.meta.com/resources/models-and-
9
+ libraries/llama-downloads/.
10
+
11
+ "Licensee" or "you" means you, or your employer or any other person or entity (if
12
+ you are entering into this Agreement on such person or entity's behalf), of the age
13
+ required under applicable laws, rules or regulations to provide legal consent and that
14
+ has legal authority to bind your employer or such other person or entity if you are
15
+ entering in this Agreement on their behalf.
16
+
17
+ "Llama 2" means the foundational large language models and software and
18
+ algorithms, including machine-learning model code, trained model weights,
19
+ inference-enabling code, training-enabling code, fine-tuning enabling code and other
20
+ elements of the foregoing distributed by Meta at ai.meta.com/resources/models-and-
21
+ libraries/llama-downloads/.
22
+
23
+ "Llama Materials" means, collectively, Meta's proprietary Llama 2 and
24
+ Documentation (and any portion thereof) made available under this Agreement.
25
+
26
+ "Meta" or "we" means Meta Platforms Ireland Limited (if you are located in or, if you
27
+ are an entity, your principal place of business is in the EEA or Switzerland) and Meta
28
+ Platforms, Inc. (if you are located outside of the EEA or Switzerland).
29
+
30
+ By clicking "I Accept" below or by using or distributing any portion or element of the
31
+ Llama Materials, you agree to be bound by this Agreement.
32
+
33
+ 1. License Rights and Redistribution.
34
+
35
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-
36
+ transferable and royalty-free limited license under Meta's intellectual property or
37
+ other rights owned by Meta embodied in the Llama Materials to use, reproduce,
38
+ distribute, copy, create derivative works of, and make modifications to the Llama
39
+ Materials.
40
+
41
+ b. Redistribution and Use.
42
+
43
+ i. If you distribute or make the Llama Materials, or any derivative works
44
+ thereof, available to a third party, you shall provide a copy of this Agreement to such
45
+ third party.
46
+ ii. If you receive Llama Materials, or any derivative works thereof, from
47
+ a Licensee as part of an integrated end user product, then Section 2 of this
48
+ Agreement will not apply to you.
49
+
50
+ iii. You must retain in all copies of the Llama Materials that you
51
+ distribute the following attribution notice within a "Notice" text file distributed as a
52
+ part of such copies: "Llama 2 is licensed under the LLAMA 2 Community License,
53
+ Copyright (c) Meta Platforms, Inc. All Rights Reserved."
54
+
55
+ iv. Your use of the Llama Materials must comply with applicable laws
56
+ and regulations (including trade compliance laws and regulations) and adhere to the
57
+ Acceptable Use Policy for the Llama Materials (available at
58
+ https://ai.meta.com/llama/use-policy), which is hereby incorporated by reference into
59
+ this Agreement.
60
+
61
+ v. You will not use the Llama Materials or any output or results of the
62
+ Llama Materials to improve any other large language model (excluding Llama 2 or
63
+ derivative works thereof).
64
+
65
+ 2. Additional Commercial Terms. If, on the Llama 2 version release date, the
66
+ monthly active users of the products or services made available by or for Licensee,
67
+ or Licensee's affiliates, is greater than 700 million monthly active users in the
68
+ preceding calendar month, you must request a license from Meta, which Meta may
69
+ grant to you in its sole discretion, and you are not authorized to exercise any of the
70
+ rights under this Agreement unless or until Meta otherwise expressly grants you
71
+ such rights.
72
+
73
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE
74
+ LLAMA MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE
75
+ PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
76
+ EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY
77
+ WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR
78
+ FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE
79
+ FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING
80
+ THE LLAMA MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR
81
+ USE OF THE LLAMA MATERIALS AND ANY OUTPUT AND RESULTS.
82
+
83
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE
84
+ LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT,
85
+ NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS
86
+ AGREEMENT, FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL,
87
+ CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN
88
+ IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF
89
+ ANY OF THE FOREGOING.
90
+
91
+ 5. Intellectual Property.
92
+
93
+ a. No trademark licenses are granted under this Agreement, and in
94
+ connection with the Llama Materials, neither Meta nor Licensee may use any name
95
+ or mark owned by or associated with the other or any of its affiliates, except as
96
+ required for reasonable and customary use in describing and redistributing the
97
+ Llama Materials.
98
+
99
+ b. Subject to Meta's ownership of Llama Materials and derivatives made by or
100
+ for Meta, with respect to any derivative works and modifications of the Llama
101
+ Materials that are made by you, as between you and Meta, you are and will be the
102
+ owner of such derivative works and modifications.
103
+
104
+ c. If you institute litigation or other proceedings against Meta or any entity
105
+ (including a cross-claim or counterclaim in a lawsuit) alleging that the Llama
106
+ Materials or Llama 2 outputs or results, or any portion of any of the foregoing,
107
+ constitutes infringement of intellectual property or other rights owned or licensable
108
+ by you, then any licenses granted to you under this Agreement shall terminate as of
109
+ the date such litigation or claim is filed or instituted. You will indemnify and hold
110
+ harmless Meta from and against any claim by any third party arising out of or related
111
+ to your use or distribution of the Llama Materials.
112
+
113
+ 6. Term and Termination. The term of this Agreement will commence upon your
114
+ acceptance of this Agreement or access to the Llama Materials and will continue in
115
+ full force and effect until terminated in accordance with the terms and conditions
116
+ herein. Meta may terminate this Agreement if you are in breach of any term or
117
+ condition of this Agreement. Upon termination of this Agreement, you shall delete
118
+ and cease use of the Llama Materials. Sections 3, 4 and 7 shall survive the
119
+ termination of this Agreement.
120
+
121
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and
122
+ construed under the laws of the State of California without regard to choice of law
123
+ principles, and the UN Convention on Contracts for the International Sale of Goods
124
+ does not apply to this Agreement. The courts of California shall have exclusive
125
+ jurisdiction of any dispute arising out of this Agreement.
126
+
models/CodeLlama-7B-Python-GPTQ/Notice ADDED
@@ -0,0 +1 @@
 
 
1
+ Llama 2 is licensed under the LLAMA 2 Community License, Copyright © Meta Platforms, Inc. All Rights Reserved.
models/CodeLlama-7B-Python-GPTQ/README.md ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - code
4
+ license: llama2
5
+ tags:
6
+ - llama-2
7
+ model_name: CodeLlama 7B Python
8
+ base_model: codellama/CodeLlama-7b-python-hf
9
+ inference: false
10
+ model_creator: Meta
11
+ model_type: llama
12
+ pipeline_tag: text-generation
13
+ prompt_template: '[INST] Write code to solve the following coding problem that obeys
14
+ the constraints and passes the example test cases. Please wrap your code answer
15
+ using ```:
16
+
17
+ {prompt}
18
+
19
+ [/INST]
20
+
21
+ '
22
+ quantized_by: TheBloke
23
+ ---
24
+
25
+ <!-- header start -->
26
+ <!-- 200823 -->
27
+ <div style="width: auto; margin-left: auto; margin-right: auto">
28
+ <img src="https://i.imgur.com/EBdldam.jpg" alt="TheBlokeAI" style="width: 100%; min-width: 400px; display: block; margin: auto;">
29
+ </div>
30
+ <div style="display: flex; justify-content: space-between; width: 100%;">
31
+ <div style="display: flex; flex-direction: column; align-items: flex-start;">
32
+ <p style="margin-top: 0.5em; margin-bottom: 0em;"><a href="https://discord.gg/theblokeai">Chat & support: TheBloke's Discord server</a></p>
33
+ </div>
34
+ <div style="display: flex; flex-direction: column; align-items: flex-end;">
35
+ <p style="margin-top: 0.5em; margin-bottom: 0em;"><a href="https://www.patreon.com/TheBlokeAI">Want to contribute? TheBloke's Patreon page</a></p>
36
+ </div>
37
+ </div>
38
+ <div style="text-align:center; margin-top: 0em; margin-bottom: 0em"><p style="margin-top: 0.25em; margin-bottom: 0em;">TheBloke's LLM work is generously supported by a grant from <a href="https://a16z.com">andreessen horowitz (a16z)</a></p></div>
39
+ <hr style="margin-top: 1.0em; margin-bottom: 1.0em;">
40
+ <!-- header end -->
41
+
42
+ # CodeLlama 7B Python - GPTQ
43
+ - Model creator: [Meta](https://huggingface.co/meta-llama)
44
+ - Original model: [CodeLlama 7B Python](https://huggingface.co/codellama/CodeLlama-7b-python-hf)
45
+
46
+ <!-- description start -->
47
+ ## Description
48
+
49
+ This repo contains GPTQ model files for [Meta's CodeLlama 7B Python](https://huggingface.co/codellama/CodeLlama-7b-python-hf).
50
+
51
+ Multiple GPTQ parameter permutations are provided; see Provided Files below for details of the options provided, their parameters, and the software used to create them.
52
+
53
+ <!-- description end -->
54
+ <!-- repositories-available start -->
55
+ ## Repositories available
56
+
57
+ * [AWQ model(s) for GPU inference.](https://huggingface.co/TheBloke/CodeLlama-7B-Python-AWQ)
58
+ * [GPTQ models for GPU inference, with multiple quantisation parameter options.](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ)
59
+ * [2, 3, 4, 5, 6 and 8-bit GGUF models for CPU+GPU inference](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GGUF)
60
+ * [Meta's original unquantised fp16 model in pytorch format, for GPU inference and for further conversions](https://huggingface.co/codellama/CodeLlama-7b-python-hf)
61
+ <!-- repositories-available end -->
62
+
63
+ <!-- prompt-template start -->
64
+ ## Prompt template: CodeLlama
65
+
66
+ ```
67
+ [INST] Write code to solve the following coding problem that obeys the constraints and passes the example test cases. Please wrap your code answer using ```:
68
+ {prompt}
69
+ [/INST]
70
+
71
+ ```
72
+
73
+ <!-- prompt-template end -->
74
+
75
+
76
+ <!-- README_GPTQ.md-provided-files start -->
77
+ ## Provided files and GPTQ parameters
78
+
79
+ Multiple quantisation parameters are provided, to allow you to choose the best one for your hardware and requirements.
80
+
81
+ Each separate quant is in a different branch. See below for instructions on fetching from different branches.
82
+
83
+ All recent GPTQ files are made with AutoGPTQ, and all files in non-main branches are made with AutoGPTQ. Files in the `main` branch which were uploaded before August 2023 were made with GPTQ-for-LLaMa.
84
+
85
+ <details>
86
+ <summary>Explanation of GPTQ parameters</summary>
87
+
88
+ - Bits: The bit size of the quantised model.
89
+ - GS: GPTQ group size. Higher numbers use less VRAM, but have lower quantisation accuracy. "None" is the lowest possible value.
90
+ - Act Order: True or False. Also known as `desc_act`. True results in better quantisation accuracy. Some GPTQ clients have had issues with models that use Act Order plus Group Size, but this is generally resolved now.
91
+ - Damp %: A GPTQ parameter that affects how samples are processed for quantisation. 0.01 is default, but 0.1 results in slightly better accuracy.
92
+ - GPTQ dataset: The dataset used for quantisation. Using a dataset more appropriate to the model's training can improve quantisation accuracy. Note that the GPTQ dataset is not the same as the dataset used to train the model - please refer to the original model repo for details of the training dataset(s).
93
+ - Sequence Length: The length of the dataset sequences used for quantisation. Ideally this is the same as the model sequence length. For some very long sequence models (16+K), a lower sequence length may have to be used. Note that a lower sequence length does not limit the sequence length of the quantised model. It only impacts the quantisation accuracy on longer inference sequences.
94
+ - ExLlama Compatibility: Whether this file can be loaded with ExLlama, which currently only supports Llama models in 4-bit.
95
+
96
+ </details>
97
+
98
+ | Branch | Bits | GS | Act Order | Damp % | GPTQ Dataset | Seq Len | Size | ExLlama | Desc |
99
+ | ------ | ---- | -- | --------- | ------ | ------------ | ------- | ---- | ------- | ---- |
100
+ | [main](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ/tree/main) | 4 | 128 | No | 0.1 | [Evol Instruct Code](https://huggingface.co/datasets/nickrosh/Evol-Instruct-Code-80k-v1) | 8192 | 3.90 GB | Yes | 4-bit, without Act Order and group size 128g. |
101
+ | [gptq-4bit-32g-actorder_True](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ/tree/gptq-4bit-32g-actorder_True) | 4 | 32 | Yes | 0.1 | [Evol Instruct Code](https://huggingface.co/datasets/nickrosh/Evol-Instruct-Code-80k-v1) | 8192 | 4.28 GB | Yes | 4-bit, with Act Order and group size 32g. Gives highest possible inference quality, with maximum VRAM usage. |
102
+ | [gptq-4bit-64g-actorder_True](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ/tree/gptq-4bit-64g-actorder_True) | 4 | 64 | Yes | 0.1 | [Evol Instruct Code](https://huggingface.co/datasets/nickrosh/Evol-Instruct-Code-80k-v1) | 8192 | 4.02 GB | Yes | 4-bit, with Act Order and group size 64g. Uses less VRAM than 32g, but with slightly lower accuracy. |
103
+ | [gptq-4bit-128g-actorder_True](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ/tree/gptq-4bit-128g-actorder_True) | 4 | 128 | Yes | 0.1 | [Evol Instruct Code](https://huggingface.co/datasets/nickrosh/Evol-Instruct-Code-80k-v1) | 8192 | 3.90 GB | Yes | 4-bit, with Act Order and group size 128g. Uses even less VRAM than 64g, but with slightly lower accuracy. |
104
+ | [gptq-8bit--1g-actorder_True](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ/tree/gptq-8bit--1g-actorder_True) | 8 | None | Yes | 0.1 | [Evol Instruct Code](https://huggingface.co/datasets/nickrosh/Evol-Instruct-Code-80k-v1) | 8192 | 7.01 GB | No | 8-bit, with Act Order. No group size, to lower VRAM requirements. |
105
+ | [gptq-8bit-128g-actorder_True](https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ/tree/gptq-8bit-128g-actorder_True) | 8 | 128 | Yes | 0.1 | [Evol Instruct Code](https://huggingface.co/datasets/nickrosh/Evol-Instruct-Code-80k-v1) | 8192 | 7.16 GB | No | 8-bit, with group size 128g for higher inference quality and with Act Order for even higher accuracy. |
106
+
107
+ <!-- README_GPTQ.md-provided-files end -->
108
+
109
+ <!-- README_GPTQ.md-download-from-branches start -->
110
+ ## How to download from branches
111
+
112
+ - In text-generation-webui, you can add `:branch` to the end of the download name, eg `TheBloke/CodeLlama-7B-Python-GPTQ:main`
113
+ - With Git, you can clone a branch with:
114
+ ```
115
+ git clone --single-branch --branch main https://huggingface.co/TheBloke/CodeLlama-7B-Python-GPTQ
116
+ ```
117
+ - In Python Transformers code, the branch is the `revision` parameter; see below.
118
+ <!-- README_GPTQ.md-download-from-branches end -->
119
+ <!-- README_GPTQ.md-text-generation-webui start -->
120
+ ## How to easily download and use this model in [text-generation-webui](https://github.com/oobabooga/text-generation-webui).
121
+
122
+ Please make sure you're using the latest version of [text-generation-webui](https://github.com/oobabooga/text-generation-webui).
123
+
124
+ It is strongly recommended to use the text-generation-webui one-click-installers unless you're sure you know how to make a manual install.
125
+
126
+ 1. Click the **Model tab**.
127
+ 2. Under **Download custom model or LoRA**, enter `TheBloke/CodeLlama-7B-Python-GPTQ`.
128
+ - To download from a specific branch, enter for example `TheBloke/CodeLlama-7B-Python-GPTQ:main`
129
+ - see Provided Files above for the list of branches for each option.
130
+ 3. Click **Download**.
131
+ 4. The model will start downloading. Once it's finished it will say "Done".
132
+ 5. In the top left, click the refresh icon next to **Model**.
133
+ 6. In the **Model** dropdown, choose the model you just downloaded: `CodeLlama-7B-Python-GPTQ`
134
+ 7. The model will automatically load, and is now ready for use!
135
+ 8. If you want any custom settings, set them and then click **Save settings for this model** followed by **Reload the Model** in the top right.
136
+ * Note that you do not need to and should not set manual GPTQ parameters any more. These are set automatically from the file `quantize_config.json`.
137
+ 9. Once you're ready, click the **Text Generation tab** and enter a prompt to get started!
138
+ <!-- README_GPTQ.md-text-generation-webui end -->
139
+
140
+ <!-- README_GPTQ.md-use-from-python start -->
141
+ ## How to use this GPTQ model from Python code
142
+
143
+ ### Install the necessary packages
144
+
145
+ Requires: Transformers 4.32.0 or later, Optimum 1.12.0 or later, and AutoGPTQ 0.4.2 or later.
146
+
147
+ ```shell
148
+ pip3 install transformers>=4.32.0 optimum>=1.12.0
149
+ pip3 install auto-gptq --extra-index-url https://huggingface.github.io/autogptq-index/whl/cu118/ # Use cu117 if on CUDA 11.7
150
+ ```
151
+
152
+ If you have problems installing AutoGPTQ using the pre-built wheels, install it from source instead:
153
+
154
+ ```shell
155
+ pip3 uninstall -y auto-gptq
156
+ git clone https://github.com/PanQiWei/AutoGPTQ
157
+ cd AutoGPTQ
158
+ pip3 install .
159
+ ```
160
+
161
+ ### For CodeLlama models only: you must use Transformers 4.33.0 or later.
162
+
163
+ If 4.33.0 is not yet released when you read this, you will need to install Transformers from source:
164
+ ```shell
165
+ pip3 uninstall -y transformers
166
+ pip3 install git+https://github.com/huggingface/transformers.git
167
+ ```
168
+
169
+ ### You can then use the following code
170
+
171
+ ```python
172
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
173
+
174
+ model_name_or_path = "TheBloke/CodeLlama-7B-Python-GPTQ"
175
+ # To use a different branch, change revision
176
+ # For example: revision="main"
177
+ model = AutoModelForCausalLM.from_pretrained(model_name_or_path,
178
+ device_map="auto",
179
+ trust_remote_code=True,
180
+ revision="main")
181
+
182
+ tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True)
183
+
184
+ prompt = "Tell me about AI"
185
+ prompt_template=f'''[INST] Write code to solve the following coding problem that obeys the constraints and passes the example test cases. Please wrap your code answer using ```:
186
+ {prompt}
187
+ [/INST]
188
+
189
+ '''
190
+
191
+ print("\n\n*** Generate:")
192
+
193
+ input_ids = tokenizer(prompt_template, return_tensors='pt').input_ids.cuda()
194
+ output = model.generate(inputs=input_ids, temperature=0.7, do_sample=True, top_p=0.95, top_k=40, max_new_tokens=512)
195
+ print(tokenizer.decode(output[0]))
196
+
197
+ # Inference can also be done using transformers' pipeline
198
+
199
+ print("*** Pipeline:")
200
+ pipe = pipeline(
201
+ "text-generation",
202
+ model=model,
203
+ tokenizer=tokenizer,
204
+ max_new_tokens=512,
205
+ do_sample=True,
206
+ temperature=0.7,
207
+ top_p=0.95,
208
+ top_k=40,
209
+ repetition_penalty=1.1
210
+ )
211
+
212
+ print(pipe(prompt_template)[0]['generated_text'])
213
+ ```
214
+ <!-- README_GPTQ.md-use-from-python end -->
215
+
216
+ <!-- README_GPTQ.md-compatibility start -->
217
+ ## Compatibility
218
+
219
+ The files provided are tested to work with AutoGPTQ, both via Transformers and using AutoGPTQ directly. They should also work with [Occ4m's GPTQ-for-LLaMa fork](https://github.com/0cc4m/KoboldAI).
220
+
221
+ [ExLlama](https://github.com/turboderp/exllama) is compatible with Llama models in 4-bit. Please see the Provided Files table above for per-file compatibility.
222
+
223
+ [Huggingface Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference) is compatible with all GPTQ models.
224
+ <!-- README_GPTQ.md-compatibility end -->
225
+
226
+ <!-- footer start -->
227
+ <!-- 200823 -->
228
+ ## Discord
229
+
230
+ For further support, and discussions on these models and AI in general, join us at:
231
+
232
+ [TheBloke AI's Discord server](https://discord.gg/theblokeai)
233
+
234
+ ## Thanks, and how to contribute
235
+
236
+ Thanks to the [chirper.ai](https://chirper.ai) team!
237
+
238
+ Thanks to Clay from [gpus.llm-utils.org](llm-utils)!
239
+
240
+ I've had a lot of people ask if they can contribute. I enjoy providing models and helping people, and would love to be able to spend even more time doing it, as well as expanding into new projects like fine tuning/training.
241
+
242
+ If you're able and willing to contribute it will be most gratefully received and will help me to keep providing more models, and to start work on new AI projects.
243
+
244
+ Donaters will get priority support on any and all AI/LLM/model questions and requests, access to a private Discord room, plus other benefits.
245
+
246
+ * Patreon: https://patreon.com/TheBlokeAI
247
+ * Ko-Fi: https://ko-fi.com/TheBlokeAI
248
+
249
+ **Special thanks to**: Aemon Algiz.
250
+
251
+ **Patreon special mentions**: Alicia Loh, Stephen Murray, K, Ajan Kanaga, RoA, Magnesian, Deo Leter, Olakabola, Eugene Pentland, zynix, Deep Realms, Raymond Fosdick, Elijah Stavena, Iucharbius, Erik Bjäreholt, Luis Javier Navarrete Lozano, Nicholas, theTransient, John Detwiler, alfie_i, knownsqashed, Mano Prime, Willem Michiel, Enrico Ros, LangChain4j, OG, Michael Dempsey, Pierre Kircher, Pedro Madruga, James Bentley, Thomas Belote, Luke @flexchar, Leonard Tan, Johann-Peter Hartmann, Illia Dulskyi, Fen Risland, Chadd, S_X, Jeff Scroggin, Ken Nordquist, Sean Connelly, Artur Olbinski, Swaroop Kallakuri, Jack West, Ai Maven, David Ziegler, Russ Johnson, transmissions 11, John Villwock, Alps Aficionado, Clay Pascal, Viktor Bowallius, Subspace Studios, Rainer Wilmers, Trenton Dambrowitz, vamX, Michael Levine, 준교 김, Brandon Frisco, Kalila, Trailburnt, Randy H, Talal Aujan, Nathan Dryer, Vadim, 阿明, ReadyPlayerEmma, Tiffany J. Kim, George Stoitzev, Spencer Kim, Jerry Meng, Gabriel Tamborski, Cory Kujawski, Jeffrey Morgan, Spiking Neurons AB, Edmond Seymore, Alexandros Triantafyllidis, Lone Striker, Cap'n Zoog, Nikolai Manek, danny, ya boyyy, Derek Yates, usrbinkat, Mandus, TL, Nathan LeClaire, subjectnull, Imad Khwaja, webtim, Raven Klaugh, Asp the Wyvern, Gabriel Puliatti, Caitlyn Gatomon, Joseph William Delisle, Jonathan Leane, Luke Pendergrass, SuperWojo, Sebastain Graf, Will Dee, Fred von Graf, Andrey, Dan Guido, Daniel P. Andersen, Nitin Borwankar, Elle, Vitor Caleffi, biorpg, jjj, NimbleBox.ai, Pieter, Matthew Berman, terasurfer, Michael Davis, Alex, Stanislav Ovsiannikov
252
+
253
+
254
+ Thank you to all my generous patrons and donaters!
255
+
256
+ And thank you again to a16z for their generous grant.
257
+
258
+ <!-- footer end -->
259
+
260
+ # Original model card: Meta's CodeLlama 7B Python
261
+
262
+ # **Code Llama**
263
+ Code Llama is a collection of pretrained and fine-tuned generative text models ranging in scale from 7 billion to 34 billion parameters. This is the repository for the 7B Python specialist version in the Hugging Face Transformers format. This model is designed for general code synthesis and understanding. Links to other models can be found in the index at the bottom.
264
+
265
+ | | Base Model | Python | Instruct |
266
+ | --- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
267
+ | 7B | [codellama/CodeLlama-7b-hf](https://huggingface.co/codellama/CodeLlama-7b-hf) | [codellama/CodeLlama-7b-Python-hf](https://huggingface.co/codellama/CodeLlama-7b-Python-hf) | [codellama/CodeLlama-7b-Instruct-hf](https://huggingface.co/codellama/CodeLlama-7b-Instruct-hf) |
268
+ | 13B | [codellama/CodeLlama-13b-hf](https://huggingface.co/codellama/CodeLlama-13b-hf) | [codellama/CodeLlama-13b-Python-hf](https://huggingface.co/codellama/CodeLlama-13b-Python-hf) | [codellama/CodeLlama-13b-Instruct-hf](https://huggingface.co/codellama/CodeLlama-13b-Instruct-hf) |
269
+ | 34B | [codellama/CodeLlama-34b-hf](https://huggingface.co/codellama/CodeLlama-34b-hf) | [codellama/CodeLlama-34b-Python-hf](https://huggingface.co/codellama/CodeLlama-34b-Python-hf) | [codellama/CodeLlama-34b-Instruct-hf](https://huggingface.co/codellama/CodeLlama-34b-Instruct-hf) |
270
+
271
+ ## Model Use
272
+
273
+ To use this model, please make sure to install transformers from `main` until the next version is released:
274
+
275
+ ```bash
276
+ pip install git+https://github.com/huggingface/transformers.git@main accelerate
277
+ ```
278
+
279
+ Model capabilities:
280
+
281
+ - [x] Code completion.
282
+ - [ ] Infilling.
283
+ - [ ] Instructions / chat.
284
+ - [x] Python specialist.
285
+
286
+ ## Model Details
287
+ *Note: Use of this model is governed by the Meta license. Meta developed and publicly released the Code Llama family of large language models (LLMs).
288
+
289
+ **Model Developers** Meta
290
+
291
+ **Variations** Code Llama comes in three model sizes, and three variants:
292
+
293
+ * Code Llama: base models designed for general code synthesis and understanding
294
+ * Code Llama - Python: designed specifically for Python
295
+ * Code Llama - Instruct: for instruction following and safer deployment
296
+
297
+ All variants are available in sizes of 7B, 13B and 34B parameters.
298
+
299
+ **This repository contains the Python version of the 7B parameters model.**
300
+
301
+ **Input** Models input text only.
302
+
303
+ **Output** Models generate text only.
304
+
305
+ **Model Architecture** Code Llama is an auto-regressive language model that uses an optimized transformer architecture.
306
+
307
+ **Model Dates** Code Llama and its variants have been trained between January 2023 and July 2023.
308
+
309
+ **Status** This is a static model trained on an offline dataset. Future versions of Code Llama - Instruct will be released as we improve model safety with community feedback.
310
+
311
+ **License** A custom commercial license is available at: [https://ai.meta.com/resources/models-and-libraries/llama-downloads/](https://ai.meta.com/resources/models-and-libraries/llama-downloads/)
312
+
313
+ **Research Paper** More information can be found in the paper "[Code Llama: Open Foundation Models for Code](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/)" or its [arXiv page](https://arxiv.org/abs/2308.12950).
314
+
315
+ ## Intended Use
316
+ **Intended Use Cases** Code Llama and its variants is intended for commercial and research use in English and relevant programming languages. The base model Code Llama can be adapted for a variety of code synthesis and understanding tasks, Code Llama - Python is designed specifically to handle the Python programming language, and Code Llama - Instruct is intended to be safer to use for code assistant and generation applications.
317
+
318
+ **Out-of-Scope Uses** Use in any manner that violates applicable laws or regulations (including trade compliance laws). Use in languages other than English. Use in any other way that is prohibited by the Acceptable Use Policy and Licensing Agreement for Code Llama and its variants.
319
+
320
+ ## Hardware and Software
321
+ **Training Factors** We used custom training libraries. The training and fine-tuning of the released models have been performed Meta’s Research Super Cluster.
322
+
323
+ **Carbon Footprint** In aggregate, training all 9 Code Llama models required 400K GPU hours of computation on hardware of type A100-80GB (TDP of 350-400W). Estimated total emissions were 65.3 tCO2eq, 100% of which were offset by Meta’s sustainability program.
324
+
325
+ ## Training Data
326
+
327
+ All experiments reported here and the released models have been trained and fine-tuned using the same data as Llama 2 with different weights (see Section 2 and Table 1 in the [research paper](https://ai.meta.com/research/publications/code-llama-open-foundation-models-for-code/) for details).
328
+
329
+ ## Evaluation Results
330
+
331
+ See evaluations for the main models and detailed ablations in Section 3 and safety evaluations in Section 4 of the research paper.
332
+
333
+
334
+ ## Ethical Considerations and Limitations
335
+
336
+ Code Llama and its variants are a new technology that carries risks with use. Testing conducted to date has been in English, and has not covered, nor could it cover all scenarios. For these reasons, as with all LLMs, Code Llama’s potential outputs cannot be predicted in advance, and the model may in some instances produce inaccurate or objectionable responses to user prompts. Therefore, before deploying any applications of Code Llama, developers should perform safety testing and tuning tailored to their specific applications of the model.
337
+
338
+ Please see the Responsible Use Guide available available at [https://ai.meta.com/llama/responsible-user-guide](https://ai.meta.com/llama/responsible-user-guide).
models/CodeLlama-7B-Python-GPTQ/USE_POLICY.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Llama 2 Acceptable Use Policy
2
+
3
+ Meta is committed to promoting safe and fair use of its tools and features, including Llama 2. If you access or use Llama 2, you agree to this Acceptable Use Policy (“Policy”). The most recent copy of this policy can be found at [ai.meta.com/llama/use-policy](http://ai.meta.com/llama/use-policy).
4
+
5
+ ## Prohibited Uses
6
+ We want everyone to use Llama 2 safely and responsibly. You agree you will not use, or allow others to use, Llama 2 to:
7
+
8
+ 1. Violate the law or others’ rights, including to:
9
+ 1. Engage in, promote, generate, contribute to, encourage, plan, incite, or further illegal or unlawful activity or content, such as:
10
+ 1. Violence or terrorism
11
+ 2. Exploitation or harm to children, including the solicitation, creation, acquisition, or dissemination of child exploitative content or failure to report Child Sexual Abuse Material
12
+ 3. Human trafficking, exploitation, and sexual violence
13
+ 4. The illegal distribution of information or materials to minors, including obscene materials, or failure to employ legally required age-gating in connection with such information or materials.
14
+ 5. Sexual solicitation
15
+ 6. Any other criminal activity
16
+ 2. Engage in, promote, incite, or facilitate the harassment, abuse, threatening, or bullying of individuals or groups of individuals
17
+ 3. Engage in, promote, incite, or facilitate discrimination or other unlawful or harmful conduct in the provision of employment, employment benefits, credit, housing, other economic benefits, or other essential goods and services
18
+ 4. Engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or related professional practices
19
+ 5. Collect, process, disclose, generate, or infer health, demographic, or other sensitive personal or private information about individuals without rights and consents required by applicable laws
20
+ 6. Engage in or facilitate any action or generate any content that infringes, misappropriates, or otherwise violates any third-party rights, including the outputs or results of any products or services using the Llama 2 Materials
21
+ 7. Create, generate, or facilitate the creation of malicious code, malware, computer viruses or do anything else that could disable, overburden, interfere with or impair the proper working, integrity, operation or appearance of a website or computer system
22
+
23
+
24
+
25
+ 2. Engage in, promote, incite, facilitate, or assist in the planning or development of activities that present a risk of death or bodily harm to individuals, including use of Llama 2 related to the following:
26
+ 1. Military, warfare, nuclear industries or applications, espionage, use for materials or activities that are subject to the International Traffic Arms Regulations (ITAR) maintained by the United States Department of State
27
+ 2. Guns and illegal weapons (including weapon development)
28
+ 3. Illegal drugs and regulated/controlled substances
29
+ 4. Operation of critical infrastructure, transportation technologies, or heavy machinery
30
+ 5. Self-harm or harm to others, including suicide, cutting, and eating disorders
31
+ 6. Any content intended to incite or promote violence, abuse, or any infliction of bodily harm to an individual
32
+
33
+
34
+
35
+ 3. Intentionally deceive or mislead others, including use of Llama 2 related to the following:
36
+ 1. Generating, promoting, or furthering fraud or the creation or promotion of disinformation
37
+ 2. Generating, promoting, or furthering defamatory content, including the creation of defamatory statements, images, or other content
38
+ 3. Generating, promoting, or further distributing spam
39
+ 4. Impersonating another individual without consent, authorization, or legal right
40
+ 5. Representing that the use of Llama 2 or outputs are human-generated
41
+ 6. Generating or facilitating false online engagement, including fake reviews and other means of fake online engagement
42
+ 4. Fail to appropriately disclose to end users any known dangers of your AI system
43
+
44
+ Please report any violation of this Policy, software “bug,” or other problems that could lead to a violation of this Policy through one of the following means:
45
+
46
+ * Reporting issues with the model: [github.com/facebookresearch/llama](http://github.com/facebookresearch/llama)
47
+ * Reporting risky content generated by the model: [developers.facebook.com/llama_output_feedback](http://developers.facebook.com/llama_output_feedback)
48
+ * Reporting bugs and security concerns: [facebook.com/whitehat/info](http://facebook.com/whitehat/info)
49
+ * Reporting violations of the Acceptable Use Policy or unlicensed uses of Llama: [LlamaUseReport@meta.com](mailto:LlamaUseReport@meta.com)
50
+
models/CodeLlama-7B-Python-GPTQ/config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlamaForCausalLM"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "eos_token_id": 2,
7
+ "hidden_act": "silu",
8
+ "hidden_size": 4096,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 11008,
11
+ "max_position_embeddings": 16384,
12
+ "model_type": "llama",
13
+ "num_attention_heads": 32,
14
+ "num_hidden_layers": 32,
15
+ "num_key_value_heads": 32,
16
+ "pretraining_tp": 1,
17
+ "rms_norm_eps": 1e-05,
18
+ "rope_scaling": null,
19
+ "tie_word_embeddings": false,
20
+ "torch_dtype": "float16",
21
+ "transformers_version": "4.32.0",
22
+ "use_cache": true,
23
+ "vocab_size": 32000,
24
+ "auto_map": {
25
+ "AutoConfig": "configuration_llama.LlamaConfig",
26
+ "AutoModel": "modeling_llama.LlamaModel",
27
+ "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM",
28
+ "AutoModelForSequenceClassification": "modeling_llama.LlamaForSequenceClassification"
29
+ },
30
+ "rope_theta": 1000000,
31
+ "quantization_config": {
32
+ "bits": 4,
33
+ "group_size": 128,
34
+ "damp_percent": 0.1,
35
+ "desc_act": false,
36
+ "sym": true,
37
+ "true_sequential": true,
38
+ "model_name_or_path": null,
39
+ "model_file_base_name": "model",
40
+ "quant_method": "gptq"
41
+ },
42
+ "pad_token_id": 0
43
+ }
models/CodeLlama-7B-Python-GPTQ/configuration_llama.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class LlamaConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`LlamaModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ pretraining_tp (`int`, *optional*, defaults to `1`):
62
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
63
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
64
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
65
+ issue](https://github.com/pytorch/pytorch/issues/76232).
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
70
+ just in case (e.g., 512 or 1024 or 2048).
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
74
+ The epsilon used by the rms normalization layers.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
77
+ relevant if `config.is_decoder=True`.
78
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_scaling (`Dict`, *optional*):
81
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
82
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
83
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
84
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
85
+ these scaling strategies behave:
86
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
87
+ experimental feature, subject to breaking API changes in future versions.
88
+
89
+ Example:
90
+
91
+ ```python
92
+ >>> from transformers import LlamaModel, LlamaConfig
93
+
94
+ >>> # Initializing a LLaMA llama-7b style configuration
95
+ >>> configuration = LlamaConfig()
96
+
97
+ >>> # Initializing a model from the llama-7b style configuration
98
+ >>> model = LlamaModel(configuration)
99
+
100
+ >>> # Accessing the model configuration
101
+ >>> configuration = model.config
102
+ ```"""
103
+ model_type = "llama"
104
+ keys_to_ignore_at_inference = ["past_key_values"]
105
+
106
+ def __init__(
107
+ self,
108
+ vocab_size=32000,
109
+ hidden_size=4096,
110
+ intermediate_size=11008,
111
+ num_hidden_layers=32,
112
+ num_attention_heads=32,
113
+ num_key_value_heads=None,
114
+ hidden_act="silu",
115
+ max_position_embeddings=2048,
116
+ initializer_range=0.02,
117
+ rms_norm_eps=1e-6,
118
+ use_cache=True,
119
+ pad_token_id=None,
120
+ bos_token_id=1,
121
+ eos_token_id=2,
122
+ pretraining_tp=1,
123
+ tie_word_embeddings=False,
124
+ rope_scaling=None,
125
+ rope_theta=10000,
126
+ **kwargs,
127
+ ):
128
+ self.vocab_size = vocab_size
129
+ self.max_position_embeddings = max_position_embeddings
130
+ self.hidden_size = hidden_size
131
+ self.intermediate_size = intermediate_size
132
+ self.num_hidden_layers = num_hidden_layers
133
+ self.num_attention_heads = num_attention_heads
134
+
135
+ # for backward compatibility
136
+ if num_key_value_heads is None:
137
+ num_key_value_heads = num_attention_heads
138
+
139
+ self.num_key_value_heads = num_key_value_heads
140
+ self.hidden_act = hidden_act
141
+ self.initializer_range = initializer_range
142
+ self.rms_norm_eps = rms_norm_eps
143
+ self.pretraining_tp = pretraining_tp
144
+ self.use_cache = use_cache
145
+ self.rope_scaling = rope_scaling
146
+ self._rope_scaling_validation()
147
+ self.rope_theta = rope_theta
148
+
149
+ super().__init__(
150
+ pad_token_id=pad_token_id,
151
+ bos_token_id=bos_token_id,
152
+ eos_token_id=eos_token_id,
153
+ tie_word_embeddings=tie_word_embeddings,
154
+ **kwargs,
155
+ )
156
+
157
+ def _rope_scaling_validation(self):
158
+ """
159
+ Validate the `rope_scaling` configuration.
160
+ """
161
+ if self.rope_scaling is None:
162
+ return
163
+
164
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
165
+ raise ValueError(
166
+ "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
167
+ f"got {self.rope_scaling}"
168
+ )
169
+ rope_scaling_type = self.rope_scaling.get("type", None)
170
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
171
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
172
+ raise ValueError(
173
+ f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
174
+ )
175
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
176
+ raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
models/CodeLlama-7B-Python-GPTQ/generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "pad_token_id": 0,
4
+ "bos_token_id": 1,
5
+ "eos_token_id": 2,
6
+ "transformers_version": "4.32.0"
7
+ }
models/CodeLlama-7B-Python-GPTQ/modeling_llama.py ADDED
@@ -0,0 +1,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
32
+ from transformers.modeling_utils import PreTrainedModel
33
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
34
+ from .configuration_llama import LlamaConfig
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ _CONFIG_FOR_DOC = "LlamaConfig"
40
+
41
+
42
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
43
+ def _make_causal_mask(
44
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
45
+ ):
46
+ """
47
+ Make causal mask used for bi-directional self-attention.
48
+ """
49
+ bsz, tgt_len = input_ids_shape
50
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
51
+ mask_cond = torch.arange(mask.size(-1), device=device)
52
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
53
+ mask = mask.to(dtype)
54
+
55
+ if past_key_values_length > 0:
56
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
57
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
58
+
59
+
60
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
61
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
62
+ """
63
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
64
+ """
65
+ bsz, src_len = mask.size()
66
+ tgt_len = tgt_len if tgt_len is not None else src_len
67
+
68
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
69
+
70
+ inverted_mask = 1.0 - expanded_mask
71
+
72
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
73
+
74
+
75
+ class LlamaRMSNorm(nn.Module):
76
+ def __init__(self, hidden_size, eps=1e-6):
77
+ """
78
+ LlamaRMSNorm is equivalent to T5LayerNorm
79
+ """
80
+ super().__init__()
81
+ self.weight = nn.Parameter(torch.ones(hidden_size))
82
+ self.variance_epsilon = eps
83
+
84
+ def forward(self, hidden_states):
85
+ input_dtype = hidden_states.dtype
86
+ hidden_states = hidden_states.to(torch.float32)
87
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
88
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
89
+ return self.weight * hidden_states.to(input_dtype)
90
+
91
+
92
+ class LlamaRotaryEmbedding(torch.nn.Module):
93
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
94
+ super().__init__()
95
+
96
+ self.dim = dim
97
+ self.max_position_embeddings = max_position_embeddings
98
+ self.base = base
99
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
100
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
101
+
102
+ # Build here to make `torch.jit.trace` work.
103
+ self._set_cos_sin_cache(
104
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
105
+ )
106
+
107
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
108
+ self.max_seq_len_cached = seq_len
109
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
110
+
111
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
112
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
113
+ emb = torch.cat((freqs, freqs), dim=-1)
114
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
115
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
116
+
117
+ def forward(self, x, seq_len=None):
118
+ # x: [bs, num_attention_heads, seq_len, head_size]
119
+ if seq_len > self.max_seq_len_cached:
120
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
121
+
122
+ return (
123
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
124
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
125
+ )
126
+
127
+
128
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
129
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
130
+
131
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
132
+ self.scaling_factor = scaling_factor
133
+ super().__init__(dim, max_position_embeddings, base, device)
134
+
135
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
136
+ self.max_seq_len_cached = seq_len
137
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
138
+ t = t / self.scaling_factor
139
+
140
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
141
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
142
+ emb = torch.cat((freqs, freqs), dim=-1)
143
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
144
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
145
+
146
+
147
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
148
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
149
+
150
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
151
+ self.scaling_factor = scaling_factor
152
+ super().__init__(dim, max_position_embeddings, base, device)
153
+
154
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
155
+ self.max_seq_len_cached = seq_len
156
+
157
+ if seq_len > self.max_position_embeddings:
158
+ base = self.base * (
159
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
160
+ ) ** (self.dim / (self.dim - 2))
161
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
162
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
163
+
164
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
165
+
166
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
167
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
168
+ emb = torch.cat((freqs, freqs), dim=-1)
169
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
170
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
171
+
172
+
173
+ def rotate_half(x):
174
+ """Rotates half the hidden dims of the input."""
175
+ x1 = x[..., : x.shape[-1] // 2]
176
+ x2 = x[..., x.shape[-1] // 2 :]
177
+ return torch.cat((-x2, x1), dim=-1)
178
+
179
+
180
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
181
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
182
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
183
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
184
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
185
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
186
+ q_embed = (q * cos) + (rotate_half(q) * sin)
187
+ k_embed = (k * cos) + (rotate_half(k) * sin)
188
+ return q_embed, k_embed
189
+
190
+
191
+ class LlamaMLP(nn.Module):
192
+ def __init__(self, config):
193
+ super().__init__()
194
+ self.config = config
195
+ self.hidden_size = config.hidden_size
196
+ self.intermediate_size = config.intermediate_size
197
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
198
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
199
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
200
+ self.act_fn = ACT2FN[config.hidden_act]
201
+
202
+ def forward(self, x):
203
+ if self.config.pretraining_tp > 1:
204
+ slice = self.intermediate_size // self.config.pretraining_tp
205
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
206
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
207
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
208
+
209
+ gate_proj = torch.cat(
210
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
211
+ )
212
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
213
+
214
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
215
+ down_proj = [
216
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
217
+ ]
218
+ down_proj = sum(down_proj)
219
+ else:
220
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
221
+
222
+ return down_proj
223
+
224
+
225
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
226
+ """
227
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
228
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
229
+ """
230
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
231
+ if n_rep == 1:
232
+ return hidden_states
233
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
234
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
235
+
236
+
237
+ class LlamaAttention(nn.Module):
238
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
239
+
240
+ def __init__(self, config: LlamaConfig):
241
+ super().__init__()
242
+ self.config = config
243
+ self.hidden_size = config.hidden_size
244
+ self.num_heads = config.num_attention_heads
245
+ self.head_dim = self.hidden_size // self.num_heads
246
+ self.num_key_value_heads = config.num_key_value_heads
247
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
248
+ self.max_position_embeddings = config.max_position_embeddings
249
+ self.rope_theta = config.rope_theta
250
+
251
+ if (self.head_dim * self.num_heads) != self.hidden_size:
252
+ raise ValueError(
253
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
254
+ f" and `num_heads`: {self.num_heads})."
255
+ )
256
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
257
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
258
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
259
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
260
+ self._init_rope()
261
+
262
+ def _init_rope(self):
263
+ if self.config.rope_scaling is None:
264
+ self.rotary_emb = LlamaRotaryEmbedding(
265
+ self.head_dim, max_position_embeddings=self.max_position_embeddings,
266
+ base=self.rope_theta
267
+ )
268
+ else:
269
+ scaling_type = self.config.rope_scaling["type"]
270
+ scaling_factor = self.config.rope_scaling["factor"]
271
+ if scaling_type == "linear":
272
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
273
+ self.head_dim, max_position_embeddings=self.max_position_embeddings,
274
+ base=self.rope_theta, scaling_factor=scaling_factor
275
+ )
276
+ elif scaling_type == "dynamic":
277
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
278
+ self.head_dim, max_position_embeddings=self.max_position_embeddings,
279
+ base=self.rope_theta, scaling_factor=scaling_factor
280
+ )
281
+ else:
282
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
283
+
284
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
285
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
286
+
287
+ def forward(
288
+ self,
289
+ hidden_states: torch.Tensor,
290
+ attention_mask: Optional[torch.Tensor] = None,
291
+ position_ids: Optional[torch.LongTensor] = None,
292
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
293
+ output_attentions: bool = False,
294
+ use_cache: bool = False,
295
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
296
+ bsz, q_len, _ = hidden_states.size()
297
+
298
+ if self.config.pretraining_tp > 1:
299
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
300
+ query_slices = self.q_proj.weight.split(
301
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
302
+ )
303
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
304
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
305
+
306
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
307
+ query_states = torch.cat(query_states, dim=-1)
308
+
309
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
310
+ key_states = torch.cat(key_states, dim=-1)
311
+
312
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
313
+ value_states = torch.cat(value_states, dim=-1)
314
+
315
+ else:
316
+ query_states = self.q_proj(hidden_states)
317
+ key_states = self.k_proj(hidden_states)
318
+ value_states = self.v_proj(hidden_states)
319
+
320
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
321
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
322
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
323
+
324
+ kv_seq_len = key_states.shape[-2]
325
+ if past_key_value is not None:
326
+ kv_seq_len += past_key_value[0].shape[-2]
327
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
328
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
329
+
330
+ if past_key_value is not None:
331
+ # reuse k, v, self_attention
332
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
333
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
334
+
335
+ past_key_value = (key_states, value_states) if use_cache else None
336
+
337
+ # repeat k/v heads if n_kv_heads < n_heads
338
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
339
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
340
+
341
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
342
+
343
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
344
+ raise ValueError(
345
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
346
+ f" {attn_weights.size()}"
347
+ )
348
+
349
+ if attention_mask is not None:
350
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
351
+ raise ValueError(
352
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
353
+ )
354
+ attn_weights = attn_weights + attention_mask
355
+
356
+ # upcast attention to fp32
357
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
358
+ attn_output = torch.matmul(attn_weights, value_states)
359
+
360
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
361
+ raise ValueError(
362
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
363
+ f" {attn_output.size()}"
364
+ )
365
+
366
+ attn_output = attn_output.transpose(1, 2).contiguous()
367
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
368
+
369
+ if self.config.pretraining_tp > 1:
370
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
371
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
372
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
373
+ else:
374
+ attn_output = self.o_proj(attn_output)
375
+
376
+ if not output_attentions:
377
+ attn_weights = None
378
+
379
+ return attn_output, attn_weights, past_key_value
380
+
381
+
382
+ class LlamaDecoderLayer(nn.Module):
383
+ def __init__(self, config: LlamaConfig):
384
+ super().__init__()
385
+ self.hidden_size = config.hidden_size
386
+ self.self_attn = LlamaAttention(config=config)
387
+ self.mlp = LlamaMLP(config)
388
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
389
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
390
+
391
+ def forward(
392
+ self,
393
+ hidden_states: torch.Tensor,
394
+ attention_mask: Optional[torch.Tensor] = None,
395
+ position_ids: Optional[torch.LongTensor] = None,
396
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
397
+ output_attentions: Optional[bool] = False,
398
+ use_cache: Optional[bool] = False,
399
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
400
+ """
401
+ Args:
402
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
403
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
404
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
405
+ output_attentions (`bool`, *optional*):
406
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
407
+ returned tensors for more detail.
408
+ use_cache (`bool`, *optional*):
409
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
410
+ (see `past_key_values`).
411
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
412
+ """
413
+
414
+ residual = hidden_states
415
+
416
+ hidden_states = self.input_layernorm(hidden_states)
417
+
418
+ # Self Attention
419
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
420
+ hidden_states=hidden_states,
421
+ attention_mask=attention_mask,
422
+ position_ids=position_ids,
423
+ past_key_value=past_key_value,
424
+ output_attentions=output_attentions,
425
+ use_cache=use_cache,
426
+ )
427
+ hidden_states = residual + hidden_states
428
+
429
+ # Fully Connected
430
+ residual = hidden_states
431
+ hidden_states = self.post_attention_layernorm(hidden_states)
432
+ hidden_states = self.mlp(hidden_states)
433
+ hidden_states = residual + hidden_states
434
+
435
+ outputs = (hidden_states,)
436
+
437
+ if output_attentions:
438
+ outputs += (self_attn_weights,)
439
+
440
+ if use_cache:
441
+ outputs += (present_key_value,)
442
+
443
+ return outputs
444
+
445
+
446
+ LLAMA_START_DOCSTRING = r"""
447
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
448
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
449
+ etc.)
450
+
451
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
452
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
453
+ and behavior.
454
+
455
+ Parameters:
456
+ config ([`LlamaConfig`]):
457
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
458
+ load the weights associated with the model, only the configuration. Check out the
459
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
460
+ """
461
+
462
+
463
+ @add_start_docstrings(
464
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
465
+ LLAMA_START_DOCSTRING,
466
+ )
467
+ class LlamaPreTrainedModel(PreTrainedModel):
468
+ config_class = LlamaConfig
469
+ base_model_prefix = "model"
470
+ supports_gradient_checkpointing = True
471
+ _no_split_modules = ["LlamaDecoderLayer"]
472
+ _skip_keys_device_placement = "past_key_values"
473
+
474
+ def _init_weights(self, module):
475
+ std = self.config.initializer_range
476
+ if isinstance(module, nn.Linear):
477
+ module.weight.data.normal_(mean=0.0, std=std)
478
+ if module.bias is not None:
479
+ module.bias.data.zero_()
480
+ elif isinstance(module, nn.Embedding):
481
+ module.weight.data.normal_(mean=0.0, std=std)
482
+ if module.padding_idx is not None:
483
+ module.weight.data[module.padding_idx].zero_()
484
+
485
+ def _set_gradient_checkpointing(self, module, value=False):
486
+ if isinstance(module, LlamaModel):
487
+ module.gradient_checkpointing = value
488
+
489
+
490
+ LLAMA_INPUTS_DOCSTRING = r"""
491
+ Args:
492
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
493
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
494
+ it.
495
+
496
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
497
+ [`PreTrainedTokenizer.__call__`] for details.
498
+
499
+ [What are input IDs?](../glossary#input-ids)
500
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
501
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
502
+
503
+ - 1 for tokens that are **not masked**,
504
+ - 0 for tokens that are **masked**.
505
+
506
+ [What are attention masks?](../glossary#attention-mask)
507
+
508
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
509
+ [`PreTrainedTokenizer.__call__`] for details.
510
+
511
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
512
+ `past_key_values`).
513
+
514
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
515
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
516
+ information on the default strategy.
517
+
518
+ - 1 indicates the head is **not masked**,
519
+ - 0 indicates the head is **masked**.
520
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
521
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
522
+ config.n_positions - 1]`.
523
+
524
+ [What are position IDs?](../glossary#position-ids)
525
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
526
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
527
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
528
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
529
+
530
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
531
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
532
+
533
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
534
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
535
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
536
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
537
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
538
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
539
+ model's internal embedding lookup matrix.
540
+ use_cache (`bool`, *optional*):
541
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
542
+ `past_key_values`).
543
+ output_attentions (`bool`, *optional*):
544
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
545
+ tensors for more detail.
546
+ output_hidden_states (`bool`, *optional*):
547
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
548
+ more detail.
549
+ return_dict (`bool`, *optional*):
550
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
551
+ """
552
+
553
+
554
+ @add_start_docstrings(
555
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
556
+ LLAMA_START_DOCSTRING,
557
+ )
558
+ class LlamaModel(LlamaPreTrainedModel):
559
+ """
560
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
561
+
562
+ Args:
563
+ config: LlamaConfig
564
+ """
565
+
566
+ def __init__(self, config: LlamaConfig):
567
+ super().__init__(config)
568
+ self.padding_idx = config.pad_token_id
569
+ self.vocab_size = config.vocab_size
570
+
571
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
572
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
573
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
574
+
575
+ self.gradient_checkpointing = False
576
+ # Initialize weights and apply final processing
577
+ self.post_init()
578
+
579
+ def get_input_embeddings(self):
580
+ return self.embed_tokens
581
+
582
+ def set_input_embeddings(self, value):
583
+ self.embed_tokens = value
584
+
585
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
586
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
587
+ # create causal mask
588
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
589
+ combined_attention_mask = None
590
+ if input_shape[-1] > 1:
591
+ combined_attention_mask = _make_causal_mask(
592
+ input_shape,
593
+ inputs_embeds.dtype,
594
+ device=inputs_embeds.device,
595
+ past_key_values_length=past_key_values_length,
596
+ )
597
+
598
+ if attention_mask is not None:
599
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
600
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
601
+ inputs_embeds.device
602
+ )
603
+ combined_attention_mask = (
604
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
605
+ )
606
+
607
+ return combined_attention_mask
608
+
609
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
610
+ def forward(
611
+ self,
612
+ input_ids: torch.LongTensor = None,
613
+ attention_mask: Optional[torch.Tensor] = None,
614
+ position_ids: Optional[torch.LongTensor] = None,
615
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
616
+ inputs_embeds: Optional[torch.FloatTensor] = None,
617
+ use_cache: Optional[bool] = None,
618
+ output_attentions: Optional[bool] = None,
619
+ output_hidden_states: Optional[bool] = None,
620
+ return_dict: Optional[bool] = None,
621
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
622
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
623
+ output_hidden_states = (
624
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
625
+ )
626
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
627
+
628
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
629
+
630
+ # retrieve input_ids and inputs_embeds
631
+ if input_ids is not None and inputs_embeds is not None:
632
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
633
+ elif input_ids is not None:
634
+ batch_size, seq_length = input_ids.shape
635
+ elif inputs_embeds is not None:
636
+ batch_size, seq_length, _ = inputs_embeds.shape
637
+ else:
638
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
639
+
640
+ seq_length_with_past = seq_length
641
+ past_key_values_length = 0
642
+
643
+ if past_key_values is not None:
644
+ past_key_values_length = past_key_values[0][0].shape[2]
645
+ seq_length_with_past = seq_length_with_past + past_key_values_length
646
+
647
+ if position_ids is None:
648
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
649
+ position_ids = torch.arange(
650
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
651
+ )
652
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
653
+ else:
654
+ position_ids = position_ids.view(-1, seq_length).long()
655
+
656
+ if inputs_embeds is None:
657
+ inputs_embeds = self.embed_tokens(input_ids)
658
+ # embed positions
659
+ if attention_mask is None:
660
+ attention_mask = torch.ones(
661
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
662
+ )
663
+ attention_mask = self._prepare_decoder_attention_mask(
664
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
665
+ )
666
+
667
+ hidden_states = inputs_embeds
668
+
669
+ if self.gradient_checkpointing and self.training:
670
+ if use_cache:
671
+ logger.warning_once(
672
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
673
+ )
674
+ use_cache = False
675
+
676
+ # decoder layers
677
+ all_hidden_states = () if output_hidden_states else None
678
+ all_self_attns = () if output_attentions else None
679
+ next_decoder_cache = () if use_cache else None
680
+
681
+ for idx, decoder_layer in enumerate(self.layers):
682
+ if output_hidden_states:
683
+ all_hidden_states += (hidden_states,)
684
+
685
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
686
+
687
+ if self.gradient_checkpointing and self.training:
688
+
689
+ def create_custom_forward(module):
690
+ def custom_forward(*inputs):
691
+ # None for past_key_value
692
+ return module(*inputs, past_key_value, output_attentions)
693
+
694
+ return custom_forward
695
+
696
+ layer_outputs = torch.utils.checkpoint.checkpoint(
697
+ create_custom_forward(decoder_layer),
698
+ hidden_states,
699
+ attention_mask,
700
+ position_ids,
701
+ )
702
+ else:
703
+ layer_outputs = decoder_layer(
704
+ hidden_states,
705
+ attention_mask=attention_mask,
706
+ position_ids=position_ids,
707
+ past_key_value=past_key_value,
708
+ output_attentions=output_attentions,
709
+ use_cache=use_cache,
710
+ )
711
+
712
+ hidden_states = layer_outputs[0]
713
+
714
+ if use_cache:
715
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
716
+
717
+ if output_attentions:
718
+ all_self_attns += (layer_outputs[1],)
719
+
720
+ hidden_states = self.norm(hidden_states)
721
+
722
+ # add hidden states from the last decoder layer
723
+ if output_hidden_states:
724
+ all_hidden_states += (hidden_states,)
725
+
726
+ next_cache = next_decoder_cache if use_cache else None
727
+ if not return_dict:
728
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
729
+ return BaseModelOutputWithPast(
730
+ last_hidden_state=hidden_states,
731
+ past_key_values=next_cache,
732
+ hidden_states=all_hidden_states,
733
+ attentions=all_self_attns,
734
+ )
735
+
736
+
737
+ class LlamaForCausalLM(LlamaPreTrainedModel):
738
+ _tied_weights_keys = ["lm_head.weight"]
739
+
740
+ def __init__(self, config):
741
+ super().__init__(config)
742
+ self.model = LlamaModel(config)
743
+ self.vocab_size = config.vocab_size
744
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
745
+
746
+ # Initialize weights and apply final processing
747
+ self.post_init()
748
+
749
+ def get_input_embeddings(self):
750
+ return self.model.embed_tokens
751
+
752
+ def set_input_embeddings(self, value):
753
+ self.model.embed_tokens = value
754
+
755
+ def get_output_embeddings(self):
756
+ return self.lm_head
757
+
758
+ def set_output_embeddings(self, new_embeddings):
759
+ self.lm_head = new_embeddings
760
+
761
+ def set_decoder(self, decoder):
762
+ self.model = decoder
763
+
764
+ def get_decoder(self):
765
+ return self.model
766
+
767
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
768
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
769
+ def forward(
770
+ self,
771
+ input_ids: torch.LongTensor = None,
772
+ attention_mask: Optional[torch.Tensor] = None,
773
+ position_ids: Optional[torch.LongTensor] = None,
774
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
775
+ inputs_embeds: Optional[torch.FloatTensor] = None,
776
+ labels: Optional[torch.LongTensor] = None,
777
+ use_cache: Optional[bool] = None,
778
+ output_attentions: Optional[bool] = None,
779
+ output_hidden_states: Optional[bool] = None,
780
+ return_dict: Optional[bool] = None,
781
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
782
+ r"""
783
+ Args:
784
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
785
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
786
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
787
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
788
+
789
+ Returns:
790
+
791
+ Example:
792
+
793
+ ```python
794
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
795
+
796
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
797
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
798
+
799
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
800
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
801
+
802
+ >>> # Generate
803
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
804
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
805
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
806
+ ```"""
807
+
808
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
809
+ output_hidden_states = (
810
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
811
+ )
812
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
813
+
814
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
815
+ outputs = self.model(
816
+ input_ids=input_ids,
817
+ attention_mask=attention_mask,
818
+ position_ids=position_ids,
819
+ past_key_values=past_key_values,
820
+ inputs_embeds=inputs_embeds,
821
+ use_cache=use_cache,
822
+ output_attentions=output_attentions,
823
+ output_hidden_states=output_hidden_states,
824
+ return_dict=return_dict,
825
+ )
826
+
827
+ hidden_states = outputs[0]
828
+ if self.config.pretraining_tp > 1:
829
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
830
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
831
+ logits = torch.cat(logits, dim=-1)
832
+ else:
833
+ logits = self.lm_head(hidden_states)
834
+ logits = logits.float()
835
+
836
+ loss = None
837
+ if labels is not None:
838
+ # Shift so that tokens < n predict n
839
+ shift_logits = logits[..., :-1, :].contiguous()
840
+ shift_labels = labels[..., 1:].contiguous()
841
+ # Flatten the tokens
842
+ loss_fct = CrossEntropyLoss()
843
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
844
+ shift_labels = shift_labels.view(-1)
845
+ # Enable model parallelism
846
+ shift_labels = shift_labels.to(shift_logits.device)
847
+ loss = loss_fct(shift_logits, shift_labels)
848
+
849
+ if not return_dict:
850
+ output = (logits,) + outputs[1:]
851
+ return (loss,) + output if loss is not None else output
852
+
853
+ return CausalLMOutputWithPast(
854
+ loss=loss,
855
+ logits=logits,
856
+ past_key_values=outputs.past_key_values,
857
+ hidden_states=outputs.hidden_states,
858
+ attentions=outputs.attentions,
859
+ )
860
+
861
+ def prepare_inputs_for_generation(
862
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
863
+ ):
864
+ if past_key_values:
865
+ input_ids = input_ids[:, -1:]
866
+
867
+ position_ids = kwargs.get("position_ids", None)
868
+ if attention_mask is not None and position_ids is None:
869
+ # create position_ids on the fly for batch generation
870
+ position_ids = attention_mask.long().cumsum(-1) - 1
871
+ position_ids.masked_fill_(attention_mask == 0, 1)
872
+ if past_key_values:
873
+ position_ids = position_ids[:, -1].unsqueeze(-1)
874
+
875
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
876
+ if inputs_embeds is not None and past_key_values is None:
877
+ model_inputs = {"inputs_embeds": inputs_embeds}
878
+ else:
879
+ model_inputs = {"input_ids": input_ids}
880
+
881
+ model_inputs.update(
882
+ {
883
+ "position_ids": position_ids,
884
+ "past_key_values": past_key_values,
885
+ "use_cache": kwargs.get("use_cache"),
886
+ "attention_mask": attention_mask,
887
+ }
888
+ )
889
+ return model_inputs
890
+
891
+ @staticmethod
892
+ def _reorder_cache(past_key_values, beam_idx):
893
+ reordered_past = ()
894
+ for layer_past in past_key_values:
895
+ reordered_past += (
896
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
897
+ )
898
+ return reordered_past
899
+
900
+
901
+ @add_start_docstrings(
902
+ """
903
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
904
+
905
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
906
+ (e.g. GPT-2) do.
907
+
908
+ Since it does classification on the last token, it requires to know the position of the last token. If a
909
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
910
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
911
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
912
+ each row of the batch).
913
+ """,
914
+ LLAMA_START_DOCSTRING,
915
+ )
916
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
917
+ def __init__(self, config):
918
+ super().__init__(config)
919
+ self.num_labels = config.num_labels
920
+ self.model = LlamaModel(config)
921
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
922
+
923
+ # Initialize weights and apply final processing
924
+ self.post_init()
925
+
926
+ def get_input_embeddings(self):
927
+ return self.model.embed_tokens
928
+
929
+ def set_input_embeddings(self, value):
930
+ self.model.embed_tokens = value
931
+
932
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
933
+ def forward(
934
+ self,
935
+ input_ids: torch.LongTensor = None,
936
+ attention_mask: Optional[torch.Tensor] = None,
937
+ position_ids: Optional[torch.LongTensor] = None,
938
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
939
+ inputs_embeds: Optional[torch.FloatTensor] = None,
940
+ labels: Optional[torch.LongTensor] = None,
941
+ use_cache: Optional[bool] = None,
942
+ output_attentions: Optional[bool] = None,
943
+ output_hidden_states: Optional[bool] = None,
944
+ return_dict: Optional[bool] = None,
945
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
946
+ r"""
947
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
948
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
949
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
950
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
951
+ """
952
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
953
+
954
+ transformer_outputs = self.model(
955
+ input_ids,
956
+ attention_mask=attention_mask,
957
+ position_ids=position_ids,
958
+ past_key_values=past_key_values,
959
+ inputs_embeds=inputs_embeds,
960
+ use_cache=use_cache,
961
+ output_attentions=output_attentions,
962
+ output_hidden_states=output_hidden_states,
963
+ return_dict=return_dict,
964
+ )
965
+ hidden_states = transformer_outputs[0]
966
+ logits = self.score(hidden_states)
967
+
968
+ if input_ids is not None:
969
+ batch_size = input_ids.shape[0]
970
+ else:
971
+ batch_size = inputs_embeds.shape[0]
972
+
973
+ if self.config.pad_token_id is None and batch_size != 1:
974
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
975
+ if self.config.pad_token_id is None:
976
+ sequence_lengths = -1
977
+ else:
978
+ if input_ids is not None:
979
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
980
+ logits.device
981
+ )
982
+ else:
983
+ sequence_lengths = -1
984
+
985
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
986
+
987
+ loss = None
988
+ if labels is not None:
989
+ labels = labels.to(logits.device)
990
+ if self.config.problem_type is None:
991
+ if self.num_labels == 1:
992
+ self.config.problem_type = "regression"
993
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
994
+ self.config.problem_type = "single_label_classification"
995
+ else:
996
+ self.config.problem_type = "multi_label_classification"
997
+
998
+ if self.config.problem_type == "regression":
999
+ loss_fct = MSELoss()
1000
+ if self.num_labels == 1:
1001
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1002
+ else:
1003
+ loss = loss_fct(pooled_logits, labels)
1004
+ elif self.config.problem_type == "single_label_classification":
1005
+ loss_fct = CrossEntropyLoss()
1006
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1007
+ elif self.config.problem_type == "multi_label_classification":
1008
+ loss_fct = BCEWithLogitsLoss()
1009
+ loss = loss_fct(pooled_logits, labels)
1010
+ if not return_dict:
1011
+ output = (pooled_logits,) + transformer_outputs[1:]
1012
+ return ((loss,) + output) if loss is not None else output
1013
+
1014
+ return SequenceClassifierOutputWithPast(
1015
+ loss=loss,
1016
+ logits=pooled_logits,
1017
+ past_key_values=transformer_outputs.past_key_values,
1018
+ hidden_states=transformer_outputs.hidden_states,
1019
+ attentions=transformer_outputs.attentions,
1020
+ )
models/CodeLlama-7B-Python-GPTQ/quantize_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bits": 4,
3
+ "group_size": 128,
4
+ "damp_percent": 0.1,
5
+ "desc_act": false,
6
+ "sym": true,
7
+ "true_sequential": true,
8
+ "model_name_or_path": null,
9
+ "model_file_base_name": "model"
10
+ }