learn / app.py
aresspark's picture
Update app.py
2c59972
Raw History Blame Contribute Delete
12.3 kB
# !/usr/bin/env python3
"""
==== No Bugs in code, just some Random Unexpected FEATURES ====
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”โ”‚
โ”‚โ”‚Escโ”‚!1 โ”‚@2 โ”‚#3 โ”‚$4 โ”‚%5 โ”‚^6 โ”‚&7 โ”‚*8 โ”‚(9 โ”‚)0 โ”‚_- โ”‚+= โ”‚|\ โ”‚`~ โ”‚โ”‚
โ”‚โ”œโ”€โ”€โ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”€โ”€โ”คโ”‚
โ”‚โ”‚ Tab โ”‚ Q โ”‚ W โ”‚ E โ”‚ R โ”‚ T โ”‚ Y โ”‚ U โ”‚ I โ”‚ O โ”‚ P โ”‚{[ โ”‚}] โ”‚ BS โ”‚โ”‚
โ”‚โ”œโ”€โ”€โ”€โ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”คโ”‚
โ”‚โ”‚ Ctrl โ”‚ A โ”‚ S โ”‚ D โ”‚ F โ”‚ G โ”‚ H โ”‚ J โ”‚ K โ”‚ L โ”‚: ;โ”‚" 'โ”‚ Enter โ”‚โ”‚
โ”‚โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”ฌโ”€โ”ดโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”คโ”‚
โ”‚โ”‚ Shift โ”‚ Z โ”‚ X โ”‚ C โ”‚ V โ”‚ B โ”‚ N โ”‚ M โ”‚< ,โ”‚> .โ”‚? /โ”‚Shift โ”‚Fn โ”‚โ”‚
โ”‚โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”€โ”€โ”ฌโ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”ฌโ”ดโ”€โ”€โ”€โ”ดโ”ฌโ”€โ”€โ”ดโ”ฌโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜โ”‚
โ”‚ โ”‚Fn โ”‚ Alt โ”‚ Space โ”‚ Alt โ”‚Winโ”‚ HHKB โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜ โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
web็ซฏๆต‹่ฏ•LLMๆ•ˆๆžœใ€‚
Author: pankeyu
Date: 2023/03/17
"""
import os
import re
import time
import json
import datetime
import torch
import streamlit as st
import pandas as pd
from transformers import AutoTokenizer, AutoModel
torch.set_default_tensor_type(torch.cuda.HalfTensor)
st.set_page_config(
page_title="LLM Playground",
layout="wide"
)
device = 'cuda:0'
max_new_tokens = 300
model_path = "checkpoints/model_1000"
LOG_PATH = 'log'
DATASET_PATH = 'data'
LOG_FILE = 'web_log.log'
FEEDBACK_FILE = 'human_feedback.log'
DATASET_FILE = 'dataset.jsonl'
if not os.path.exists(DATASET_PATH):
os.makedirs(DATASET_PATH)
if not os.path.exists(LOG_PATH):
os.makedirs(LOG_PATH)
if not os.path.exists(os.path.join(DATASET_PATH, DATASET_FILE)):
with open(os.path.join(DATASET_PATH, DATASET_FILE), 'w', encoding='utf8') as f:
print('ๆ ‡ๆณจๆ•ฐๆฎ้›†ๅทฒๅˆ›ๅปบใ€‚')
if 'model_out' not in st.session_state:
st.session_state['model_out'] = ''
st.session_state['used_time'] = 0.0
if 'model' not in st.session_state:
with st.spinner('Loading Model...'):
tokenizer = AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True
)
model = AutoModel.from_pretrained(
model_path,
trust_remote_code=True
).half().to(device)
st.session_state['model'] = model
st.session_state['tokenizer'] = tokenizer
def start_evaluate_page():
"""
ๆจกๅž‹ๆต‹่ฏ•้กต้ขใ€‚
"""
c1, c2 = st.columns([5, 5])
with c1:
with st.expander('โš™๏ธ Instruct ่ฎพๅฎš๏ผˆInstruct Setting๏ผ‰', expanded=True):
instruct = st.text_area(
f'Instruct',
value='ไฝ ็Žฐๅœจๆ˜ฏไธ€ไธชๅพˆๅމๅฎณ็š„้˜…่ฏป็†่งฃๅ™จ๏ผŒไธฅๆ ผๆŒ‰็…งไบบ็ฑปๆŒ‡ไปค่ฟ›่กŒๅ›ž็ญ”ใ€‚',
height=250
)
with c2:
with st.expander('๐Ÿ’ฌ ๅฏน่ฏ่พ“ๅ…ฅๆก†', expanded=True):
current_input = st.text_area(
'ๅฝ“ๅ‰็”จๆˆท่พ“ๅ…ฅ',
value='ๅธฎๆˆ‘ๆๅ–ๅ‡บไธ‹้ขๅฅๅญไธญๆ‰€ๆœ‰็š„SPO๏ผŒๅนถ่พ“ๅ‡บไธบjson๏ผŒไธ่ฆๅšๅคšไฝ™็š„ๅ›žๅค๏ผš\n\nใ€Š็…็Šๆฆœใ€‹ๆ˜ฏ็”ฑๅฑฑไธœๅฝฑ่ง†ไผ ๅช’้›†ๅ›ขใ€ๅฑฑไธœๅฝฑ่ง†ๅˆถไฝœๆœ‰้™ๅ…ฌๅธใ€ๅŒ—ไบฌๅ„’ๆ„ๆฌฃๆฌฃๅฝฑไธšๆŠ•่ต„ๆœ‰้™ๅ…ฌๅธใ€ๅŒ—ไบฌๅ’Œ้ข‚ๅคฉๅœฐๅฝฑ่ง†ๆ–‡ๅŒ–ๆœ‰้™ๅ…ฌๅธใ€ๅŒ—ไบฌๅœฃๅŸบๅฝฑไธšๆœ‰้™ๅ…ฌๅธใ€ไธœ้˜ณๆญฃๅˆ้˜ณๅ…‰ๅฝฑ่ง†ๆœ‰้™ๅ…ฌๅธ่”ๅˆๅ‡บๅ“๏ผŒ็”ฑๅญ”็ฌ™ใ€ๆŽ้›ชๆ‰งๅฏผ๏ผŒ่ƒกๆญŒใ€ๅˆ˜ๆถ›ใ€็Ž‹ๅ‡ฏใ€้ป„็ปดๅพทใ€้™ˆ้พ™ใ€ๅด็ฃŠใ€้ซ˜้‘ซ็ญ‰ไธปๆผ”็š„ๅค่ฃ…ๅ‰งใ€‚',
height=200
)
bt = st.button('Generate')
if bt:
start = time.time()
with st.spinner('็”Ÿๆˆไธญ...'):
with torch.no_grad():
input_text = f"Instruction: {instruct}\n"
input_text += f"Input: {current_input}\n"
input_text += f"Answer:"
batch = st.session_state['tokenizer'](input_text, return_tensors="pt")
out = st.session_state['model'].generate(
input_ids=batch["input_ids"].to(device),
max_new_tokens=max_new_tokens,
temperature=0
)
out_text = st.session_state['tokenizer'].decode(out[0])
answer = out_text.split('Answer: ')[-1]
used_time = round(time.time() - start, 2)
st.session_state['model_out'] = answer
st.session_state['used_time'] = used_time
with open(os.path.join(LOG_PATH, LOG_FILE), 'a', encoding='utf8') as f:
log_dict = {
'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'used_seconds': used_time,
'instruct': instruct,
'input': current_input,
'model_output': st.session_state['model_out']
}
f.write(f'{json.dumps(log_dict, ensure_ascii=False)}\n')
if st.session_state['model_out']:
c1, c2 = st.columns([5, 5])
with c2:
with st.expander(f"๐Ÿค– ๅฝ“ๅ‰ๆจกๅž‹่พ“ๅ‡บ๏ผˆ{st.session_state['used_time']}s๏ผ‰", expanded=True):
answer = st.session_state['model_out']
if len(answer) < 200:
height = 100
elif len(answer) < 500:
height = 200
else:
height = 300
st.text_area(
'',
value=f'{answer}',
height=height
)
human_feedback = st.radio(
"ๆจกๅž‹็”Ÿๆˆ็ป“ๆžœๆ˜ฏๅฆๆญฃ็กฎ ๐Ÿ‘‡",
["๐Ÿค“ ไธๅ้ฆˆ", "๐Ÿ˜Š ๆญฃ็กฎ", "๐Ÿ˜ก ้”™่ฏฏ"],
key="visibility",
horizontal=True
)
if human_feedback in ["๐Ÿ˜ก ้”™่ฏฏ", "๐Ÿ˜Š ๆญฃ็กฎ"]:
if human_feedback == "๐Ÿ˜ก ้”™่ฏฏ":
error_feedback = st.text_area(
'[error feedback]',
placeholder='ๆ„Ÿ่ฐขๆ‚จ็š„ๅ้ฆˆ๏ผŒ่ฏทๅกซๅ†™้—ฎ้ข˜็š„ๆญฃ็กฎ็ญ”ๆกˆไปฅๅธฎๅŠฉๆจกๅž‹ๆ”น่ฟ› ๐Ÿฅบ'
)
current_feedback = {
'instruct': instruct,
'input': current_input,
'model_output': st.session_state['model_out'],
'human_feedback': error_feedback,
'is_error': True
}
else:
advice = st.text_area(
'[advice feedback]',
placeholder='่ฏท่พ“ๅ…ฅๆ‚จ็š„ๅ้ฆˆ...'
)
current_feedback = {
'instruct': instruct,
'input': current_input,
'model_output': st.session_state['model_out'],
'human_feedback': advice,
'is_error': False
}
submit_button = st.button('ๆไบค')
if submit_button:
with open(os.path.join(LOG_PATH, FEEDBACK_FILE), 'a', encoding='utf8') as f:
f.write(f'{json.dumps(current_feedback, ensure_ascii=False)}\n')
st.success('ๆ„Ÿ่ฐขๆ‚จ็š„ๅ้ฆˆ~', icon="โœ…")
with c1:
with st.expander(f'๐Ÿ’ป json ่งฃๆž็ป“ๆžœ', expanded=True):
st.markdown(answer)
json_res = re.findall(r'```json(.*)```', answer.replace('\n', ''))
if len(json_res):
json_res = json_res[0]
try:
json_res = json.loads(json_res)
st.write(json_res)
except:
pass
def read_dataset_file():
"""
่ฏปๅ–ๆœฌๅœฐๆ ‡ๆณจ็š„ๆ•ฐๆฎ้›†ใ€‚
"""
temp_dict = {}
with open(os.path.join(DATASET_PATH, DATASET_FILE), 'r', encoding='utf8') as f:
for line in f.readlines():
line = json.loads(line)
for key, value in line.items():
if key not in temp_dict:
temp_dict[key] = []
temp_dict[key].append(value)
df = pd.DataFrame.from_dict(temp_dict)
return df
def start_label_page():
"""
ๆ•ฐๆฎ้›†ๆ ‡ๆณจ้กต้ขใ€‚
"""
c1, c2 = st.columns([4, 6])
with c1:
with st.expander(f'๐Ÿ’ป ๆ ‡ๆณจ็•Œ้ข', expanded=True):
instruct = st.text_area(
'Human Instruct',
value='ไฝ ็Žฐๅœจๆ˜ฏไธ€ไธชๅพˆๅމๅฎณ็š„้˜…่ฏป็†่งฃๅ™จ๏ผŒไธฅๆ ผๆŒ‰็…งไบบ็ฑปๆŒ‡ไปค่ฟ›่กŒๅ›ž็ญ”ใ€‚'
)
inputs = st.text_area(
'Human Input',
placeholder='่พ“ๅ…ฅไบบๅทฅๆž„้€ ้—ฎ้ข˜๏ผŒไพ‹ๅฆ‚: ๅธฎๆˆ‘ๆŠฝๅ–ไธ‹้ขๅฅๅญ็š„SPO๏ผŒ็”จjsonๆ ผๅผ่ฟ”ๅ›ž...'
)
answer = st.text_area(
'Human Output',
placeholder='่พ“ๅ…ฅไบบๅทฅๆž„้€ ็ญ”ๆกˆ๏ผŒไพ‹ๅฆ‚:\n ๅฅฝ็š„๏ผŒไปฅไธ‹ๆ˜ฏๆŠฝๅ–SPO็š„jsonไฟกๆฏ๏ผš\n```json\n{\n"subject": "ๅญ™็บข้›ท", \n"predicate": "ๅนด้พ„", \n"object": "52ๅฒ"\n}\n```',
height=500
)
save_button = st.button('Save')
if save_button:
with open(os.path.join(DATASET_PATH, DATASET_FILE), 'a', encoding='utf8') as f:
context = f'Instruction: {instruct}\nInput: {inputs}\nAnswer: '
current_sample = {
'context': context,
'target': answer
}
f.write(json.dumps(current_sample, ensure_ascii=False) + '\n')
st.success('ๆ•ฐๆฎๅทฒไฟๅญ˜๏ผ', icon="โœ…")
st.session_state['dataset_df'] = read_dataset_file()
with c2:
if 'dataset_df' not in st.session_state:
st.session_state['dataset_df'] = read_dataset_file()
with st.expander(f"๐Ÿ“š ๆœฌๅœฐๆ•ฐๆฎ้›†๏ผˆๅ…ฑ {len(st.session_state['dataset_df'])} ๆก๏ผ‰", expanded=True):
st.dataframe(st.session_state['dataset_df'], height=820)
refresh_button = st.button('ๅˆทๆ–ฐๆ•ฐๆฎ้›†')
if refresh_button:
st.session_state['dataset_df'] = read_dataset_file()
def main():
"""
ไธปๅ‡ฝๆ•ฐๆต็จ‹ใ€‚
"""
logo = '[![Typing SVG](https://readme-typing-svg.demolab.com?font=Fira+Code&duration=500&pause=500&color=00E455&center=true&vCenter=true&multiline=true&repeat=false&width=700&height=50&lines=LLM%EF%BC%88Large+Language+Model%EF%BC%89Playground+-+Enjoy++(%EF%BC%BE%EF%BC%B5%EF%BC%BE)%E3%83%8E)](https://github.com/HarderThenHarder/transformers_tasks)'
st.markdown(logo)
evaluate_page, label_page = st.tabs(['evaluate_page', 'label_page'])
with evaluate_page:
start_evaluate_page()
with label_page:
start_label_page()
if __name__ == '__main__':
main()