slim.frikha commited on
Commit
cb3354e
·
0 Parent(s):
Files changed (12) hide show
  1. .gitattributes +36 -0
  2. .gitignore +175 -0
  3. README.md +15 -0
  4. app.py +795 -0
  5. config.py +147 -0
  6. interface/logo.py +12 -0
  7. interface/settings.py +79 -0
  8. logs/.keepfile +0 -0
  9. photos/falcon_logo.png +3 -0
  10. photos/tii_logo.png +3 -0
  11. requirements.txt +3 -0
  12. test.py +93 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+ .vscode
170
+
171
+ # Ruff stuff:
172
+ .ruff_cache/
173
+
174
+ # PyPI configuration file
175
+ .pypirc
README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Falcon H1R Playground
3
+ emoji: 🚀
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.27.0
8
+ app_file: app.py
9
+ pinned: false
10
+ short_description: This a chat demo with Falcon-H1R reasoning models.
11
+ hf_oauth: true
12
+ ---
13
+
14
+
15
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import time
4
+ import uuid
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+
8
+ import gradio as gr
9
+ import modelscope_studio.components.antd as antd
10
+ import modelscope_studio.components.antdx as antdx
11
+ import modelscope_studio.components.base as ms
12
+ import modelscope_studio.components.pro as pro
13
+ from huggingface_hub import CommitScheduler
14
+ from openai import OpenAI
15
+
16
+ from config import (
17
+ CHAR_YIELD_SIZE,
18
+ DEFAULT_LOCALE,
19
+ DEFAULT_SETTINGS,
20
+ DEFAULT_THEME,
21
+ KEPT_TURNS,
22
+ MODEL_OPTIONS_MAP,
23
+ bot_config,
24
+ save_history,
25
+ user_config,
26
+ welcome_config,
27
+ )
28
+ from interface.logo import Logo
29
+ from interface.settings import SettingsMenu
30
+
31
+ logs_id = os.getenv("LOGS_ID")
32
+ logs_token = os.getenv("HF_LOGS_TOKEN")
33
+
34
+ logs_file = Path("logs/") / f"data_{uuid.uuid4()}.json"
35
+ logs_folder = logs_file.parent
36
+
37
+ scheduler = CommitScheduler(
38
+ repo_id=logs_id,
39
+ repo_type="dataset",
40
+ folder_path=logs_folder,
41
+ path_in_repo="data",
42
+ every=5,
43
+ token=logs_token,
44
+ private=True,
45
+ )
46
+
47
+
48
+ def format_history(history):
49
+ messages = []
50
+ for item in history:
51
+ if item["role"] == "user":
52
+ messages.append({"role": "user", "content": item["content"]})
53
+ elif item["role"] == "assistant":
54
+ contents = [
55
+ {"type": "text", "text": content["content"]}
56
+ for content in item["content"]
57
+ if content["type"] == "text"
58
+ ]
59
+ messages.append(
60
+ {
61
+ "role": "assistant",
62
+ "content": contents[0]["text"] if len(contents) > 0 else "",
63
+ }
64
+ )
65
+ return messages
66
+
67
+
68
+ class Gradio_Events:
69
+ @staticmethod
70
+ def submit(
71
+ state_value,
72
+ request: gr.Request,
73
+ profile: gr.OAuthProfile | None,
74
+ ):
75
+ settings = state_value["conversation_contexts"][state_value["conversation_id"]][
76
+ "settings"
77
+ ]
78
+
79
+ model = settings.get("model")
80
+ api_key_env = MODEL_OPTIONS_MAP.get(model).get("api_key_env")
81
+ base_url_env = MODEL_OPTIONS_MAP.get(model).get("base_url_env")
82
+ api_key_value = os.getenv(api_key_env)
83
+ base_url_value = os.getenv(base_url_env)
84
+
85
+ client = OpenAI(api_key=api_key_value, base_url=base_url_value)
86
+
87
+ history = state_value["conversation_contexts"][state_value["conversation_id"]][
88
+ "history"
89
+ ]
90
+ messages = format_history(history)
91
+
92
+ history.append(
93
+ {
94
+ "role": "assistant",
95
+ "content": [],
96
+ "key": str(uuid.uuid4()),
97
+ "header": MODEL_OPTIONS_MAP.get(model, {}).get("label", None),
98
+ "loading": True,
99
+ "status": "pending",
100
+ }
101
+ )
102
+
103
+ yield {
104
+ chatbot: gr.update(value=history),
105
+ state: gr.update(value=state_value),
106
+ }
107
+
108
+ try:
109
+ kept_messages = messages[:2] + messages[-(2 * (KEPT_TURNS - 1) + 1) :]
110
+ response = client.chat.completions.create(
111
+ model=model,
112
+ messages=kept_messages,
113
+ temperature=settings.get("temperature"),
114
+ top_p=settings.get("top_p"),
115
+ max_tokens=settings.get("max_new_tokens"),
116
+ stream=True,
117
+ )
118
+ start_time = time.time()
119
+ thought_cost_time = 0
120
+ reasoning_content = ""
121
+ answer_content = ""
122
+ is_thinking = False
123
+ is_answering = False
124
+ contents = [None, None]
125
+ last_yielded_length = 0
126
+ for chunk in response:
127
+ if not getattr(
128
+ getattr(chunk.choices[0], "message", None), "content", None
129
+ ) and not not getattr(
130
+ getattr(chunk.choices[0], "message", None),
131
+ "reasoning_content",
132
+ None,
133
+ ):
134
+ pass
135
+
136
+ else:
137
+ delta = chunk.choices[0].delta
138
+ if hasattr(delta, "reasoning_content") and delta.reasoning_content:
139
+ if not is_thinking:
140
+ contents[0] = {
141
+ "type": "tool",
142
+ "content": "",
143
+ "options": {
144
+ "title": "Let me think...",
145
+ "status": "pending",
146
+ },
147
+ "copyable": False,
148
+ "editable": False,
149
+ }
150
+ is_thinking = True
151
+ reasoning_content += delta.reasoning_content
152
+ if hasattr(delta, "content") and delta.content:
153
+ if not is_answering:
154
+ thought_cost_time = "{:.2f}".format(
155
+ time.time() - start_time
156
+ )
157
+ if contents[0]:
158
+ contents[0]["options"]["title"] = (
159
+ f"Inner reflections ({thought_cost_time}s)"
160
+ )
161
+ contents[0]["options"]["status"] = "done"
162
+ contents[1] = {
163
+ "type": "text",
164
+ "content": "",
165
+ }
166
+ is_answering = True
167
+ answer_content += delta.content
168
+ if contents[0]:
169
+ contents[0]["content"] = reasoning_content
170
+ if contents[1]:
171
+ contents[1]["content"] = answer_content
172
+ current_length = len(reasoning_content) + len(answer_content)
173
+ if current_length - last_yielded_length >= CHAR_YIELD_SIZE:
174
+ last_yielded_length = current_length
175
+ history[-1]["content"] = [
176
+ content for content in contents if content
177
+ ]
178
+ history[-1]["loading"] = False
179
+ yield {
180
+ chatbot: gr.update(value=history),
181
+ }
182
+ history[-1]["content"] = [content for content in contents if content]
183
+ history[-1]["loading"] = False
184
+ history[-1]["status"] = "done"
185
+ cost_time = "{:.2f}".format(time.time() - start_time)
186
+ history[-1]["footer"] = f"{cost_time}s"
187
+ yield {
188
+ chatbot: gr.update(value=history),
189
+ state: gr.update(value=state_value),
190
+ }
191
+ with scheduler.lock:
192
+ with logs_file.open("a") as f:
193
+ f.write(
194
+ json.dumps(
195
+ {
196
+ "request_id": str(uuid.uuid4()),
197
+ "input": messages,
198
+ "reasoning_content": reasoning_content,
199
+ "output": answer_content,
200
+ "turn": len(messages),
201
+ "model": model,
202
+ "temperature": settings.get("temperature"),
203
+ "top_p": settings.get("top_p"),
204
+ "max_tokens": settings.get("max_new_tokens"),
205
+ "latency": cost_time,
206
+ "reasoning_latency": thought_cost_time
207
+ if thought_cost_time
208
+ else cost_time,
209
+ "timestamp": datetime.now(timezone.utc).isoformat(),
210
+ "hf_username": profile.username if profile else None,
211
+ "session_hash": request.session_hash,
212
+ "client_ip": request.client.host,
213
+ "user_agent": request.headers.get("user-agent"),
214
+ "referer": request.headers.get("referer"),
215
+ "accept_language": request.headers.get(
216
+ "accept-language"
217
+ ),
218
+ }
219
+ )
220
+ )
221
+ f.write("\n")
222
+ except Exception as e:
223
+ print("model: ", model, "-", "Error: ", e)
224
+ history[-1]["loading"] = False
225
+ history[-1]["status"] = "done"
226
+ history[-1]["content"] += [
227
+ {
228
+ "type": "text",
229
+ "content": f'<span style="color: var(--color-red-500)">{str(e)}</span>',
230
+ }
231
+ ]
232
+ yield {
233
+ chatbot: gr.update(value=history),
234
+ state: gr.update(value=state_value),
235
+ }
236
+ raise e
237
+
238
+ @staticmethod
239
+ def add_message(
240
+ input_value,
241
+ settings_form_value,
242
+ state_value,
243
+ request: gr.Request,
244
+ profile: gr.OAuthProfile | None,
245
+ ):
246
+ if not state_value["conversation_id"]:
247
+ random_id = str(uuid.uuid4())
248
+ history = []
249
+ state_value["conversation_id"] = random_id
250
+ state_value["conversation_contexts"][state_value["conversation_id"]] = {
251
+ "history": history
252
+ }
253
+ state_value["conversations"].append(
254
+ {"label": input_value, "key": random_id}
255
+ )
256
+
257
+ history = state_value["conversation_contexts"][state_value["conversation_id"]][
258
+ "history"
259
+ ]
260
+
261
+ state_value["conversation_contexts"][state_value["conversation_id"]] = {
262
+ "history": history,
263
+ "settings": settings_form_value,
264
+ }
265
+ history.append(
266
+ {"role": "user", "content": input_value, "key": str(uuid.uuid4())}
267
+ )
268
+ yield Gradio_Events.preprocess_submit(clear_input=True)(state_value)
269
+
270
+ try:
271
+ for chunk in Gradio_Events.submit(state_value, request, profile):
272
+ yield chunk
273
+ except Exception as e:
274
+ raise e
275
+ finally:
276
+ yield Gradio_Events.postprocess_submit(state_value)
277
+
278
+ @staticmethod
279
+ def preprocess_submit(clear_input=True):
280
+ def preprocess_submit_handler(state_value):
281
+ history = state_value["conversation_contexts"][
282
+ state_value["conversation_id"]
283
+ ]["history"]
284
+ return {
285
+ **(
286
+ {
287
+ input: gr.update(value=None, loading=True)
288
+ if clear_input
289
+ else gr.update(loading=True),
290
+ }
291
+ if clear_input
292
+ else {}
293
+ ),
294
+ conversations: gr.update(
295
+ active_key=state_value["conversation_id"],
296
+ items=list(
297
+ map(
298
+ lambda item: {
299
+ **item,
300
+ "disabled": True
301
+ if item["key"] != state_value["conversation_id"]
302
+ else False,
303
+ },
304
+ state_value["conversations"],
305
+ )
306
+ ),
307
+ ),
308
+ add_conversation_btn: gr.update(disabled=True),
309
+ clear_btn: gr.update(disabled=True),
310
+ conversation_delete_menu_item: gr.update(disabled=True),
311
+ chatbot: gr.update(
312
+ value=history,
313
+ bot_config=bot_config(disabled_actions=["edit", "retry", "delete"]),
314
+ user_config=user_config(disabled_actions=["edit", "delete"]),
315
+ ),
316
+ state: gr.update(value=state_value),
317
+ }
318
+
319
+ return preprocess_submit_handler
320
+
321
+ @staticmethod
322
+ def postprocess_submit(state_value):
323
+ history = state_value["conversation_contexts"][state_value["conversation_id"]][
324
+ "history"
325
+ ]
326
+ return {
327
+ input: gr.update(loading=False),
328
+ conversation_delete_menu_item: gr.update(disabled=False),
329
+ clear_btn: gr.update(disabled=False),
330
+ conversations: gr.update(items=state_value["conversations"]),
331
+ add_conversation_btn: gr.update(disabled=False),
332
+ chatbot: gr.update(
333
+ value=history, bot_config=bot_config(), user_config=user_config()
334
+ ),
335
+ state: gr.update(value=state_value),
336
+ }
337
+
338
+ @staticmethod
339
+ def cancel(state_value):
340
+ history = state_value["conversation_contexts"][state_value["conversation_id"]][
341
+ "history"
342
+ ]
343
+ history[-1]["loading"] = False
344
+ history[-1]["status"] = "done"
345
+ history[-1]["footer"] = "Chat completion paused"
346
+ return Gradio_Events.postprocess_submit(state_value)
347
+
348
+ @staticmethod
349
+ def delete_message(state_value, e: gr.EventData):
350
+ index = e._data["payload"][0]["index"]
351
+ history = state_value["conversation_contexts"][state_value["conversation_id"]][
352
+ "history"
353
+ ]
354
+ history = history[:index] + history[index + 1 :]
355
+
356
+ state_value["conversation_contexts"][state_value["conversation_id"]][
357
+ "history"
358
+ ] = history
359
+
360
+ return gr.update(value=state_value)
361
+
362
+ @staticmethod
363
+ def edit_message(state_value, chatbot_value, e: gr.EventData):
364
+ index = e._data["payload"][0]["index"]
365
+ history = state_value["conversation_contexts"][state_value["conversation_id"]][
366
+ "history"
367
+ ]
368
+ history[index]["content"] = chatbot_value[index]["content"]
369
+ return gr.update(value=state_value)
370
+
371
+ @staticmethod
372
+ def regenerate_message(
373
+ settings_form_value,
374
+ state_value,
375
+ e: gr.EventData,
376
+ request: gr.Request,
377
+ profile: gr.OAuthProfile | None,
378
+ ):
379
+ index = e._data["payload"][0]["index"]
380
+ history = state_value["conversation_contexts"][state_value["conversation_id"]][
381
+ "history"
382
+ ]
383
+ history = history[:index]
384
+
385
+ state_value["conversation_contexts"][state_value["conversation_id"]] = {
386
+ "history": history,
387
+ "settings": settings_form_value,
388
+ }
389
+
390
+ yield Gradio_Events.preprocess_submit()(state_value)
391
+ try:
392
+ for chunk in Gradio_Events.submit(state_value, request, profile):
393
+ yield chunk
394
+ except Exception as e:
395
+ raise e
396
+ finally:
397
+ yield Gradio_Events.postprocess_submit(state_value)
398
+
399
+ @staticmethod
400
+ def select_suggestion(input_value, e: gr.EventData):
401
+ input_value = input_value[:-1] + e._data["payload"][0]
402
+ return gr.update(value=input_value)
403
+
404
+ @staticmethod
405
+ def apply_prompt(e: gr.EventData):
406
+ return gr.update(value=e._data["payload"][0]["value"]["description"])
407
+
408
+ @staticmethod
409
+ def new_chat(state_value):
410
+ if not state_value["conversation_id"]:
411
+ return gr.skip()
412
+ state_value["conversation_id"] = ""
413
+ return (
414
+ gr.update(active_key=state_value["conversation_id"]),
415
+ gr.update(value=None),
416
+ gr.update(value=DEFAULT_SETTINGS),
417
+ gr.update(value=state_value),
418
+ )
419
+
420
+ @staticmethod
421
+ def select_conversation(state_value, e: gr.EventData):
422
+ active_key = e._data["payload"][0]
423
+ if state_value["conversation_id"] == active_key or (
424
+ active_key not in state_value["conversation_contexts"]
425
+ ):
426
+ return gr.skip()
427
+ state_value["conversation_id"] = active_key
428
+ return (
429
+ gr.update(active_key=active_key),
430
+ gr.update(
431
+ value=state_value["conversation_contexts"][active_key]["history"]
432
+ ),
433
+ gr.update(
434
+ value=state_value["conversation_contexts"][active_key]["settings"]
435
+ ),
436
+ gr.update(value=state_value),
437
+ )
438
+
439
+ @staticmethod
440
+ def click_conversation_menu(state_value, e: gr.EventData):
441
+ conversation_id = e._data["payload"][0]["key"]
442
+ operation = e._data["payload"][1]["key"]
443
+ if operation == "delete":
444
+ del state_value["conversation_contexts"][conversation_id]
445
+
446
+ state_value["conversations"] = [
447
+ item
448
+ for item in state_value["conversations"]
449
+ if item["key"] != conversation_id
450
+ ]
451
+
452
+ if state_value["conversation_id"] == conversation_id:
453
+ state_value["conversation_id"] = ""
454
+ return (
455
+ gr.update(
456
+ items=state_value["conversations"],
457
+ active_key=state_value["conversation_id"],
458
+ ),
459
+ gr.update(value=None),
460
+ gr.update(value=state_value),
461
+ )
462
+ else:
463
+ return (
464
+ gr.update(items=state_value["conversations"]),
465
+ gr.skip(),
466
+ gr.update(value=state_value),
467
+ )
468
+ return gr.skip()
469
+
470
+ @staticmethod
471
+ def toggle_settings_header(settings_header_state_value):
472
+ settings_header_state_value["open"] = not settings_header_state_value["open"]
473
+ return gr.update(value=settings_header_state_value)
474
+
475
+ @staticmethod
476
+ def clear_conversation_history(state_value):
477
+ if not state_value["conversation_id"]:
478
+ return gr.skip()
479
+ state_value["conversation_contexts"][state_value["conversation_id"]][
480
+ "history"
481
+ ] = []
482
+ return gr.update(value=None), gr.update(value=state_value)
483
+
484
+ @staticmethod
485
+ def update_browser_state(state_value):
486
+ return gr.update(
487
+ value=dict(
488
+ conversations=state_value["conversations"],
489
+ conversation_contexts=state_value["conversation_contexts"],
490
+ )
491
+ )
492
+
493
+ @staticmethod
494
+ def apply_browser_state(browser_state_value, state_value):
495
+ state_value["conversations"] = browser_state_value["conversations"]
496
+ state_value["conversation_contexts"] = browser_state_value[
497
+ "conversation_contexts"
498
+ ]
499
+ return gr.update(items=browser_state_value["conversations"]), gr.update(
500
+ value=state_value
501
+ )
502
+
503
+
504
+ css = """
505
+ .gradio-container {
506
+ padding: 0 !important;
507
+ }
508
+
509
+ .gradio-container > main.fillable {
510
+ padding: 0 !important;
511
+ }
512
+
513
+ #chatbot {
514
+ height: calc(100vh - 21px - 16px);
515
+ max-height: 1500px;
516
+ }
517
+
518
+ #chatbot .chatbot-conversations {
519
+ height: 100vh;
520
+ background-color: var(--ms-gr-ant-color-bg-layout);
521
+ padding-left: 4px;
522
+ padding-right: 4px;
523
+ }
524
+
525
+ #chatbot .chatbot-conversations .chatbot-conversations-list {
526
+ padding-left: 0;
527
+ padding-right: 0;
528
+ }
529
+
530
+ /* NEW: Right sidebar styles */
531
+ #chatbot .chatbot-settings-sidebar {
532
+ height: 100vh;
533
+ background-color: var(--ms-gr-ant-color-bg-layout);
534
+ overflow-y: auto;
535
+ }
536
+
537
+ #chatbot .chatbot-settings-sidebar .ant-card {
538
+ height: 100%;
539
+ }
540
+
541
+ #chatbot .chatbot-chat {
542
+ padding: 32px;
543
+ padding-bottom: 0;
544
+ height: 100%;
545
+ }
546
+
547
+ @media (max-width: 768px) {
548
+ #chatbot .chatbot-chat {
549
+ padding: 0;
550
+ }
551
+ }
552
+
553
+ #chatbot .chatbot-chat .chatbot-chat-messages {
554
+ flex: 1;
555
+ }
556
+
557
+ #chatbot .setting-form-temperature .ms-gr-ant-form-item-control-input-content {
558
+ display: flex;
559
+ flex-wrap: wrap;
560
+ }
561
+
562
+ #chatbot .setting-form-max-new-tokens .ms-gr-ant-form-item-control-input-content {
563
+ display: flex;
564
+ flex-wrap: wrap;
565
+ }
566
+
567
+ #chatbot .setting-form-top-p .ms-gr-ant-form-item-control-input-content {
568
+ display: flex;
569
+ flex-wrap: wrap;
570
+ }
571
+
572
+ #chatbot .chatbot-settings-sidebar.hidden {
573
+ display: none;
574
+ }
575
+ """
576
+
577
+ model_options_map_json = json.dumps(MODEL_OPTIONS_MAP)
578
+ js = "function init() { window.MODEL_OPTIONS_MAP=" + model_options_map_json + "}"
579
+
580
+ with gr.Blocks(css=css, js=js, fill_width=True) as demo:
581
+ state = gr.State(
582
+ {
583
+ "conversation_contexts": {},
584
+ "conversations": [],
585
+ "conversation_id": "",
586
+ }
587
+ )
588
+
589
+ with (
590
+ ms.Application(),
591
+ antdx.XProvider(theme=DEFAULT_THEME, locale=DEFAULT_LOCALE),
592
+ ms.AutoLoading(),
593
+ ):
594
+ with antd.Row(gutter=[20, 20], wrap=False, elem_id="chatbot"):
595
+ # Left Column
596
+ with antd.Col(
597
+ md=dict(flex="0 0 260px", span=24, order=0),
598
+ span=0,
599
+ elem_style=dict(width=0),
600
+ order=1,
601
+ ):
602
+ with ms.Div(elem_classes="chatbot-conversations"):
603
+ with antd.Flex(
604
+ vertical=True,
605
+ gap="small",
606
+ elem_style=dict(
607
+ height="100%",
608
+ # backgroundImage="linear-gradient(137deg, #e5f4ff 40%, #6400FF 120%)",
609
+ ),
610
+ ):
611
+ # Logo
612
+ Logo()
613
+
614
+ # New Conversation Button
615
+ with (
616
+ antd.Button(
617
+ value=None,
618
+ color="primary",
619
+ variant="solid", # "outlined", "dashed", "solid", "filled", "text","link"]
620
+ block=True,
621
+ ) as add_conversation_btn
622
+ ):
623
+ ms.Text("New Chat")
624
+ with ms.Slot("icon"):
625
+ antd.Icon("PlusOutlined")
626
+
627
+ # Conversations List
628
+ with antdx.Conversations(
629
+ elem_classes="chatbot-conversations-list",
630
+ ) as conversations:
631
+ with ms.Slot("menu.items"):
632
+ with antd.Menu.Item(
633
+ label="Delete", key="delete", danger=True
634
+ ) as conversation_delete_menu_item:
635
+ with ms.Slot("icon"):
636
+ antd.Icon("DeleteOutlined")
637
+ # Mid Column
638
+ with antd.Col(flex=1, elem_style=dict(height="100%")):
639
+ with antd.Flex(
640
+ vertical=True,
641
+ gap="small",
642
+ elem_classes="chatbot-chat",
643
+ # elem_style=dict(
644
+ # backgroundImage="linear-gradient(137deg, #e5f4ff 10%, #efe7ff 1000%)",
645
+ # ),
646
+ ):
647
+ # Chatbot
648
+ chatbot = pro.Chatbot(
649
+ elem_classes="chatbot-chat-messages",
650
+ height=0,
651
+ welcome_config=welcome_config(),
652
+ user_config=user_config(),
653
+ bot_config=bot_config(),
654
+ )
655
+
656
+ with antdx.Sender(placeholder="Enter your message...") as input:
657
+ with ms.Slot("prefix"):
658
+ with antd.Flex(
659
+ gap=4, wrap=True, elem_style=dict(maxWidth="40vw")
660
+ ):
661
+ with antd.Tooltip(title="Clear chat") as tooltip:
662
+ with antd.Button(
663
+ value=None, type="text"
664
+ ) as clear_btn:
665
+ with ms.Slot("icon"):
666
+ antd.Icon(
667
+ "FormatPainterOutlined",
668
+ elem_style=dict(color="red"),
669
+ )
670
+
671
+ # Right Column
672
+ settings_sidebar_visible = gr.State(True)
673
+ with antd.Col(
674
+ md=dict(flex="0 0 355px", span=24, order=2),
675
+ span=0,
676
+ elem_style=dict(width=0),
677
+ order=1,
678
+ visible=True,
679
+ ) as settings_sidebar_col:
680
+ with ms.Div(elem_classes="chatbot-settings-sidebar"):
681
+ with antd.Flex(
682
+ vertical=True,
683
+ gap="small",
684
+ elem_style=dict(
685
+ height="100%",
686
+ padding="32px 16px",
687
+ # backgroundImage="linear-gradient(137deg, #e5f4ff 10%, #6400FF 115%)",
688
+ ),
689
+ ):
690
+ login_btn = gr.LoginButton()
691
+ settings_header_state, settings_form = SettingsMenu()
692
+
693
+ # Events Handler
694
+ # Browser State Handler
695
+ if save_history:
696
+ browser_state = gr.BrowserState(
697
+ {
698
+ "conversation_contexts": {},
699
+ "conversations": [],
700
+ },
701
+ storage_key="chat_demo_storage",
702
+ )
703
+ state.change(
704
+ fn=Gradio_Events.update_browser_state,
705
+ inputs=[state],
706
+ outputs=[browser_state],
707
+ )
708
+
709
+ demo.load(
710
+ fn=Gradio_Events.apply_browser_state,
711
+ inputs=[browser_state, state],
712
+ outputs=[conversations, state],
713
+ )
714
+
715
+ # Conversations Handler
716
+ add_conversation_btn.click(
717
+ fn=Gradio_Events.new_chat,
718
+ inputs=[state],
719
+ outputs=[conversations, chatbot, settings_form, state],
720
+ )
721
+ conversations.active_change(
722
+ fn=Gradio_Events.select_conversation,
723
+ inputs=[state],
724
+ outputs=[conversations, chatbot, settings_form, state],
725
+ )
726
+ conversations.menu_click(
727
+ fn=Gradio_Events.click_conversation_menu,
728
+ inputs=[state],
729
+ outputs=[conversations, chatbot, state],
730
+ )
731
+ # Chatbot Handler
732
+ chatbot.welcome_prompt_select(fn=Gradio_Events.apply_prompt, outputs=[input])
733
+
734
+ chatbot.delete(fn=Gradio_Events.delete_message, inputs=[state], outputs=[state])
735
+ chatbot.edit(
736
+ fn=Gradio_Events.edit_message, inputs=[state, chatbot], outputs=[state]
737
+ )
738
+
739
+ regenerating_event = chatbot.retry(
740
+ fn=Gradio_Events.regenerate_message,
741
+ inputs=[settings_form, state],
742
+ outputs=[
743
+ input,
744
+ clear_btn,
745
+ conversation_delete_menu_item,
746
+ add_conversation_btn,
747
+ conversations,
748
+ chatbot,
749
+ state,
750
+ ],
751
+ )
752
+
753
+ def toggle_settings_sidebar(visible):
754
+ return gr.update(value=not visible), gr.update(visible=not visible)
755
+
756
+ # Input Handler
757
+ submit_event = input.submit(
758
+ fn=Gradio_Events.add_message,
759
+ inputs=[input, settings_form, state],
760
+ outputs=[
761
+ input,
762
+ clear_btn,
763
+ conversation_delete_menu_item,
764
+ add_conversation_btn,
765
+ conversations,
766
+ chatbot,
767
+ state,
768
+ ],
769
+ )
770
+ input.cancel(
771
+ fn=Gradio_Events.cancel,
772
+ inputs=[state],
773
+ outputs=[
774
+ input,
775
+ conversation_delete_menu_item,
776
+ clear_btn,
777
+ conversations,
778
+ add_conversation_btn,
779
+ chatbot,
780
+ state,
781
+ ],
782
+ cancels=[submit_event, regenerating_event],
783
+ queue=False,
784
+ )
785
+
786
+ clear_btn.click(
787
+ fn=Gradio_Events.clear_conversation_history,
788
+ inputs=[state],
789
+ outputs=[chatbot, state],
790
+ )
791
+
792
+ if __name__ == "__main__":
793
+ demo.queue(default_concurrency_limit=100, max_size=100).launch(
794
+ ssr_mode=False, max_threads=100
795
+ )
config.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from modelscope_studio.components.pro.chatbot import (
2
+ ChatbotActionConfig,
3
+ ChatbotBotConfig,
4
+ ChatbotUserConfig,
5
+ ChatbotWelcomeConfig,
6
+ )
7
+
8
+ MIN_TEMPERATURE = 0
9
+ MAX_TEMPERATURE = 1
10
+ DEFAULT_TEMPERATURE = 0.6
11
+
12
+ MIN_MAX_NEW_TOKENS = 4096
13
+ MAX_MAX_NEW_TOKENS = 65536
14
+ DEFAULT_MAX_NEW_TOKENS = 65536
15
+
16
+ MIN_TOP_P = 0
17
+ MAX_TOP_P = 1
18
+ DEFAULT_TOP_P = 0.95
19
+
20
+
21
+ DEFAULT_MODEL = "tiiuae/Falcon-H1R-7B"
22
+ MODEL_OPTIONS = [
23
+ {
24
+ "label": "Falcon-H1R-7B",
25
+ "modelId": "tiiuae/Falcon-H1R-7B",
26
+ "value": "tiiuae/Falcon-H1R-7B",
27
+ "link": "https://huggingface.co/tiiuae/Falcon-H1R-7B",
28
+ "api_key_env": "X_API_KEY",
29
+ "base_url_env": "X_URL",
30
+ }
31
+ ]
32
+ MODEL_OPTIONS_MAP = {model["value"]: model for model in MODEL_OPTIONS}
33
+
34
+ DEFAULT_LOCALE = "en_US"
35
+
36
+ DEFAULT_THEME = {
37
+ "token": {
38
+ "colorPrimary": "#7422f2",
39
+ }
40
+ }
41
+
42
+ DEFAULT_SETTINGS = {
43
+ "model": DEFAULT_MODEL,
44
+ "temperature": DEFAULT_TEMPERATURE,
45
+ "max_new_tokens": DEFAULT_MAX_NEW_TOKENS,
46
+ "top_p": DEFAULT_TOP_P,
47
+ }
48
+
49
+
50
+ # Save history in browser
51
+ save_history = True
52
+
53
+ CHAR_YIELD_SIZE = 100 # Update UI every 100 characters
54
+ KEPT_TURNS = 10
55
+
56
+
57
+ # Chatbot Config
58
+ def user_config(disabled_actions=None):
59
+ return ChatbotUserConfig(
60
+ class_names=dict(content="user-message-content"),
61
+ actions=[
62
+ "copy",
63
+ "edit",
64
+ ChatbotActionConfig(
65
+ action="delete",
66
+ popconfirm=dict(
67
+ title="Delete the message",
68
+ description="Are you sure to delete this message?",
69
+ okButtonProps=dict(danger=True),
70
+ ),
71
+ ),
72
+ ],
73
+ disabled_actions=disabled_actions,
74
+ )
75
+
76
+
77
+ def bot_config(disabled_actions=None):
78
+ return ChatbotBotConfig(
79
+ actions=[
80
+ "copy",
81
+ "edit",
82
+ ChatbotActionConfig(
83
+ action="retry",
84
+ popconfirm=dict(
85
+ title="Re-generate the response",
86
+ description="Re-generate the response will also delete all subsequent messages.",
87
+ okButtonProps=dict(danger=False),
88
+ ),
89
+ ),
90
+ ChatbotActionConfig(
91
+ action="delete",
92
+ popconfirm=dict(
93
+ title="Delete the response",
94
+ description="Are you sure to delete this response?",
95
+ okButtonProps=dict(danger=True),
96
+ ),
97
+ ),
98
+ ],
99
+ avatar="./photos/falcon_logo.png",
100
+ disabled_actions=disabled_actions,
101
+ )
102
+
103
+
104
+ def welcome_config():
105
+ return ChatbotWelcomeConfig(
106
+ # variant="filled",
107
+ variant="borderless",
108
+ icon="./photos/falcon_logo.png",
109
+ title="Falcon-H1R",
110
+ description="Select your preferred reasoning model size and set your configs on the 'Settings' menu and enter your message to start chatting.",
111
+ prompts=dict(
112
+ styles={
113
+ "list": {
114
+ "width": "100%",
115
+ },
116
+ "item": {
117
+ "flex": 1,
118
+ },
119
+ },
120
+ items=[
121
+ {
122
+ "label": "📟 Write Python code",
123
+ "children": [
124
+ {
125
+ "description": "Write a python function that returns the factorial of a number using recursion.",
126
+ },
127
+ ],
128
+ },
129
+ {
130
+ "label": "🔢 Solve math questions",
131
+ "children": [
132
+ {
133
+ "description": "Solve 3x^2 + 2x + 1 = 0",
134
+ },
135
+ ],
136
+ },
137
+ {
138
+ "label": "🧠 Logical reasoning",
139
+ "children": [
140
+ {
141
+ "description": "A train leaves Station A at 9:00 AM traveling at 60 mph toward Station B. Another train leaves Station B at 10:00 AM traveling at 80 mph toward Station A. If the stations are 280 miles apart, at what time do the trains meet?",
142
+ },
143
+ ],
144
+ },
145
+ ],
146
+ ),
147
+ )
interface/logo.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import modelscope_studio.components.antd as antd
2
+ import modelscope_studio.components.base as ms
3
+
4
+
5
+ def Logo():
6
+ with antd.Typography.Title(
7
+ level=1, elem_style=dict(fontSize=34, padding=20, margin=0)
8
+ ):
9
+ with antd.Flex(align="center", gap="small", justify="center"):
10
+ antd.Image(
11
+ "./photos/tii_logo.png", preview=False, alt="photos", width=205, height=110
12
+ )
interface/settings.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import modelscope_studio.components.antd as antd
3
+ import modelscope_studio.components.base as ms
4
+
5
+ from config import *
6
+
7
+
8
+ def SettingsMenu():
9
+ state = gr.State({"open": True})
10
+
11
+ # Use a Card or just a Flex container for the sidebar
12
+ with antd.Card(title="Settings", size="small", bordered=True):
13
+ with antd.Form(value=DEFAULT_SETTINGS) as settings_form:
14
+ with antd.Form.Item(form_name="model", label="Model"):
15
+ with antd.Select(options=MODEL_OPTIONS):
16
+ with ms.Slot(
17
+ "labelRender",
18
+ params_mapping="""(option) => ({
19
+ label: option.label,
20
+ link: { href: window.MODEL_OPTIONS_MAP[option.value].link },
21
+ })""",
22
+ ):
23
+ antd.Typography.Text(as_item="label")
24
+
25
+ with antd.Form.Item(
26
+ form_name="temperature",
27
+ label="Temperature",
28
+ elem_classes="setting-form-temperature",
29
+ ):
30
+ antd.Slider(
31
+ elem_style=dict(flex=1, marginRight=14),
32
+ min=MIN_TEMPERATURE,
33
+ max=MAX_TEMPERATURE,
34
+ step=0.05,
35
+ tooltip=dict(formatter="(v) => `${v}`"),
36
+ )
37
+ antd.InputNumber(
38
+ max=MAX_TEMPERATURE,
39
+ min=MIN_TEMPERATURE,
40
+ step=0.05,
41
+ elem_style=dict(width=65),
42
+ )
43
+
44
+ with antd.Form.Item(
45
+ form_name="max_new_tokens",
46
+ label="Max new tokens",
47
+ elem_classes="setting-form-max-new-tokens",
48
+ ):
49
+ antd.Slider(
50
+ elem_style=dict(flex=1, marginRight=14),
51
+ min=MIN_MAX_NEW_TOKENS,
52
+ max=MAX_MAX_NEW_TOKENS,
53
+ step=64,
54
+ tooltip=dict(formatter="(v) => `${v}`"),
55
+ )
56
+ antd.InputNumber(
57
+ max=MAX_MAX_NEW_TOKENS,
58
+ min=MIN_MAX_NEW_TOKENS,
59
+ step=64,
60
+ elem_style=dict(width=85),
61
+ )
62
+
63
+ with antd.Form.Item(
64
+ form_name="top_p",
65
+ label="Top_p",
66
+ elem_classes="setting-form-top-p",
67
+ ):
68
+ antd.Slider(
69
+ elem_style=dict(flex=1, marginRight=14),
70
+ min=MIN_TOP_P,
71
+ max=MAX_TOP_P,
72
+ step=0.05,
73
+ tooltip=dict(formatter="(v) => `${v}`"),
74
+ )
75
+ antd.InputNumber(
76
+ max=MAX_TOP_P, min=MIN_TOP_P, step=0.05, elem_style=dict(width=65)
77
+ )
78
+
79
+ return state, settings_form
logs/.keepfile ADDED
File without changes
photos/falcon_logo.png ADDED

Git LFS Details

  • SHA256: cc60d522f58a4a19e11a6079e3d3a004888e487996a1e38d991501171828f2c3
  • Pointer size: 131 Bytes
  • Size of remote file: 605 kB
photos/tii_logo.png ADDED

Git LFS Details

  • SHA256: 1ffe126f30fd0a0b868d13d620dabc9ee93da7e7f3be9f6dd3e3fef1af67b8cc
  • Pointer size: 130 Bytes
  • Size of remote file: 66.6 kB
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio[oauth]
2
+ modelscope_studio
3
+ openai
test.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+
4
+ # Set environment variables FIRST, before any other imports
5
+ os.environ["PYTHONHASHSEED"] = "42"
6
+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":16:8"
7
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
8
+
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import torch
13
+ from tqdm import tqdm
14
+ from transformers import AutoTokenizer
15
+ from transformers import set_seed as transformers_set_seed
16
+ from vllm import LLM, SamplingParams
17
+
18
+ current_dir = Path(__file__).parent
19
+
20
+
21
+ def set_seed(seed: int = 42):
22
+ """Set seed for reproducibility across all libraries"""
23
+ random.seed(seed)
24
+ np.random.seed(seed)
25
+ torch.manual_seed(seed)
26
+
27
+ if torch.cuda.is_available():
28
+ torch.cuda.manual_seed(seed)
29
+ torch.cuda.manual_seed_all(seed)
30
+
31
+ transformers_set_seed(seed)
32
+ torch.use_deterministic_algorithms(True)
33
+ torch.backends.cudnn.deterministic = True
34
+ torch.backends.cudnn.benchmark = False
35
+
36
+
37
+ def main() -> None:
38
+ set_seed(41)
39
+ path = "../Falcon-H1R-7B"
40
+ tokenizer = AutoTokenizer.from_pretrained(path)
41
+ samples = [
42
+ "hi",
43
+ "what is 1+1?",
44
+ "what is the capital of france?",
45
+ "who are you?",
46
+ "solve 3x+1=0",
47
+ "Write a python function that returns the factorial of a number using recursion.",
48
+ "A train leaves Station A at 9:00 AM traveling at 60 mph toward Station B. Another train leaves Station B at 10:00 AM traveling at 80 mph toward Station A. If the stations are 280 miles apart, at what time do the trains meet?",
49
+ "Find the sum of all integer bases $b>9$ for which $17_b$ is a divisor of $97_b.$",
50
+ ]
51
+
52
+ # prepare Vllm input
53
+ inputs = [
54
+ tokenizer.apply_chat_template(
55
+ [{"role": "user", "content": sample}],
56
+ tokenize=False,
57
+ add_generation_prompt=True,
58
+ )
59
+ # + "<think>\n</think>\n"
60
+ for sample in tqdm(samples)
61
+ ]
62
+
63
+ # Load model in vllm
64
+ llm_kwargs = {
65
+ "model": path,
66
+ "trust_remote_code": True,
67
+ "tensor_parallel_size": 2,
68
+ }
69
+ llm = LLM(**llm_kwargs)
70
+
71
+ # Sampling params
72
+ gen_kwargs = {
73
+ "max_tokens": 32768,
74
+ "temperature": 0.6,
75
+ "top_p": 0.95,
76
+ "stop": ["<|endoftext|>", "<|im_end|>", "</s>", "<|eot_id|>", "<|end|>"],
77
+ }
78
+ sampling_params = SamplingParams(**gen_kwargs)
79
+
80
+ # generate
81
+ outputs = llm.generate(inputs, sampling_params)
82
+ generated_texts = [output.outputs[0].text for output in outputs]
83
+
84
+ # display
85
+ for sample, generated_text in zip(samples, generated_texts):
86
+ print("User:")
87
+ print(sample)
88
+ print("Assisant:")
89
+ print(generated_text)
90
+ print("-" * 50)
91
+
92
+
93
+ main()