Cran-May matthoffner commited on
Commit
2f98890
0 Parent(s):

Duplicate from matthoffner/falcon-40b-instruct-ggml

Browse files

Co-authored-by: Matt Hoffner <matthoffner@users.noreply.huggingface.co>

Files changed (6) hide show
  1. .gitattributes +35 -0
  2. Dockerfile +66 -0
  3. README.md +15 -0
  4. api.py +79 -0
  5. demo.py +198 -0
  6. requirements.txt +11 -0
.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
Dockerfile ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:12.0.0-cudnn8-devel-ubuntu22.04
2
+
3
+ # Set environment variables
4
+ ENV PATH="/usr/local/cuda/bin:$PATH"
5
+ ENV MODEL_NAME="falcon-40b-instruct-GGML"
6
+ ENV MODEL_FILE="falcon40b-instruct.ggmlv3.q4_K_S.bin"
7
+ ENV MODEL_URL="https://huggingface.co/TheBloke/${MODEL_NAME}/raw/ggmlv3/${MODEL_FILE}"
8
+
9
+ RUN apt update && \
10
+ apt install --no-install-recommends -y build-essential python3 python3-pip wget curl git && \
11
+ apt clean && rm -rf /var/lib/apt/lists/*
12
+
13
+ # Set the working directory in the container to /app
14
+ WORKDIR /app
15
+
16
+ # Install cmake
17
+ RUN apt-get install -y wget && \
18
+ wget -qO- "https://cmake.org/files/v3.18/cmake-3.18.0-Linux-x86_64.tar.gz" | tar --strip-components=1 -xz -C /usr/local
19
+
20
+ # Copy the requirements.txt file into the container
21
+ COPY requirements.txt ./
22
+
23
+ # Install any needed packages specified in requirements.txt
24
+ RUN pip3 install --upgrade pip && \
25
+ pip3 install -r requirements.txt
26
+
27
+ # Clone ctransformers and update submodule ggllm.cpp
28
+ RUN git clone --recursive https://github.com/marella/ctransformers.git && \
29
+ cd ctransformers && \
30
+ git submodule update --init models/submodules/ggllm.cpp && \
31
+ cd models/submodules/ggllm.cpp && \
32
+ git checkout master && \
33
+ git pull
34
+
35
+ # Install ctransformers from source
36
+ RUN cd ctransformers && \
37
+ CT_CUBLAS=1 FORCE_CMAKE=1 pip install .
38
+
39
+ # Download the model file
40
+ # RUN wget -O /app/${MODEL_FILE} ${MODEL_URL}
41
+
42
+ # Create user
43
+ RUN useradd -m -u 1000 user
44
+
45
+ # Create a directory for app and move the downloaded file there
46
+ # RUN mkdir -p /home/user/app && mv /app/${MODEL_FILE} /home/user/app
47
+
48
+ # Change the ownership of the copied file to user
49
+ # RUN chown user:user /home/user/app/${MODEL_FILE}
50
+
51
+ USER user
52
+ ENV HOME=/home/user \
53
+ PATH=/home/user/.local/bin:$PATH
54
+
55
+ WORKDIR $HOME/app
56
+
57
+ # Now you can COPY the rest of your app
58
+ COPY --chown=user . .
59
+
60
+ RUN ls -al
61
+
62
+ # Make port available to the world outside this container
63
+ EXPOSE 7860
64
+
65
+ # Run uvicorn when the container launches
66
+ CMD ["python3", "demo.py", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: falcon-40b-ggml-cuda
3
+ emoji: 🦅
4
+ colorFrom: red
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 7860
9
+ duplicated_from: matthoffner/falcon-40b-instruct-ggml
10
+ ---
11
+
12
+ # falcon-40b-ggml-cuda
13
+
14
+ ## <a href="https://github.com/cmp-nct/ggllm.cpp" target="_blank">ggllm.cpp</a>
15
+ ## ctransformers
api.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fastapi
2
+ import json
3
+ import uvicorn
4
+ from fastapi import HTTPException
5
+ from fastapi.responses import HTMLResponse
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+ from sse_starlette.sse import EventSourceResponse
8
+ from starlette.responses import StreamingResponse
9
+ from ctransformers import AutoModelForCausalLM
10
+ from pydantic import BaseModel
11
+ from typing import List, Dict, Any, Generator
12
+
13
+ llm = AutoModelForCausalLM.from_pretrained("TheBloke/falcon-40b-instruct-GGML", model_file="falcon40b-instruct.ggmlv3.q2_K.bin",
14
+ model_type="falcon", threads=8)
15
+ app = fastapi.FastAPI(title="🦅Falcon 40B GGML (ggmlv3.q2_K)🦅")
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=["*"],
19
+ allow_credentials=True,
20
+ allow_methods=["*"],
21
+ allow_headers=["*"],
22
+ )
23
+
24
+ class ChatCompletionRequestV0(BaseModel):
25
+ prompt: str
26
+
27
+ class Message(BaseModel):
28
+ role: str
29
+ content: str
30
+
31
+ class ChatCompletionRequest(BaseModel):
32
+ messages: List[Message]
33
+ max_tokens: int = 250
34
+
35
+ @app.post("/v1/completions")
36
+ async def completion(request: ChatCompletionRequestV0, response_mode=None):
37
+ response = llm(request.prompt)
38
+ return response
39
+
40
+ @app.post("/v1/chat/completions")
41
+ async def chat(request: ChatCompletionRequest):
42
+ combined_messages = ' '.join([message.content for message in request.messages])
43
+ tokens = llm.tokenize(combined_messages)
44
+
45
+ try:
46
+ chat_chunks = llm.generate(tokens)
47
+ except Exception as e:
48
+ raise HTTPException(status_code=500, detail=str(e))
49
+
50
+ async def format_response(chat_chunks: Generator) -> Any:
51
+ for chat_chunk in chat_chunks:
52
+ response = {
53
+ 'choices': [
54
+ {
55
+ 'message': {
56
+ 'role': 'system',
57
+ 'content': llm.detokenize(chat_chunk)
58
+ },
59
+ 'finish_reason': 'stop' if llm.detokenize(chat_chunk) == "[DONE]" else 'unknown'
60
+ }
61
+ ]
62
+ }
63
+ yield f"data: {json.dumps(response)}\n\n"
64
+ yield "event: done\ndata: {}\n\n"
65
+
66
+ return StreamingResponse(format_response(chat_chunks), media_type="text/event-stream")
67
+
68
+ @app.post("/v0/chat/completions")
69
+ async def chat(request: ChatCompletionRequestV0, response_mode=None):
70
+ tokens = llm.tokenize(request.prompt)
71
+ async def server_sent_events(chat_chunks, llm):
72
+ for chat_chunk in llm.generate(chat_chunks):
73
+ yield dict(data=json.dumps(llm.detokenize(chat_chunk)))
74
+ yield dict(data="[DONE]")
75
+
76
+ return EventSourceResponse(server_sent_events(tokens, llm))
77
+
78
+ if __name__ == "__main__":
79
+ uvicorn.run(app, host="0.0.0.0", port=8000)
demo.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from ctransformers import AutoModelForCausalLM
3
+ import gradio as gr
4
+
5
+ llm = AutoModelForCausalLM.from_pretrained("TheBloke/falcon-40b-instruct-GGML", model_file="falcon-40b-instruct.ggccv1.q2_k.bin",
6
+ model_type="falcon", threads=8, gpu_layers=30)
7
+
8
+ TITLE = """<h2 align="center">🦅 falcon-40b-instruct.ggccv1.q2_k.bin 🦅"""
9
+ USER_NAME = "User"
10
+ BOT_NAME = "Falcon"
11
+ DEFAULT_INSTRUCTIONS = f"""The following is a conversation between a highly knowledgeable and intelligent AI assistant, called Falcon, and a human user, called User. In the following interactions, User and Falcon will converse in natural language, and Falcon will answer User's questions. Falcon was built to be respectful, polite and inclusive. Falcon was built by the Technology Innovation Institute in Abu Dhabi. Falcon will never decline to answer a question, and always attempts to give an answer that User would be satisfied with. It knows a lot, and always tells the truth. The conversation begins.
12
+ """
13
+ RETRY_COMMAND = "/retry"
14
+ STOP_STR = f"\n{USER_NAME}:"
15
+ STOP_SUSPECT_LIST = [":", "\n", "User"]
16
+
17
+
18
+ def chat_accordion():
19
+ with gr.Accordion("Parameters", open=False):
20
+ temperature = gr.Slider(
21
+ minimum=0.1,
22
+ maximum=2.0,
23
+ value=0.8,
24
+ step=0.1,
25
+ interactive=True,
26
+ label="Temperature",
27
+ )
28
+ top_p = gr.Slider(
29
+ minimum=0.1,
30
+ maximum=0.99,
31
+ value=0.9,
32
+ step=0.01,
33
+ interactive=True,
34
+ label="p (nucleus sampling)",
35
+ )
36
+ return temperature, top_p
37
+
38
+
39
+ def format_chat_prompt(message: str, chat_history, instructions: str) -> str:
40
+ instructions = instructions.strip(" ").strip("\n")
41
+ prompt = instructions
42
+ for turn in chat_history:
43
+ user_message, bot_message = turn
44
+ prompt = f"{prompt}\n{USER_NAME}: {user_message}\n{BOT_NAME}: {bot_message}"
45
+ prompt = f"{prompt}\n{USER_NAME}: {message}\n{BOT_NAME}:"
46
+ return prompt
47
+
48
+
49
+ def chat():
50
+ with gr.Column(elem_id="chat_container"):
51
+ with gr.Row():
52
+ chatbot = gr.Chatbot(elem_id="chatbot")
53
+ with gr.Row():
54
+ inputs = gr.Textbox(
55
+ placeholder=f"Hello {BOT_NAME} !!",
56
+ label="Type an input and press Enter",
57
+ max_lines=3,
58
+ )
59
+
60
+ with gr.Row(elem_id="button_container"):
61
+ with gr.Column():
62
+ retry_button = gr.Button("♻️ Retry last turn")
63
+ with gr.Column():
64
+ delete_turn_button = gr.Button("🧽 Delete last turn")
65
+ with gr.Column():
66
+ clear_chat_button = gr.Button("✨ Delete all history")
67
+
68
+ gr.Examples(
69
+ [
70
+ ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"],
71
+ ["What's the Everett interpretation of quantum mechanics?"],
72
+ ["Give me a list of the top 10 dive sites you would recommend around the world."],
73
+ ["Can you tell me more about deep-water soloing?"],
74
+ ["Can you write a short tweet about the Apache 2.0 release of our latest AI model, Falcon LLM?"],
75
+ ],
76
+ inputs=inputs,
77
+ label="Click on any example and press Enter in the input textbox!",
78
+ )
79
+
80
+ with gr.Row(elem_id="param_container"):
81
+ with gr.Column():
82
+ temperature, top_p = chat_accordion()
83
+ with gr.Column():
84
+ with gr.Accordion("Instructions", open=False):
85
+ instructions = gr.Textbox(
86
+ placeholder="LLM instructions",
87
+ value=DEFAULT_INSTRUCTIONS,
88
+ lines=10,
89
+ interactive=True,
90
+ label="Instructions",
91
+ max_lines=16,
92
+ show_label=False,
93
+ )
94
+
95
+ def run_chat(message: str, chat_history, instructions: str, temperature: float, top_p: float):
96
+ if not message or (message == RETRY_COMMAND and len(chat_history) == 0):
97
+ yield chat_history
98
+ return
99
+
100
+ if message == RETRY_COMMAND and chat_history:
101
+ prev_turn = chat_history.pop(-1)
102
+ user_message, _ = prev_turn
103
+ message = user_message
104
+
105
+ prompt = format_chat_prompt(message, chat_history, instructions)
106
+ chat_history = chat_history + [[message, ""]]
107
+ stream = llm(
108
+ prompt,
109
+ max_new_tokens=1024,
110
+ stop=[STOP_STR, "<|endoftext|>"],
111
+ temperature=temperature,
112
+ top_p=top_p,
113
+ stream=True
114
+ )
115
+ acc_text = ""
116
+ for idx, response in enumerate(stream):
117
+ text_token = response
118
+
119
+ if text_token in STOP_SUSPECT_LIST:
120
+ acc_text += text_token
121
+ continue
122
+
123
+ if idx == 0 and text_token.startswith(" "):
124
+ text_token = text_token[1:]
125
+
126
+ acc_text += text_token
127
+ last_turn = list(chat_history.pop(-1))
128
+ last_turn[-1] += acc_text
129
+ chat_history = chat_history + [last_turn]
130
+ yield chat_history
131
+ acc_text = ""
132
+
133
+ def delete_last_turn(chat_history):
134
+ if chat_history:
135
+ chat_history.pop(-1)
136
+ return {chatbot: gr.update(value=chat_history)}
137
+
138
+ def run_retry(message: str, chat_history, instructions: str, temperature: float, top_p: float):
139
+ yield from run_chat(RETRY_COMMAND, chat_history, instructions, temperature, top_p)
140
+
141
+ def clear_chat():
142
+ return []
143
+
144
+ inputs.submit(
145
+ run_chat,
146
+ [inputs, chatbot, instructions, temperature, top_p],
147
+ outputs=[chatbot],
148
+ show_progress=False,
149
+ )
150
+ inputs.submit(lambda: "", inputs=None, outputs=inputs)
151
+ delete_turn_button.click(delete_last_turn, inputs=[chatbot], outputs=[chatbot])
152
+ retry_button.click(
153
+ run_retry,
154
+ [inputs, chatbot, instructions, temperature, top_p],
155
+ outputs=[chatbot],
156
+ show_progress=False,
157
+ )
158
+ clear_chat_button.click(clear_chat, [], chatbot)
159
+
160
+
161
+ def get_demo():
162
+ with gr.Blocks(
163
+ # css=None
164
+ # css="""#chat_container {width: 700px; margin-left: auto; margin-right: auto;}
165
+ # #button_container {width: 700px; margin-left: auto; margin-right: auto;}
166
+ # #param_container {width: 700px; margin-left: auto; margin-right: auto;}"""
167
+ css="""#chatbot {
168
+ font-size: 14px;
169
+ min-height: 300px;
170
+ }"""
171
+ ) as demo:
172
+ gr.HTML(TITLE)
173
+
174
+ with gr.Row():
175
+ with gr.Column():
176
+ gr.Markdown(
177
+ """**Chat with [Falcon-40B-Instruct](https://huggingface.co/tiiuae/falcon-40b-instruct), brainstorm ideas, discuss your holiday plans, and more!**
178
+
179
+ ✨ This demo is powered by [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b), finetuned on the [Baize](https://github.com/project-baize/baize-chatbot) dataset, and running with [Text Generation Inference](https://github.com/huggingface/text-generation-inference). [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b) is a state-of-the-art large language model built by the [Technology Innovation Institute](https://www.tii.ae) in Abu Dhabi. It is trained on 1 trillion tokens (including [RefinedWeb](https://huggingface.co/datasets/tiiuae/falcon-refinedweb)) and available under the Apache 2.0 license. It currently holds the 🥇 1st place on the [🤗 Open LLM leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). This demo is made available by the [HuggingFace H4 team](https://huggingface.co/HuggingFaceH4).
180
+
181
+ 🧪 This is only a **first experimental preview**: the [H4 team](https://huggingface.co/HuggingFaceH4) intends to provide increasingly capable versions of Falcon Chat in the future, based on improved datasets and RLHF/RLAIF.
182
+
183
+ 👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/)
184
+
185
+ ➡️️ **Intended Use**: this demo is intended to showcase an early finetuning of [Falcon-40B](https://huggingface.co/tiiuae/falcon-40b), to illustrate the impact (and limitations) of finetuning on a dataset of conversations and instructions. We encourage the community to further build upon the base model, and to create even better instruct/chat versions!
186
+
187
+ ⚠️ **Limitations**: the model can and will produce factually incorrect information, hallucinating facts and actions. As it has not undergone any advanced tuning/alignment, it can produce problematic outputs, especially if prompted to do so. Finally, this demo is limited to a session length of about 1,000 words.
188
+ """
189
+ )
190
+
191
+ chat()
192
+
193
+ return demo
194
+
195
+ if __name__ == "__main__":
196
+ demo = get_demo()
197
+ demo.queue(max_size=64, concurrency_count=8)
198
+ demo.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ uvicorn
2
+ markdown
3
+ fastapi
4
+ loguru
5
+ torch
6
+ numpy
7
+ transformers
8
+ accelerate
9
+ langchain
10
+ sse_starlette
11
+ gradio