Spaces:
Runtime error
Runtime error
File size: 9,886 Bytes
c74831d 54ac395 af43a3d 54ac395 c74831d 54ac395 311e2d3 54ac395 0292d70 6420f07 54ac395 311e2d3 54ac395 433d9a2 54ac395 311e2d3 54ac395 311e2d3 54ac395 311e2d3 54ac395 311e2d3 54ac395 311e2d3 54ac395 433d9a2 54ac395 311e2d3 af43a3d 54ac395 433d9a2 af43a3d 433d9a2 54ac395 af43a3d 311e2d3 54ac395 311e2d3 433d9a2 54ac395 433d9a2 54ac395 311e2d3 54ac395 311e2d3 54ac395 af43a3d 54ac395 af43a3d 6420f07 af43a3d 6420f07 af43a3d 54ac395 311e2d3 4762d68 433d9a2 311e2d3 54ac395 af43a3d 763a991 311e2d3 af43a3d 311e2d3 af43a3d 9f5d2e9 311e2d3 af43a3d b4ba75b af43a3d b4ba75b af43a3d 9f5d2e9 af43a3d 9f5d2e9 af43a3d 9f5d2e9 927ae14 9f5d2e9 af43a3d 763a991 af43a3d 54ac395 af43a3d 433d9a2 54ac395 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
import gradio as gr
import os
import threading
import arrow
import time
import argparse
import logging
from dataclasses import dataclass
import torch
import sentencepiece as spm
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers import GPTNeoXForCausalLM, GPTNeoXConfig
from transformers.generation.streamers import BaseStreamer
from huggingface_hub import hf_hub_download, login
logger = logging.getLogger()
logger.setLevel("INFO")
gr_interface = None
VERSION = "0.1.0"
@dataclass
class DefaultArgs:
hf_model_name_or_path: str = None
hf_tokenizer_name_or_path: str = None
spm_model_path: str = None
env: str = "dev"
port: int = 7860
make_public: bool = False
if os.getenv("RUNNING_ON_HF_SPACE"):
login(token=os.getenv("HF_TOKEN"))
hf_repo = os.getenv("HF_MODEL_REPO")
args = DefaultArgs()
args.hf_model_name_or_path = hf_repo
args.hf_tokenizer_name_or_path = os.path.join(hf_repo, "tokenizer")
args.spm_model_path = hf_hub_download(repo_id=hf_repo, filename="sentencepiece.model")
else:
parser = argparse.ArgumentParser(description="")
parser.add_argument("--hf_model_name_or_path", type=str, required=True)
parser.add_argument("--hf_tokenizer_name_or_path", type=str, required=False)
parser.add_argument("--spm_model_path", type=str, required=True)
parser.add_argument("--env", type=str, default="dev")
parser.add_argument("--port", type=int, default=7860)
parser.add_argument("--make_public", action='store_true')
args = parser.parse_args()
def load_model(
model_dir,
):
config = GPTNeoXConfig.from_pretrained(model_dir)
config.is_decoder = True
model = GPTNeoXForCausalLM.from_pretrained(model_dir, config=config, torch_dtype=torch.bfloat16)
if torch.cuda.is_available():
model = model.to("cuda:0")
return model
logging.info("Loading model")
model = load_model(args.hf_model_name_or_path)
sp = spm.SentencePieceProcessor(model_file=args.spm_model_path)
logging.info("Finished loading model")
tokenizer = AutoTokenizer.from_pretrained(
args.hf_model_name_or_path,
subfolder="tokenizer",
use_fast=False
)
class TokenizerStreamer(BaseStreamer):
def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.num_invoked = 0
self.prompt = ""
self.generated_text = ""
self.ended = False
def put(self, t: torch.Tensor):
d = t.dim()
if d == 1:
pass
elif d == 2:
t = t[0]
else:
raise NotImplementedError
t = [int(x) for x in t.numpy()]
text = tokenizer.decode(t)
if text in [tokenizer.bos_token, tokenizer.eos_token]:
text = ""
if self.num_invoked == 0:
self.prompt = text
self.num_invoked += 1
return
self.generated_text += text
logging.debug(f"[streamer]: {self.generated_text}")
def end(self):
self.ended = True
INPUT_PROMPT = """ไปฅไธใฏใใฟในใฏใ่ชฌๆใใๆ็คบใจใๆ่ใฎใใๅ
ฅๅใฎ็ตใฟๅใใใงใใ่ฆๆฑใ้ฉๅใซๆบใใๅฟ็ญใๆธใใชใใใ
### ๆ็คบ:
{instruction}
### ๅ
ฅๅ:
{input}
### ๅฟ็ญ: """
NO_INPUT_PROMPT = """ไปฅไธใฏใใฟในใฏใ่ชฌๆใใๆ็คบใจใๆ่ใฎใใๅ
ฅๅใฎ็ตใฟๅใใใงใใ่ฆๆฑใ้ฉๅใซๆบใใๅฟ็ญใๆธใใชใใใ
### ๆ็คบ:
{instruction}
### ๅฟ็ญ: """
def postprocess_output(output):
output = output\
.split('### ๅฟ็ญ:')[1]\
.split('###')[0]\
.split('##')[0]\
.lstrip(tokenizer.bos_token)\
.rstrip(tokenizer.eos_token)\
.replace("###", "")\
.strip()
return output
def generate(
prompt,
max_new_tokens,
temperature,
repetition_penalty,
do_sample,
no_repeat_ngram_size,
):
log = dict(locals())
logging.debug(log)
input_text = NO_INPUT_PROMPT.format(instruction=prompt)
input_ids = tokenizer.encode(input_text, add_special_tokens=False, return_tensors="pt")
streamer = TokenizerStreamer(tokenizer=tokenizer)
max_possilbe_new_tokens = model.config.max_position_embeddings - input_ids.shape[0]
max_possilbe_new_tokens = min(max_possilbe_new_tokens, max_new_tokens)
thr = threading.Thread(target=model.generate, args=(), kwargs=dict(
input_ids=input_ids.to(model.device),
do_sample=do_sample,
temperature=temperature,
repetition_penalty=repetition_penalty,
no_repeat_ngram_size=no_repeat_ngram_size,
max_new_tokens=max_possilbe_new_tokens,
pad_token_id=tokenizer.pad_token_id,
bos_token_id=tokenizer.bos_token_id,
eos_token_id=tokenizer.eos_token_id,
bad_words_ids=[[tokenizer.unk_token_id]],
streamer=streamer,
))
thr.start()
while not streamer.ended:
time.sleep(0.05)
yield streamer.generated_text
# TODO: optimize for final few tokens
gen = streamer.generated_text
log.update(dict(
generation=gen,
version=VERSION,
time=str(arrow.now("+09:00"))))
logging.info(log)
yield gen
def process_feedback(
rating,
prompt,
generation,
max_new_tokens,
temperature,
repetition_penalty,
do_sample,
no_repeat_ngram_size,
):
log = dict(locals())
log.update(dict(
time=str(arrow.now("+09:00")),
version=VERSION,
))
logging.info(log)
if gr_interface:
gr_interface.close(verbose=False)
with gr.Blocks() as gr_interface:
with gr.Row():
gr.Markdown(f"# ๆฅๆฌ่ช StableLM Tuned Pre-Alpha ({VERSION})")
# gr.Markdown(f"ใใผใธใงใณ๏ผ{VERSION}")
with gr.Row():
gr.Markdown("ใใฎ่จ่ชใขใใซใฏ Stability AI Japan ใ้็บใใๅๆใใผใธใงใณใฎๆฅๆฌ่ชใขใใซใงใใใขใใซใฏใใใญใณใใใใซๅ
ฅๅใใ่ใใใใใจใซๅฏพใใฆใใใใใใๅฟ็ญใใใใใจใใงใใพใใ")
with gr.Row():
# left panel
with gr.Column(scale=1):
# generation params
with gr.Box():
gr.Markdown("ใใฉใกใผใฟ")
# hidden default params
do_sample = gr.Checkbox(True, label="Do Sample", info="ใตใณใใชใณใฐ็ๆ", visible=True)
no_repeat_ngram_size = gr.Slider(0, 10, value=3, step=1, label="No Repeat Ngram Size", visible=False)
# visible params
max_new_tokens = gr.Slider(
128,
min(512, model.config.max_position_embeddings),
value=128,
step=128,
label="max tokens",
info="็ๆใใใใผใฏใณใฎๆๅคงๆฐใๆๅฎใใ",
)
temperature = gr.Slider(
0, 1, value=0.1, step=0.05, label="temperature",
info="ไฝใๅคใฏๅบๅใใใ้ไธญใใใฆๆฑบๅฎ่ซ็ใซใใ")
repetition_penalty = gr.Slider(
1, 1.5, value=1.2, step=0.05, label="frequency penalty",
info="้ซใๅคใฏAIใ็นฐใ่ฟใๅฏ่ฝๆงใๆธๅฐใใใ")
# grouping params for easier reference
gr_params = [
max_new_tokens,
temperature,
repetition_penalty,
do_sample,
no_repeat_ngram_size,
]
# right panel
with gr.Column(scale=2):
# user input block
with gr.Box():
textbox_prompt = gr.Textbox(
label="ใใญใณใใ",
placeholder="ๆฅๆฌใฎ้ฆ้ฝใฏ๏ผ",
interactive=True,
lines=5,
value=""
)
with gr.Box():
with gr.Row():
btn_stop = gr.Button(value="ใญใฃใณใปใซ", variant="secondary")
btn_submit = gr.Button(value="ๅฎ่ก", variant="primary")
# model output block
with gr.Box():
textbox_generation = gr.Textbox(
label="็ๆ็ตๆ",
lines=5,
value=""
)
# rating block
with gr.Row():
gr.Markdown("ใใ่ฏใ่จ่ชใขใใซใ็ๆงใซๆไพใงใใใใใ็ๆๅ่ณชใซใคใใฆใฎใๆ่ฆใใ่ใใใใ ใใใ")
with gr.Box():
with gr.Row():
rating_options = [
"ๆๆช",
"ไธๅๆ ผ",
"ไธญ็ซ",
"ๅๆ ผ",
"ๆ้ซ",
]
btn_ratings = [gr.Button(value=v) for v in rating_options]
# TODO: we might not need this for sharing with close groups
# with gr.Box():
# gr.Markdown("TODO๏ผFor more feedback link for google form")
# event handling
inputs = [textbox_prompt] + gr_params
click_event = btn_submit.click(generate, inputs, textbox_generation, queue=True)
btn_stop.click(None, None, None, cancels=click_event, queue=False)
for btn_rating in btn_ratings:
btn_rating.click(process_feedback, [btn_rating, textbox_prompt, textbox_generation] + gr_params, queue=False)
gr_interface.queue(max_size=32, concurrency_count=2)
gr_interface.launch(server_port=args.port, share=args.make_public)
|