Spaces:
Build error
Build error
Use inference endpoint
Browse files- .gitignore +162 -0
- README.md +6 -5
- app.py +154 -0
- dialogues.py +241 -0
- gradio-12.34.56.tar.gz +3 -0
- requirements.txt +3 -0
- utils.py +19 -0
.gitignore
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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/
|
161 |
+
|
162 |
+
data/
|
README.md
CHANGED
@@ -1,12 +1,13 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
|
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: Reward Modeling UI
|
3 |
+
emoji: 🎁
|
4 |
+
colorFrom: orange
|
5 |
+
colorTo: indigo
|
6 |
sdk: gradio
|
7 |
+
python_version: 3.9.13
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
license: apache-2.0
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import subprocess
|
2 |
+
|
3 |
+
commands = 'pip uninstall gradio -y; echo "pwd is: $(pwd)"; pip install ./gradio-12.34.56.tar.gz'
|
4 |
+
subprocess.run(commands, shell=True)
|
5 |
+
|
6 |
+
import json
|
7 |
+
import os
|
8 |
+
|
9 |
+
import shutil
|
10 |
+
import threading
|
11 |
+
|
12 |
+
from typing import List
|
13 |
+
|
14 |
+
import gradio as gr
|
15 |
+
|
16 |
+
from dialogues import DialogueTemplate
|
17 |
+
from huggingface_hub import Repository
|
18 |
+
from text_generation import Client
|
19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
20 |
+
|
21 |
+
from utils import get_full_text, wrap_html_code
|
22 |
+
|
23 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
24 |
+
REPO_ID = "sheonhan/rm-test-data"
|
25 |
+
API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/starcoderbase-finetuned-oasst1"
|
26 |
+
|
27 |
+
|
28 |
+
LABELER_ID = "labeler_123"
|
29 |
+
SESSION_ID = "session_123"
|
30 |
+
|
31 |
+
client = Client(
|
32 |
+
API_URL,
|
33 |
+
headers={"Authorization": f"Bearer {HF_TOKEN}"},
|
34 |
+
)
|
35 |
+
|
36 |
+
repo = None
|
37 |
+
if HF_TOKEN:
|
38 |
+
try:
|
39 |
+
shutil.rmtree("./data/")
|
40 |
+
except:
|
41 |
+
pass
|
42 |
+
|
43 |
+
print("Pulling repo...")
|
44 |
+
repo = Repository(
|
45 |
+
local_dir="./data/",
|
46 |
+
clone_from=REPO_ID,
|
47 |
+
use_auth_token=HF_TOKEN,
|
48 |
+
repo_type="dataset",
|
49 |
+
)
|
50 |
+
repo.git_pull()
|
51 |
+
|
52 |
+
system_message = ""
|
53 |
+
|
54 |
+
|
55 |
+
def generate(user_message, history):
|
56 |
+
past_messages = []
|
57 |
+
for data in history:
|
58 |
+
user_data, model_data = data
|
59 |
+
|
60 |
+
past_messages.extend(
|
61 |
+
[
|
62 |
+
{"role": "user", "content": user_data},
|
63 |
+
{"role": "assistant", "content": model_data.rstrip()},
|
64 |
+
]
|
65 |
+
)
|
66 |
+
|
67 |
+
if len(past_messages) < 1:
|
68 |
+
dialogue_template = DialogueTemplate(
|
69 |
+
system=system_message,
|
70 |
+
messages=[{"role": "user", "content": user_message}],
|
71 |
+
end_token="<|endoftext|>",
|
72 |
+
)
|
73 |
+
prompt = dialogue_template.get_inference_prompt()
|
74 |
+
else:
|
75 |
+
dialogue_template = DialogueTemplate(
|
76 |
+
system=system_message,
|
77 |
+
messages=past_messages + [{"role": "user", "content": user_message}],
|
78 |
+
end_token="<|endoftext|>",
|
79 |
+
)
|
80 |
+
prompt = dialogue_template.get_inference_prompt()
|
81 |
+
|
82 |
+
response_1 = client.generate_stream(
|
83 |
+
prompt, temperature=0.1, stop_sequences=["<|end|>"]
|
84 |
+
)
|
85 |
+
|
86 |
+
response_2 = client.generate_stream(
|
87 |
+
prompt, temperature=0.9, stop_sequences=["<|end|>"]
|
88 |
+
)
|
89 |
+
|
90 |
+
response_1_text = get_full_text(response_1)
|
91 |
+
response_2_text = get_full_text(response_2)
|
92 |
+
|
93 |
+
option_a = wrap_html_code(response_1_text.strip())
|
94 |
+
option_b = wrap_html_code(response_2_text.strip())
|
95 |
+
|
96 |
+
history.append((user_message, option_a, option_b))
|
97 |
+
|
98 |
+
return "", history
|
99 |
+
|
100 |
+
|
101 |
+
def save_labeling_data(last_dialogue, score):
|
102 |
+
(
|
103 |
+
prompt,
|
104 |
+
response_1,
|
105 |
+
response_2,
|
106 |
+
) = last_dialogue
|
107 |
+
|
108 |
+
file_name = "data.jsonl"
|
109 |
+
|
110 |
+
if repo is not None:
|
111 |
+
repo.git_pull(rebase=True)
|
112 |
+
|
113 |
+
with open(os.path.join("data", file_name), "a", encoding="utf-8") as f:
|
114 |
+
data = {
|
115 |
+
"labeler_id": LABELER_ID,
|
116 |
+
"session_id": SESSION_ID,
|
117 |
+
"prompt": prompt,
|
118 |
+
"response_1": response_1,
|
119 |
+
"response_2": response_2,
|
120 |
+
"score": score,
|
121 |
+
}
|
122 |
+
json.dump(data, f, ensure_ascii=False)
|
123 |
+
f.write("\n")
|
124 |
+
|
125 |
+
repo.push_to_hub()
|
126 |
+
|
127 |
+
|
128 |
+
def on_select(event: gr.SelectData, history):
|
129 |
+
score = event.value
|
130 |
+
index_to_delete = event.index
|
131 |
+
|
132 |
+
threading.Thread(target=save_labeling_data, args=(history[-1], score)).start()
|
133 |
+
|
134 |
+
del history[-1][index_to_delete]
|
135 |
+
return history
|
136 |
+
|
137 |
+
|
138 |
+
with gr.Blocks() as demo:
|
139 |
+
chatbot = gr.Chatbot()
|
140 |
+
user_message = gr.Textbox()
|
141 |
+
clear = gr.Button("Clear")
|
142 |
+
|
143 |
+
user_message.submit(
|
144 |
+
generate,
|
145 |
+
[user_message, chatbot],
|
146 |
+
[user_message, chatbot],
|
147 |
+
queue=False,
|
148 |
+
)
|
149 |
+
|
150 |
+
chatbot.select(on_select, chatbot, chatbot)
|
151 |
+
|
152 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
153 |
+
|
154 |
+
demo.launch()
|
dialogues.py
ADDED
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
import json
|
17 |
+
import os
|
18 |
+
from dataclasses import asdict, dataclass
|
19 |
+
from pathlib import Path
|
20 |
+
from typing import Any, Dict, List, Optional, Type, TypeVar, Union
|
21 |
+
|
22 |
+
from huggingface_hub import ModelHubMixin, hf_hub_download
|
23 |
+
|
24 |
+
# Generic variable that is either ModelHubMixin or a subclass thereof
|
25 |
+
T = TypeVar("T", bound="ModelHubMixin")
|
26 |
+
|
27 |
+
TEMPLATE_FILENAME = "dialogue_template.json"
|
28 |
+
IGNORE_INDEX = -100
|
29 |
+
|
30 |
+
|
31 |
+
@dataclass
|
32 |
+
class DialogueTemplate(ModelHubMixin):
|
33 |
+
"""Converts all turns of a dialogue between a user and assistant to a standardized format.
|
34 |
+
|
35 |
+
Adapted from OpenAI's ChatML (https://github.com/openai/openai-python/blob/main/chatml.md) and Vicuna (https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py)
|
36 |
+
"""
|
37 |
+
|
38 |
+
system: str
|
39 |
+
messages: List[Dict[str, str]] = None
|
40 |
+
system_token: str = "<|system|>"
|
41 |
+
user_token: str = "<|user|>"
|
42 |
+
assistant_token: str = "<|assistant|>"
|
43 |
+
end_token: str = "<|end|>"
|
44 |
+
|
45 |
+
def get_training_prompt(self) -> str:
|
46 |
+
prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
|
47 |
+
if self.messages is None:
|
48 |
+
raise ValueError("Dialogue template must have at least one message.")
|
49 |
+
for message in self.messages:
|
50 |
+
if message["role"] == "user":
|
51 |
+
prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
|
52 |
+
else:
|
53 |
+
prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
|
54 |
+
return prompt
|
55 |
+
|
56 |
+
def get_inference_prompt(self) -> str:
|
57 |
+
prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
|
58 |
+
if self.messages is None:
|
59 |
+
raise ValueError("Dialogue template must have at least one message.")
|
60 |
+
for message in self.messages:
|
61 |
+
if message["role"] == "user":
|
62 |
+
prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
|
63 |
+
else:
|
64 |
+
prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
|
65 |
+
prompt += self.assistant_token + "\n"
|
66 |
+
return prompt
|
67 |
+
|
68 |
+
def get_dialogue(self):
|
69 |
+
"""Helper function to format the messages as an easy-to-read dialogue."""
|
70 |
+
prompt = ""
|
71 |
+
if self.messages is None:
|
72 |
+
raise ValueError("Dialogue template must have at least one message.")
|
73 |
+
for message in self.messages:
|
74 |
+
if message["role"] == "user":
|
75 |
+
prompt += "\n\nHuman: " + message["content"]
|
76 |
+
else:
|
77 |
+
prompt += "\n\nAssistant: " + message["content"]
|
78 |
+
return prompt
|
79 |
+
|
80 |
+
def get_special_tokens(self) -> List[str]:
|
81 |
+
return [self.system_token, self.user_token, self.assistant_token, self.end_token]
|
82 |
+
|
83 |
+
def copy(self):
|
84 |
+
return DialogueTemplate(
|
85 |
+
system=self.system,
|
86 |
+
messages=self.messages,
|
87 |
+
system_token=self.system_token,
|
88 |
+
user_token=self.user_token,
|
89 |
+
assistant_token=self.assistant_token,
|
90 |
+
end_token=self.end_token,
|
91 |
+
)
|
92 |
+
|
93 |
+
def to_dict(self) -> Dict[str, Any]:
|
94 |
+
return {k: v for k, v in asdict(self).items()}
|
95 |
+
|
96 |
+
@classmethod
|
97 |
+
def from_dict(cls, data):
|
98 |
+
return DialogueTemplate(
|
99 |
+
system=data["system"] if "system" in data else "",
|
100 |
+
messages=data["messages"] if "messages" in data else None,
|
101 |
+
system_token=data["system_token"] if "system_token" in data else "<|system|>",
|
102 |
+
user_token=data["user_token"] if "user_token" in data else "<|user|>",
|
103 |
+
assistant_token=data["assistant_token"] if "assistant_token" in data else "<|assistant|>",
|
104 |
+
end_token=data["end_token"] if "end_token" in data else "<|end|>",
|
105 |
+
)
|
106 |
+
|
107 |
+
def _save_pretrained(self, save_directory: Union[str, Path]) -> None:
|
108 |
+
save_directory = Path(save_directory)
|
109 |
+
save_directory.mkdir(exist_ok=True)
|
110 |
+
with open(save_directory / "dialogue_template.json", "w") as f:
|
111 |
+
json.dump(self.to_dict(), f, indent=2)
|
112 |
+
|
113 |
+
@classmethod
|
114 |
+
def _from_pretrained(
|
115 |
+
cls: Type[T],
|
116 |
+
*,
|
117 |
+
model_id: str,
|
118 |
+
revision: Optional[str],
|
119 |
+
cache_dir: Optional[Union[str, Path]],
|
120 |
+
force_download: bool,
|
121 |
+
proxies: Optional[Dict],
|
122 |
+
resume_download: bool,
|
123 |
+
local_files_only: bool,
|
124 |
+
token: Optional[Union[str, bool]],
|
125 |
+
**model_kwargs,
|
126 |
+
) -> T:
|
127 |
+
"""Loads the dialogue template from a local directory or the Huggingface Hub.
|
128 |
+
|
129 |
+
Args:
|
130 |
+
model_id (`str`):
|
131 |
+
ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
|
132 |
+
revision (`str`, *optional*):
|
133 |
+
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
|
134 |
+
latest commit on `main` branch.
|
135 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
136 |
+
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
|
137 |
+
the existing cache.
|
138 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
139 |
+
Whether to delete incompletely received files. Will attempt to resume the download if such a file exists.
|
140 |
+
proxies (`Dict[str, str]`, *optional*):
|
141 |
+
A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128',
|
142 |
+
'http://hostname': 'foo.bar:4012'}`).
|
143 |
+
token (`str` or `bool`, *optional*):
|
144 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
145 |
+
cached when running `huggingface-cli login`.
|
146 |
+
cache_dir (`str`, `Path`, *optional*):
|
147 |
+
Path to the folder where cached files are stored.
|
148 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
149 |
+
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
|
150 |
+
model_kwargs:
|
151 |
+
Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
|
152 |
+
"""
|
153 |
+
if os.path.isdir(model_id): # Can either be a local directory
|
154 |
+
print("Loading dialogue template from local directory")
|
155 |
+
template_file = os.path.join(model_id, TEMPLATE_FILENAME)
|
156 |
+
else: # Or a template on the Hub
|
157 |
+
template_file = hf_hub_download( # Download from the hub, passing same input args
|
158 |
+
repo_id=model_id,
|
159 |
+
filename=TEMPLATE_FILENAME,
|
160 |
+
revision=revision,
|
161 |
+
cache_dir=cache_dir,
|
162 |
+
force_download=force_download,
|
163 |
+
proxies=proxies,
|
164 |
+
resume_download=resume_download,
|
165 |
+
token=token,
|
166 |
+
local_files_only=local_files_only,
|
167 |
+
)
|
168 |
+
|
169 |
+
# Load template
|
170 |
+
with open(template_file, "r") as f:
|
171 |
+
data = json.load(f)
|
172 |
+
return cls.from_dict(data=data)
|
173 |
+
|
174 |
+
|
175 |
+
# A shortened version of the system message in Anthropic's HHH prompt: https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt
|
176 |
+
default_template = DialogueTemplate(
|
177 |
+
system="Below is a dialogue between a human user and an AI assistant. The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.",
|
178 |
+
)
|
179 |
+
|
180 |
+
# OpenAI and OpenAssistant train on few to no system messages.
|
181 |
+
# TODO: consider defining this as the `default` template
|
182 |
+
no_system_template = DialogueTemplate(
|
183 |
+
system="",
|
184 |
+
)
|
185 |
+
|
186 |
+
alpaca_template = DialogueTemplate(
|
187 |
+
system="Below is an instruction that describes a task. Write a response that appropriately completes the request.",
|
188 |
+
user_token="### Instruction:",
|
189 |
+
assistant_token="### Response:",
|
190 |
+
)
|
191 |
+
|
192 |
+
SUPPORTED_DIALOGUE_TEMPLATES = {
|
193 |
+
"default": default_template,
|
194 |
+
"no_system": no_system_template,
|
195 |
+
"alpaca": alpaca_template,
|
196 |
+
}
|
197 |
+
|
198 |
+
|
199 |
+
def get_dialogue_template(template: str) -> DialogueTemplate:
|
200 |
+
if template not in SUPPORTED_DIALOGUE_TEMPLATES.keys():
|
201 |
+
raise ValueError(f"Template {template} is not supported!")
|
202 |
+
return SUPPORTED_DIALOGUE_TEMPLATES[template].copy()
|
203 |
+
|
204 |
+
|
205 |
+
def prepare_dialogue(example, dialogue_template, is_train=True):
|
206 |
+
"""Format example to single- or multi-turn dialogue."""
|
207 |
+
# TODO: make this simpler by just ensuring every dataset has a messages column
|
208 |
+
if "messages" in example.keys() and example["messages"] is not None:
|
209 |
+
dialogue_template.messages = example["messages"]
|
210 |
+
elif all(k in example.keys() for k in ("prompt", "completion")):
|
211 |
+
# Construct single-turn dialogue from prompt and completion
|
212 |
+
dialogue_template.messages = [
|
213 |
+
{"role": "user", "content": example["prompt"]},
|
214 |
+
{"role": "assistant", "content": example["completion"]},
|
215 |
+
]
|
216 |
+
elif "prompt" in example.keys():
|
217 |
+
# Construct single-turn dialogue from prompt (inference only)
|
218 |
+
dialogue_template.messages = [
|
219 |
+
{"role": "user", "content": example["prompt"]},
|
220 |
+
]
|
221 |
+
else:
|
222 |
+
raise ValueError(
|
223 |
+
f"Could not format example as dialogue! Require either `messages` or `[prompt, completion]` or `[prompt]` keys but found {list(example.keys())}"
|
224 |
+
)
|
225 |
+
if is_train:
|
226 |
+
example["text"] = dialogue_template.get_training_prompt()
|
227 |
+
else:
|
228 |
+
example["text"] = dialogue_template.get_inference_prompt()
|
229 |
+
return example
|
230 |
+
|
231 |
+
|
232 |
+
def mask_user_labels(tokenizer, dialogue_template, labels):
|
233 |
+
"""Masks the user turns of a dialogue from the loss"""
|
234 |
+
user_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.user_token)
|
235 |
+
assistant_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.assistant_token)
|
236 |
+
for idx, label_id in enumerate(labels):
|
237 |
+
if label_id == user_token_id:
|
238 |
+
current_idx = idx
|
239 |
+
while labels[current_idx] != assistant_token_id and current_idx < len(labels):
|
240 |
+
labels[current_idx] = IGNORE_INDEX
|
241 |
+
current_idx += 1
|
gradio-12.34.56.tar.gz
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dfde41d90c665e4e4c9ac81b5e9014c2b4f460f908035f7d7fd280fef2d5937f
|
3 |
+
size 11060509
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
text-generation
|
2 |
+
torch
|
3 |
+
transformers
|
utils.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
|
4 |
+
def wrap_html_code(text):
|
5 |
+
pattern = r"<.*?>"
|
6 |
+
matches = re.findall(pattern, text)
|
7 |
+
if len(matches) > 0:
|
8 |
+
return f"```{text}```"
|
9 |
+
else:
|
10 |
+
return text
|
11 |
+
|
12 |
+
|
13 |
+
def get_full_text(response):
|
14 |
+
output = ""
|
15 |
+
for resp in response:
|
16 |
+
if resp.token.special:
|
17 |
+
continue
|
18 |
+
output += resp.token.text
|
19 |
+
return output
|