import gradio as gr import gc, copy, re from huggingface_hub import hf_hub_download from rwkv.model import RWKV from rwkv.utils import PIPELINE, PIPELINE_ARGS ctx_limit = 2048 title = "ru_rwkv5_extract_qa_04B_65536_ctx8192_L24_D1024.pth" model_path = hf_hub_download(repo_id="Sigma-AI/ru_rwkv5_extract_qa", filename=f"{title}") model = RWKV(model=model_path, strategy='cpu bf16') pipeline = PIPELINE(model, "rwkv_vocab_v20230424") def generate_prompt(context, question): context = context.strip().replace('\r\n','\n').replace('\n\n','\n').replace('\n\n','\n') question = question.strip().replace('\r\n','\n').replace('\n\n','\n').replace('\n\n','\n') return f"""CONTEXT:{context} QUESTION:{question} ANSWER:""" examples = [ ["Вторая мировая война (началась 01.09.1939 и закончилась 02.09.1945) — война двух мировых военно-политических коалиций, ставшая крупнейшим вооружённым конфликтом в истории человечества.В ней участвовали 62 государства из 74 существовавших на тот момент (80 % населения Земного шара).\nБоевые действия велись на территории Европы, Азии и Африки и в водах всех океанов. Это единственный конфликт, в котором было применено ядерное оружие. В результате войны погибло более 70 миллионов человек, из которых большинство — мирные жители.Число участвовавших стран менялось в течение войны. Некоторые из них вели активные военные действия, другие помогали Союзникам поставками продовольствия, а многие участвовали в войне только номинально.", "Было ли применено ядерное оружие?", 300, 1, 0.5, 0.4, 0.4], ] def evaluate( instruction, input=None, token_count=200, temperature=1.0, top_p=0.5, presencePenalty = 0.4, countPenalty = 0.4, ): args = PIPELINE_ARGS(temperature = max(0.2, float(temperature)), top_p = float(top_p), alpha_frequency = countPenalty, alpha_presence = presencePenalty, token_ban = [], # ban the generation of some tokens token_stop = [0]) # stop generation whenever you see any token here instruction = re.sub(r'\n{2,}', '\n', instruction).strip().replace('\r\n','\n') input = re.sub(r'\n{2,}', '\n', input).strip().replace('\r\n','\n') ctx = generate_prompt(instruction, input) all_tokens = [] out_last = 0 out_str = '' occurrence = {} state = None for i in range(int(token_count)): out, state = model.forward(pipeline.encode(ctx)[-ctx_limit:] if i == 0 else [token], state) for n in occurrence: out[n] -= (args.alpha_presence + occurrence[n] * args.alpha_frequency) token = pipeline.sample_logits(out, temperature=args.temperature, top_p=args.top_p) if token in args.token_stop: break all_tokens += [token] for xxx in occurrence: occurrence[xxx] *= 0.996 if token not in occurrence: occurrence[token] = 1 else: occurrence[token] += 1 tmp = pipeline.decode(all_tokens[out_last:]) if '\ufffd' not in tmp: out_str += tmp yield out_str.strip() out_last = i + 1 if '\n\n' in out_str: break del out del state gc.collect() yield out_str.strip() def user(message, chatbot): chatbot = chatbot or [] return "", chatbot + [[message, None]] def alternative(chatbot, history): if not chatbot or not history: return chatbot, history chatbot[-1][1] = None history[0] = copy.deepcopy(history[1]) return chatbot, history with gr.Blocks(title=title) as demo: gr.HTML(f"
\n

🌍World - {title}

\n
") with gr.Tab("Extract QA"): gr.Markdown(f"100% RNN RWKV-LM **trained on 100+ world languages**. Demo limited to ctxlen {ctx_limit}") with gr.Row(): with gr.Column(): context = gr.Textbox(lines=2, label="Context", value='') question = gr.Textbox(lines=2, label="Question", placeholder="") token_count = gr.Slider(10, 300, label="Max Tokens", step=10, value=300) temperature = gr.Slider(0.2, 2.0, label="Temperature", step=0.1, value=1.2) top_p = gr.Slider(0.0, 1.0, label="Top P", step=0.05, value=0.5) presence_penalty = gr.Slider(0.0, 1.0, label="Presence Penalty", step=0.1, value=0.4) count_penalty = gr.Slider(0.0, 1.0, label="Count Penalty", step=0.1, value=0.4) with gr.Column(): with gr.Row(): submit = gr.Button("Submit", variant="primary") clear = gr.Button("Clear", variant="secondary") output = gr.Textbox(label="Output", lines=5) data = gr.Dataset(components=[context, question, token_count, temperature, top_p, presence_penalty, count_penalty], samples=examples, label="Example", headers=["Context", "Question", "Max Tokens", "Temperature", "Top P", "Presence Penalty", "Count Penalty"]) submit.click(evaluate, [context, question, token_count, temperature, top_p, presence_penalty, count_penalty], [output]) clear.click(lambda: None, [], [output]) data.click(lambda x: x, [data], [context, question, token_count, temperature, top_p, presence_penalty, count_penalty]) demo.queue(max_size=10) demo.launch(share=False)