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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 4 |
+
from transformers import DynamicCache
|
| 5 |
+
|
| 6 |
+
USE_GPU = torch.cuda.is_available()
|
| 7 |
+
|
| 8 |
+
API_SERVER = "https://tools.kenarnold.org/api"
|
| 9 |
+
|
| 10 |
+
@st.cache_resource
|
| 11 |
+
def load_model():
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
model_name = 'google/gemma-2-9b-it'
|
| 15 |
+
|
| 16 |
+
dtype = torch.bfloat16 if USE_GPU else torch.float16
|
| 17 |
+
|
| 18 |
+
llm = {
|
| 19 |
+
'tokenizer': AutoTokenizer.from_pretrained(model_name),
|
| 20 |
+
'model': AutoModelForCausalLM.from_pretrained(
|
| 21 |
+
model_name,
|
| 22 |
+
device_map="auto" if USE_GPU else "cpu",
|
| 23 |
+
torch_dtype=dtype,
|
| 24 |
+
attn_implementation='eager'
|
| 25 |
+
)
|
| 26 |
+
}
|
| 27 |
+
llm['model'].eval()
|
| 28 |
+
return llm
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def type_assistant_response():
|
| 33 |
+
if 'messages' not in st.session_state or st.button("Start a new conversation"):
|
| 34 |
+
st.session_state['messages'] = [{"role": "user", "content": ""}]
|
| 35 |
+
st.session_state['msg_in_progress'] = ""
|
| 36 |
+
messages = st.session_state.messages
|
| 37 |
+
|
| 38 |
+
def rewind_to(i):
|
| 39 |
+
st.session_state.messages = st.session_state.messages[:i+1]
|
| 40 |
+
st.session_state['msg_in_progress'] = st.session_state.messages[-1]['content']
|
| 41 |
+
|
| 42 |
+
for i, message in enumerate(st.session_state.messages[:-1]):
|
| 43 |
+
with st.chat_message(message["role"]):
|
| 44 |
+
st.markdown(message["content"])
|
| 45 |
+
st.button("Edit", on_click=rewind_to, args=(i,), key=f"rewind_to_{i}")
|
| 46 |
+
|
| 47 |
+
# Display message-in-progress in chat message container
|
| 48 |
+
last_role = messages[-1]["role"]
|
| 49 |
+
with st.chat_message(last_role):
|
| 50 |
+
label = "Your message" if last_role == "user" else "Assistant response"
|
| 51 |
+
msg_in_progress = st.text_area(label, placeholder="Clicking the buttons below will update this field. You can also edit it directly; press Ctrl+Enter to apply changes.", height=300, key="msg_in_progress")
|
| 52 |
+
if msg_in_progress is None:
|
| 53 |
+
msg_in_progress = ""
|
| 54 |
+
|
| 55 |
+
messages[-1]['content'] = msg_in_progress
|
| 56 |
+
|
| 57 |
+
def append_token(word):
|
| 58 |
+
messages[-1]['content'] = st.session_state['msg_in_progress'] = (
|
| 59 |
+
msg_in_progress + word
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
allow_multi_word = st.checkbox("Allow multi-word predictions", value=False)
|
| 63 |
+
|
| 64 |
+
response = continue_messages(
|
| 65 |
+
messages=messages,
|
| 66 |
+
n_branch_tokens=5,
|
| 67 |
+
n_future_tokens=2
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
continuations = response['continuations']
|
| 71 |
+
for i, (col, continuation) in enumerate(zip(st.columns(len(continuations)), continuations)):
|
| 72 |
+
token = continuation['doc_text']
|
| 73 |
+
with col:
|
| 74 |
+
if not allow_multi_word and ' ' in token[1:]:
|
| 75 |
+
token = token[0] + token[1:].split(' ', 1)[0]
|
| 76 |
+
|
| 77 |
+
# if not allow_multi_word:
|
| 78 |
+
# import re
|
| 79 |
+
# split_result = re.split(r'(\s+)', token, maxsplit=1)
|
| 80 |
+
# assert len(split_result) == 3
|
| 81 |
+
# before_ws, token, after_ws = split_result
|
| 82 |
+
# print(repr(split_result))
|
| 83 |
+
# if before_ws != '':
|
| 84 |
+
# token = before_ws
|
| 85 |
+
token_display = show_token(token)
|
| 86 |
+
st.button(token_display, on_click=append_token, args=(token,), key=i, use_container_width=True)
|
| 87 |
+
|
| 88 |
+
def send_message():
|
| 89 |
+
other_role = "assistant" if last_role == "user" else "user"
|
| 90 |
+
st.session_state['messages'].append({"role": other_role, "content": ""})
|
| 91 |
+
st.session_state['msg_in_progress'] = ""
|
| 92 |
+
st.button("Send", on_click=send_message)
|
| 93 |
+
|
| 94 |
+
def show_token(token: str, escape_markdown=True) -> str:
|
| 95 |
+
token_display = token.replace('\n', '↵').replace('\t', '⇥')
|
| 96 |
+
if escape_markdown:
|
| 97 |
+
for c in "\\`*_{}[]()#+-.!":
|
| 98 |
+
token_display = token_display.replace(c, "\\" + c)
|
| 99 |
+
return token_display
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def continue_messages(messages, n_branch_tokens, n_future_tokens):
|
| 103 |
+
|
| 104 |
+
messages = [{"role": m.role, "content": m.content} for m in messages]
|
| 105 |
+
if len(messages) == 0:
|
| 106 |
+
raise ValueError("At least one message must be provided.")
|
| 107 |
+
|
| 108 |
+
llm = load_model()
|
| 109 |
+
model = llm['model']
|
| 110 |
+
tokenizer = llm['tokenizer']
|
| 111 |
+
|
| 112 |
+
generated_docs = continue_messages_inner(model, tokenizer, messages, n_branch_tokens, n_future_tokens)
|
| 113 |
+
|
| 114 |
+
return {
|
| 115 |
+
'continuations': [dict(doc_text=doc) for doc in generated_docs]
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def get_lookahead_sequences(model, tokenizer, hypotheses, n_branch_tokens, device):
|
| 120 |
+
"""
|
| 121 |
+
For each of the n_branch_tokens next tokens, generate most-likely next tokens and append back on.
|
| 122 |
+
"""
|
| 123 |
+
assert len(hypotheses.shape) == 2
|
| 124 |
+
assert hypotheses.shape[0] == 1
|
| 125 |
+
n_tokens_so_far = hypotheses.shape[1]
|
| 126 |
+
past_key_values = DynamicCache()
|
| 127 |
+
|
| 128 |
+
with torch.no_grad():
|
| 129 |
+
model_outs_onestep = model(hypotheses, output_hidden_states=True, past_key_values=past_key_values)
|
| 130 |
+
|
| 131 |
+
branch_tokens = model_outs_onestep.logits[0, -1].topk(n_branch_tokens).indices
|
| 132 |
+
|
| 133 |
+
# split the cache into n_branch_tokens reps. We pretend we're doing a "Beam search"...
|
| 134 |
+
past_key_values.reorder_cache(torch.zeros((n_branch_tokens,), dtype=torch.long, device=device))
|
| 135 |
+
|
| 136 |
+
# Now call the model again, passing the kv cache, so we can continue generating.
|
| 137 |
+
# Each of the n_branch_tokens next tokens will be considered as one sequence in a "batch".
|
| 138 |
+
next_tokens_as_batch = branch_tokens.unsqueeze(1)
|
| 139 |
+
assert next_tokens_as_batch.shape == (n_branch_tokens, 1)
|
| 140 |
+
|
| 141 |
+
position_id_for_final_token = n_tokens_so_far
|
| 142 |
+
cache_position = torch.full((1,), position_id_for_final_token, dtype=int, device=device)
|
| 143 |
+
with torch.no_grad():
|
| 144 |
+
model_outs = model(
|
| 145 |
+
next_tokens_as_batch,
|
| 146 |
+
past_key_values=past_key_values,
|
| 147 |
+
output_hidden_states=True,
|
| 148 |
+
use_cache=True,
|
| 149 |
+
# the cache surprisingly doesn't know the position of the last token
|
| 150 |
+
cache_position=cache_position
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Grab the single most likely token from each of the n_branch_tokens sequences
|
| 154 |
+
next_token_logits = model_outs.logits[:, -1]
|
| 155 |
+
vocab_size = model.config.vocab_size
|
| 156 |
+
assert next_token_logits.shape == (n_branch_tokens, vocab_size), f"{next_token_logits.shape=}, {n_branch_tokens=}, {vocab_size=}"
|
| 157 |
+
most_likely_token_ids = next_token_logits.argmax(dim=-1)
|
| 158 |
+
|
| 159 |
+
# Stick them at the end of the branch tokens.
|
| 160 |
+
assert most_likely_token_ids.shape == (n_branch_tokens,)
|
| 161 |
+
lookahead_sequences = torch.cat([
|
| 162 |
+
branch_tokens.unsqueeze(1),
|
| 163 |
+
most_likely_token_ids.unsqueeze(1)
|
| 164 |
+
], dim=1)
|
| 165 |
+
assert lookahead_sequences.shape == (n_branch_tokens, 2)
|
| 166 |
+
return lookahead_sequences, next_token_logits
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def continue_messages_inner(model, tokenizer, messages, n_branch_tokens, n_future_tokens):
|
| 170 |
+
# Note: we're ignoring n_future_tokens right now since the old implementation was buggy.
|
| 171 |
+
device = model.device
|
| 172 |
+
|
| 173 |
+
tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, return_tensors="pt", continue_final_message=True).to(model.device)
|
| 174 |
+
print(tokenizer.batch_decode(tokenized_chat, skip_special_tokens=False))
|
| 175 |
+
|
| 176 |
+
lookahead_sequences, next_token_logits = get_lookahead_sequences(
|
| 177 |
+
model, tokenizer, tokenized_chat, n_branch_tokens, device)
|
| 178 |
+
|
| 179 |
+
generated_docs = tokenizer.batch_decode(lookahead_sequences, skip_special_tokens=True)
|
| 180 |
+
return generated_docs
|
| 181 |
+
|
| 182 |
+
type_assistant_response()
|
| 183 |
+
|