lewtun HF staff commited on
Commit
cd59634
1 Parent(s): 6c76ef9
Files changed (2) hide show
  1. .gitignore +160 -0
  2. app.py +215 -0
.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
app.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import gradio as gr
5
+ from text_generation import Client
6
+
7
+ TITLE = """<h2 align="center">🚀 Falcon-Chat demo</h2>"""
8
+ USER_NAME = "User"
9
+ BOT_NAME = "Falcon"
10
+ 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.
11
+ """
12
+ RETRY_COMMAND = "/retry"
13
+ STOP_STR = f"\n{USER_NAME}:"
14
+ STOP_SUSPECT_LIST = [":", "\n", "User"]
15
+
16
+ INFERENCE_ENDPOINT = os.environ.get("INFERENCE_ENDPOINT")
17
+ INFERENCE_AUTH = os.environ.get("INFERENCE_AUTH")
18
+
19
+
20
+ def chat_accordion():
21
+ with gr.Accordion("Parameters", open=False):
22
+ temperature = gr.Slider(
23
+ minimum=0.1,
24
+ maximum=2.0,
25
+ value=0.8,
26
+ step=0.1,
27
+ interactive=True,
28
+ label="Temperature",
29
+ )
30
+ top_p = gr.Slider(
31
+ minimum=0.1,
32
+ maximum=0.99,
33
+ value=0.9,
34
+ step=0.01,
35
+ interactive=True,
36
+ label="p (nucleus sampling)",
37
+ )
38
+ return temperature, top_p
39
+
40
+
41
+ def format_chat_prompt(message: str, chat_history, instructions: str) -> str:
42
+ instructions = instructions.strip(" ").strip("\n")
43
+ prompt = instructions
44
+ for turn in chat_history:
45
+ user_message, bot_message = turn
46
+ prompt = f"{prompt}\n{USER_NAME}: {user_message}\n{BOT_NAME}: {bot_message}"
47
+ prompt = f"{prompt}\n{USER_NAME}: {message}\n{BOT_NAME}:"
48
+ return prompt
49
+
50
+
51
+ def chat(client: Client):
52
+ with gr.Column(elem_id="chat_container"):
53
+ with gr.Row():
54
+ chatbot = gr.Chatbot(elem_id="chatbot")
55
+ with gr.Row():
56
+ inputs = gr.Textbox(
57
+ placeholder=f"Hello {BOT_NAME} !!",
58
+ label="Type an input and press Enter",
59
+ max_lines=3,
60
+ )
61
+
62
+ with gr.Row(elem_id="button_container"):
63
+ with gr.Column():
64
+ retry_button = gr.Button("♻️ Retry last turn")
65
+ with gr.Column():
66
+ delete_turn_button = gr.Button("🧽 Delete last turn")
67
+ with gr.Column():
68
+ clear_chat_button = gr.Button("✨ Delete all history")
69
+
70
+ gr.Examples(
71
+ [
72
+ ["Hey Falcon! Any recommendations for my holidays in Abu Dhabi?"],
73
+ ["What's the Everett interpretation of quantum mechanics?"],
74
+ ["Give me a list of the top 10 dive sites you would recommend around the world."],
75
+ ["Can you tell me more about deep-water soloing?"],
76
+ ["Can you write a short tweet about the Apache 2.0 release of our latest AI model, Falcon LLM?"],
77
+ ],
78
+ inputs=inputs,
79
+ label="Click on any example and press Enter in the input textbox!",
80
+ )
81
+
82
+ with gr.Row(elem_id="param_container"):
83
+ with gr.Column():
84
+ temperature, top_p = chat_accordion()
85
+ with gr.Column():
86
+ with gr.Accordion("Instructions", open=False):
87
+ instructions = gr.Textbox(
88
+ placeholder="LLM instructions",
89
+ value=DEFAULT_INSTRUCTIONS,
90
+ lines=10,
91
+ interactive=True,
92
+ label="Instructions",
93
+ max_lines=16,
94
+ show_label=False,
95
+ )
96
+
97
+ def run_chat(message: str, chat_history, instructions: str, temperature: float, top_p: float):
98
+ if not message or (message == RETRY_COMMAND and len(chat_history) == 0):
99
+ yield chat_history
100
+ return
101
+
102
+ if message == RETRY_COMMAND and chat_history:
103
+ prev_turn = chat_history.pop(-1)
104
+ user_message, _ = prev_turn
105
+ message = user_message
106
+
107
+ prompt = format_chat_prompt(message, chat_history, instructions)
108
+ chat_history = chat_history + [[message, ""]]
109
+ stream = client.generate_stream(
110
+ prompt,
111
+ do_sample=True,
112
+ max_new_tokens=1024,
113
+ stop_sequences=[STOP_STR, "<|endoftext|>"],
114
+ temperature=temperature,
115
+ top_p=top_p,
116
+ )
117
+ acc_text = ""
118
+ for idx, response in enumerate(stream):
119
+ text_token = response.token.text
120
+
121
+ if response.details:
122
+ return
123
+
124
+ if text_token in STOP_SUSPECT_LIST:
125
+ acc_text += text_token
126
+ continue
127
+
128
+ if idx == 0 and text_token.startswith(" "):
129
+ text_token = text_token[1:]
130
+
131
+ acc_text += text_token
132
+ last_turn = list(chat_history.pop(-1))
133
+ last_turn[-1] += acc_text
134
+ chat_history = chat_history + [last_turn]
135
+ yield chat_history
136
+ acc_text = ""
137
+
138
+ def delete_last_turn(chat_history):
139
+ if chat_history:
140
+ chat_history.pop(-1)
141
+ return {chatbot: gr.update(value=chat_history)}
142
+
143
+ def run_retry(message: str, chat_history, instructions: str, temperature: float, top_p: float):
144
+ yield from run_chat(RETRY_COMMAND, chat_history, instructions, temperature, top_p)
145
+
146
+ def clear_chat():
147
+ return []
148
+
149
+ inputs.submit(
150
+ run_chat,
151
+ [inputs, chatbot, instructions, temperature, top_p],
152
+ outputs=[chatbot],
153
+ show_progress=False,
154
+ )
155
+ inputs.submit(lambda: "", inputs=None, outputs=inputs)
156
+ delete_turn_button.click(delete_last_turn, inputs=[chatbot], outputs=[chatbot])
157
+ retry_button.click(
158
+ run_retry,
159
+ [inputs, chatbot, instructions, temperature, top_p],
160
+ outputs=[chatbot],
161
+ show_progress=False,
162
+ )
163
+ clear_chat_button.click(clear_chat, [], chatbot)
164
+
165
+
166
+ def get_demo(client: Client):
167
+ with gr.Blocks(
168
+ # css=None
169
+ # css="""#chat_container {width: 700px; margin-left: auto; margin-right: auto;}
170
+ # #button_container {width: 700px; margin-left: auto; margin-right: auto;}
171
+ # #param_container {width: 700px; margin-left: auto; margin-right: auto;}"""
172
+ css="""#chatbot {
173
+ font-size: 14px;
174
+ min-height: 300px;
175
+ }"""
176
+ ) as demo:
177
+ gr.HTML(TITLE)
178
+
179
+ with gr.Row():
180
+ # with gr.Column():
181
+ # gr.Image("home-banner.jpg", elem_id="banner-image", show_label=False)
182
+ with gr.Column():
183
+ gr.Markdown(
184
+ """**Chat with [Falcon-40B-Instruct](https://huggingface.co/tiiuae/falcon-40b-instruct), brainstorm ideas, discuss your holiday plans, and more!**
185
+
186
+ ✨ 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. [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).
187
+
188
+ 🧪 This is only a **first experimental preview**: we intend to provide increasingly capable versions of Falcon Chat in the future, based on improved datasets and RLHF/RLAIF.
189
+
190
+ 👀 **Learn more about Falcon LLM:** [falconllm.tii.ae](https://falconllm.tii.ae/)
191
+
192
+ ➡️️ **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!
193
+
194
+ ⚠️ **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.
195
+ """
196
+ )
197
+
198
+ chat(client)
199
+
200
+ return demo
201
+
202
+
203
+ if __name__ == "__main__":
204
+ parser = argparse.ArgumentParser("Playground Demo")
205
+ parser.add_argument(
206
+ "--addr",
207
+ type=str,
208
+ required=False,
209
+ default=INFERENCE_ENDPOINT,
210
+ )
211
+ args = parser.parse_args()
212
+ client = Client(args.addr, headers={"Authorization": f"Basic {INFERENCE_AUTH}"})
213
+ demo = get_demo(client)
214
+ demo.queue(max_size=128, concurrency_count=16)
215
+ demo.launch()