ionik matthoffner commited on
Commit
82373e1
·
0 Parent(s):

Duplicate from matthoffner/falcon-mini

Browse files

Co-authored-by: Matt Hoffner <[email protected]>

Files changed (7) hide show
  1. .gitattributes +35 -0
  2. Dockerfile +51 -0
  3. README.md +16 -0
  4. api.py +79 -0
  5. demo.py +192 -0
  6. falcon.png +0 -0
  7. 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,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:11.0.3-base-ubuntu20.04
2
+ RUN export PATH="/usr/local/cuda/bin:$PATH"
3
+ RUN apt update && \
4
+ apt install --no-install-recommends -y build-essential python3 python3-pip wget curl git && \
5
+ apt clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Set the working directory in the container to /app
8
+ WORKDIR /app
9
+
10
+ # Install cmake
11
+ RUN apt-get install -y wget && \
12
+ 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
13
+
14
+ # Copy the requirements.txt file into the container
15
+ COPY requirements.txt ./
16
+
17
+ # Install any needed packages specified in requirements.txt
18
+ RUN pip3 install --upgrade pip && \
19
+ pip3 install -r requirements.txt
20
+
21
+ RUN export PATH="/usr/local/cuda/bin:$PATH"
22
+ RUN pip install ctransformers --no-binary ctransformers
23
+ # Assume the specific file is hosted somewhere and is publicly accessible, replace the URL with the actual URL
24
+ #RUN wget -O falcon40b-instruct.ggmlv3.q2_K.bin https://huggingface.co/TheBloke/falcon-40b-instruct-GGML/raw/main/falcon40b-instruct.ggmlv3.q2_K.bin
25
+
26
+ # Change the ownership of the downloaded file to myuser
27
+
28
+
29
+ # Install git and clone the ggllm.cpp repository and build
30
+ #RUN apt-get install -y git && \
31
+ # git clone https://github.com/cmp-nct/ggllm.cpp && \
32
+ # cd ggllm.cpp && \
33
+ # rm -rf build && mkdir build && cd build && cmake -DGGML_CUBLAS=1 .. && cmake --build . --config Release
34
+
35
+ RUN useradd -m -u 1000 user
36
+ # RUN chown user:user falcon7b-instruct.ggmlv3.q4_0.bin
37
+ USER user
38
+ ENV HOME=/home/user \
39
+ PATH=/home/user/.local/bin:$PATH
40
+
41
+ WORKDIR $HOME/app
42
+
43
+ COPY --chown=user . $HOME/app
44
+
45
+ RUN ls -al
46
+
47
+ # Make port available to the world outside this container
48
+ EXPOSE 7860
49
+
50
+ # Run uvicorn when the container launches
51
+ CMD ["python3", "demo.py", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: falcon-mini
3
+ emoji: 🦅💸
4
+ colorFrom: red
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 7860
9
+ license: apache-2.0
10
+ duplicated_from: matthoffner/falcon-mini
11
+ ---
12
+
13
+ # falcon-7b-instruct
14
+
15
+ ## <a href="https://github.com/cmp-nct/ggllm.cpp" target="_blank">ggllm.cpp</a>
16
+ ## 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,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from ctransformers import AutoModelForCausalLM
3
+ import gradio as gr
4
+
5
+
6
+ llm = AutoModelForCausalLM.from_pretrained("TheBloke/falcon-7b-instruct-GGML", model_file="falcon-7b-instruct.ggccv1.q4_0.bin",
7
+ model_type="falcon", threads=8)
8
+
9
+ TITLE = """<h1 align="center">🦅 falcon ggccv1.q4_0 demo 🦅</h1>"""
10
+ USER_NAME = "User"
11
+ BOT_NAME = "Falcon"
12
+ 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.
13
+ """
14
+ RETRY_COMMAND = "/retry"
15
+ STOP_STR = f"\n{USER_NAME}:"
16
+ STOP_SUSPECT_LIST = [":", "\n", "User"]
17
+
18
+
19
+ def chat_accordion():
20
+ with gr.Accordion("Parameters", open=False):
21
+ temperature = gr.Slider(
22
+ minimum=0.1,
23
+ maximum=2.0,
24
+ value=0.8,
25
+ step=0.1,
26
+ interactive=True,
27
+ label="Temperature",
28
+ )
29
+ top_p = gr.Slider(
30
+ minimum=0.1,
31
+ maximum=0.99,
32
+ value=0.9,
33
+ step=0.01,
34
+ interactive=True,
35
+ label="p (nucleus sampling)",
36
+ )
37
+ return temperature, top_p
38
+
39
+
40
+ def format_chat_prompt(message: str, chat_history, instructions: str) -> str:
41
+ instructions = instructions.strip(" ").strip("\n")
42
+ prompt = instructions
43
+ for turn in chat_history:
44
+ user_message, bot_message = turn
45
+ prompt = f"{prompt}\n{USER_NAME}: {user_message}\n{BOT_NAME}: {bot_message}"
46
+ prompt = f"{prompt}\n{USER_NAME}: {message}\n{BOT_NAME}:"
47
+ return prompt
48
+
49
+
50
+ def chat():
51
+ with gr.Column(elem_id="chat_container"):
52
+ with gr.Row():
53
+ chatbot = gr.Chatbot(elem_id="chatbot")
54
+ with gr.Row():
55
+ inputs = gr.Textbox(
56
+ placeholder=f"Hello {BOT_NAME} !!",
57
+ label="Type an input and press Enter",
58
+ max_lines=3,
59
+ )
60
+
61
+ with gr.Row(elem_id="button_container"):
62
+ with gr.Column():
63
+ retry_button = gr.Button("♻️ Retry last turn")
64
+ with gr.Column():
65
+ delete_turn_button = gr.Button("🧽 Delete last turn")
66
+ with gr.Column():
67
+ clear_chat_button = gr.Button("✨ Delete all history")
68
+
69
+ gr.Examples(
70
+ [
71
+ ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"],
72
+ ["What's the Everett interpretation of quantum mechanics?"],
73
+ ["Give me a list of the top 10 dive sites you would recommend around the world."],
74
+ ["Can you tell me more about deep-water soloing?"],
75
+ ["Can you write a short tweet about the Apache 2.0 release of our latest AI model, Falcon LLM?"],
76
+ ],
77
+ inputs=inputs,
78
+ label="Click on any example and press Enter in the input textbox!",
79
+ )
80
+
81
+ with gr.Row(elem_id="param_container"):
82
+ with gr.Column():
83
+ temperature, top_p = chat_accordion()
84
+ with gr.Column():
85
+ with gr.Accordion("Instructions", open=False):
86
+ instructions = gr.Textbox(
87
+ placeholder="LLM instructions",
88
+ value=DEFAULT_INSTRUCTIONS,
89
+ lines=10,
90
+ interactive=True,
91
+ label="Instructions",
92
+ max_lines=16,
93
+ show_label=False,
94
+ )
95
+
96
+ def run_chat(message: str, chat_history, instructions: str, temperature: float, top_p: float):
97
+ if not message or (message == RETRY_COMMAND and len(chat_history) == 0):
98
+ yield chat_history
99
+ return
100
+
101
+ if message == RETRY_COMMAND and chat_history:
102
+ prev_turn = chat_history.pop(-1)
103
+ user_message, _ = prev_turn
104
+ message = user_message
105
+
106
+ prompt = format_chat_prompt(message, chat_history, instructions)
107
+ chat_history = chat_history + [[message, ""]]
108
+ stream = llm(
109
+ prompt,
110
+ max_new_tokens=1024,
111
+ stop=[STOP_STR, "<|endoftext|>", USER_NAME],
112
+ temperature=temperature,
113
+ top_p=top_p,
114
+ stream=True
115
+ )
116
+ acc_text = ""
117
+ for idx, response in enumerate(stream):
118
+ text_token = response
119
+
120
+ if text_token in STOP_SUSPECT_LIST:
121
+ acc_text += text_token
122
+ continue
123
+
124
+ if idx == 0 and text_token.startswith(" "):
125
+ text_token = text_token[1:]
126
+
127
+ acc_text += text_token
128
+ last_turn = list(chat_history.pop(-1))
129
+ last_turn[-1] += acc_text
130
+ chat_history = chat_history + [last_turn]
131
+ yield chat_history
132
+ acc_text = ""
133
+
134
+
135
+ def delete_last_turn(chat_history):
136
+ if chat_history:
137
+ chat_history.pop(-1)
138
+ return {chatbot: gr.update(value=chat_history)}
139
+
140
+ def run_retry(message: str, chat_history, instructions: str, temperature: float, top_p: float):
141
+ yield from run_chat(RETRY_COMMAND, chat_history, instructions, temperature, top_p)
142
+
143
+ def clear_chat():
144
+ return []
145
+
146
+ inputs.submit(
147
+ run_chat,
148
+ [inputs, chatbot, instructions, temperature, top_p],
149
+ outputs=[chatbot],
150
+ show_progress=False,
151
+ )
152
+ inputs.submit(lambda: "", inputs=None, outputs=inputs)
153
+ delete_turn_button.click(delete_last_turn, inputs=[chatbot], outputs=[chatbot])
154
+ retry_button.click(
155
+ run_retry,
156
+ [inputs, chatbot, instructions, temperature, top_p],
157
+ outputs=[chatbot],
158
+ show_progress=False,
159
+ )
160
+ clear_chat_button.click(clear_chat, [], chatbot)
161
+
162
+
163
+ def get_demo():
164
+ with gr.Blocks(
165
+ # css=None
166
+ # css="""#chat_container {width: 700px; margin-left: auto; margin-right: auto;}
167
+ # #button_container {width: 700px; margin-left: auto; margin-right: auto;}
168
+ # #param_container {width: 700px; margin-left: auto; margin-right: auto;}"""
169
+ css="""#chatbot {
170
+ font-size: 14px;
171
+ min-height: 300px;
172
+ }"""
173
+ ) as demo:
174
+ gr.HTML(TITLE)
175
+
176
+ with gr.Row():
177
+ with gr.Column():
178
+ gr.Markdown(
179
+ """**Chat with [Falcon-7B-Instruct](https://huggingface.co/tiiuae/falcon-7b-instruct), brainstorm ideas, discuss your holiday plans, and more!**
180
+
181
+ 🧪 This uses a quantized [ggml](https://github.com/ggerganov/ggml) optimized for CPU. Special thanks to [ggllm.cpp](https://github.com/cmp-nct/ggllm.cpp), [ctransformers](https://github.com/marella/ctransformers), and [TheBloke](https://huggingface.co/TheBloke).
182
+ """
183
+ )
184
+
185
+ chat()
186
+
187
+ return demo
188
+
189
+ if __name__ == "__main__":
190
+ demo = get_demo()
191
+ demo.queue(max_size=128, concurrency_count=8)
192
+ demo.launch(server_name="0.0.0.0", server_port=7860)
falcon.png ADDED
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