Spaces:
Runtime error
Runtime error
Commit
·
e352af0
1
Parent(s):
65d9dc8
Add app
Browse files- Dockerfile +28 -0
- README.md +1 -0
- app.py +203 -0
- requirements.txt +4 -0
Dockerfile
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.11
|
2 |
+
|
3 |
+
# Set up a new user named "user" with user ID 1000
|
4 |
+
RUN useradd -m -u 1000 user
|
5 |
+
|
6 |
+
# Switch to the "user" user
|
7 |
+
USER user
|
8 |
+
|
9 |
+
# Set home to the user's home directory
|
10 |
+
ENV HOME=/home/user \
|
11 |
+
PATH=/home/user/.local/bin:$PATH
|
12 |
+
|
13 |
+
# Set the working directory to the user's home directory
|
14 |
+
WORKDIR $HOME/app
|
15 |
+
|
16 |
+
# Try and run pip command after setting the user with `USER user` to avoid permission issues with Python
|
17 |
+
RUN pip install --no-cache-dir --upgrade pip
|
18 |
+
|
19 |
+
# Copy the current directory contents into the container at $HOME/app setting the owner to the user
|
20 |
+
COPY --chown=user . $HOME/app
|
21 |
+
|
22 |
+
COPY --chown=user requirements.txt .
|
23 |
+
|
24 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
25 |
+
|
26 |
+
COPY --chown=user app.py app.py
|
27 |
+
|
28 |
+
ENTRYPOINT ["solara", "run", "app.py", "--host=0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
@@ -6,6 +6,7 @@ colorTo: gray
|
|
6 |
sdk: docker
|
7 |
pinned: false
|
8 |
license: mit
|
|
|
9 |
---
|
10 |
|
11 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
6 |
sdk: docker
|
7 |
pinned: false
|
8 |
license: mit
|
9 |
+
app_port: 7860
|
10 |
---
|
11 |
|
12 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import pandas as pd
|
3 |
+
import random
|
4 |
+
import solara
|
5 |
+
import torch
|
6 |
+
import torch.nn.functional as F
|
7 |
+
import ipyvue
|
8 |
+
import reacton
|
9 |
+
from solara.alias import rv as v
|
10 |
+
from typing import Any, Callable, Optional, TypeVar, Union, cast, overload
|
11 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig
|
12 |
+
|
13 |
+
config = AutoConfig.from_pretrained(
|
14 |
+
"replit/replit-code-v1_5-3b",
|
15 |
+
trust_remote_code=True
|
16 |
+
)
|
17 |
+
|
18 |
+
tokenizer = AutoTokenizer.from_pretrained('replit/replit-code-v1_5-3b', trust_remote_code=True)
|
19 |
+
model = AutoModelForCausalLM.from_pretrained('replit/replit-code-v1_5-3b', config=config, trust_remote_code=True)
|
20 |
+
|
21 |
+
def use_change(el: reacton.core.Element, on_value: Callable[[Any], Any], enabled=True):
|
22 |
+
"""Trigger a callback when a blur events occurs or the enter key is pressed."""
|
23 |
+
on_value_ref = solara.use_ref(on_value)
|
24 |
+
on_value_ref.current = on_value
|
25 |
+
|
26 |
+
def add_events():
|
27 |
+
def on_change(widget, event, data):
|
28 |
+
if enabled:
|
29 |
+
on_value_ref.current(widget.v_model)
|
30 |
+
|
31 |
+
widget = cast(ipyvue.VueWidget, solara.get_widget(el))
|
32 |
+
if enabled:
|
33 |
+
widget.on_event("blur", on_change)
|
34 |
+
widget.on_event("keyup.enter", on_change)
|
35 |
+
|
36 |
+
def cleanup():
|
37 |
+
if enabled:
|
38 |
+
widget.on_event("blur", on_change, remove=True)
|
39 |
+
widget.on_event("keyup.enter", on_change, remove=True)
|
40 |
+
|
41 |
+
return cleanup
|
42 |
+
|
43 |
+
solara.use_effect(add_events, [enabled])
|
44 |
+
|
45 |
+
|
46 |
+
@solara.component
|
47 |
+
def InputTextarea(
|
48 |
+
label: str,
|
49 |
+
value: Union[str, solara.Reactive[str]] = "",
|
50 |
+
on_value: Callable[[str], None] = None,
|
51 |
+
disabled: bool = False,
|
52 |
+
password: bool = False,
|
53 |
+
continuous_update: bool = False,
|
54 |
+
error: Union[bool, str] = False,
|
55 |
+
message: Optional[str] = None,
|
56 |
+
):
|
57 |
+
reactive_value = solara.use_reactive(value, on_value)
|
58 |
+
del value, on_value
|
59 |
+
|
60 |
+
def set_value_cast(value):
|
61 |
+
reactive_value.value = str(value)
|
62 |
+
|
63 |
+
def on_v_model(value):
|
64 |
+
if continuous_update:
|
65 |
+
set_value_cast(value)
|
66 |
+
|
67 |
+
messages = []
|
68 |
+
if error and isinstance(error, str):
|
69 |
+
messages.append(error)
|
70 |
+
elif message:
|
71 |
+
messages.append(message)
|
72 |
+
text_area = v.Textarea(
|
73 |
+
v_model=reactive_value.value,
|
74 |
+
on_v_model=on_v_model,
|
75 |
+
label=label,
|
76 |
+
disabled=disabled,
|
77 |
+
type="password" if password else None,
|
78 |
+
error=bool(error),
|
79 |
+
messages=messages,
|
80 |
+
solo=True,
|
81 |
+
hide_details=True,
|
82 |
+
outlined=True,
|
83 |
+
rows=1,
|
84 |
+
auto_grow=True,
|
85 |
+
)
|
86 |
+
use_change(text_area, set_value_cast, enabled=not continuous_update)
|
87 |
+
return text_area
|
88 |
+
|
89 |
+
@solara.component
|
90 |
+
def my_component(tokens, i, color, df):
|
91 |
+
text = tokenizer.decode(tokens[0][i+1])
|
92 |
+
color = solara.use_reactive(f"{color}")
|
93 |
+
text_element = solara.Text(f"{text}", classes=[f"{color.value}"])
|
94 |
+
with solara.lab.ClickMenu(activator=text_element):
|
95 |
+
with solara.Column(gap="0px"):
|
96 |
+
def replace_token(text=text):
|
97 |
+
color.set("mystronggreen")
|
98 |
+
text1.value = f"{tokenizer.decode(tokens[0][1:i+1])}"+f"{df.iloc[1,1]}"+f"{tokenizer.decode(tokens[0][i+2:])}"
|
99 |
+
solara.Button(f"Replace "+ f"'{tokenizer.decode(tokens[0][i+1])}'".replace(" ", "␣")+" by "+f"'{df.iloc[1,1]}'".replace(" ", "␣"), on_click=replace_token, text=True, classes=["mybuttonclass"])
|
100 |
+
def add_token(text=text):
|
101 |
+
color.set("mystronggreen")
|
102 |
+
text1.value = f"{tokenizer.decode(tokens[0][1:i+1])}"+f"{df.iloc[1,1]}"+f"{tokenizer.decode(tokens[0][i+1:])}"
|
103 |
+
solara.Button(f"Add "+f"'{df.iloc[1,1]}'".replace(" ", "␣"), on_click=add_token, text=True, classes=["mybuttonclass"])
|
104 |
+
def delete_token(text=text):
|
105 |
+
color.set("mystronggreen")
|
106 |
+
text1.value = f"{tokenizer.decode(tokens[0][1:i+1])}"+f"{tokenizer.decode(tokens[0][i+2:])}"
|
107 |
+
solara.Button(f"Delete "+f"'{tokenizer.decode(tokens[0][i+1])}'".replace(" ", "␣"), on_click=delete_token, text=True, classes=["mybuttonclass"])
|
108 |
+
def ignore_token(text=text):
|
109 |
+
color.set("mystronggreen")
|
110 |
+
solara.Button("Ignore", on_click=ignore_token, text=True, classes=["mybuttonclass"])
|
111 |
+
|
112 |
+
text1 = solara.reactive("""def HelloWorld():\n print("Hello World)""")
|
113 |
+
@solara.component
|
114 |
+
def Page():
|
115 |
+
with solara.Column(margin="10"):
|
116 |
+
solara.Markdown("#Code Perplexity")
|
117 |
+
solara.Markdown("This is an educational tool where, for any given passage of code, it augments the original code with highlights and annotations that indicate how 'surprising' each token is to the model, as well as which other tokens the model deemed most likely to occur in its place.")
|
118 |
+
css = """
|
119 |
+
.mybuttonclass{
|
120 |
+
text-transform: none !important;
|
121 |
+
}
|
122 |
+
.mystronggreen{
|
123 |
+
background-color:#99ff99;
|
124 |
+
color:black!important;
|
125 |
+
padding:0px;
|
126 |
+
white-space-collapse:preserve;
|
127 |
+
}
|
128 |
+
.mygreen{
|
129 |
+
background-color:#ccffcc;
|
130 |
+
color:black!important;
|
131 |
+
white-space-collapse:preserve;
|
132 |
+
}
|
133 |
+
.myyellow{
|
134 |
+
background-color: #ffff99;
|
135 |
+
color:black!important;
|
136 |
+
white-space-collapse:preserve;
|
137 |
+
}
|
138 |
+
.myorange{
|
139 |
+
background-color: #ffe6cc;
|
140 |
+
color:black!important;
|
141 |
+
white-space-collapse:preserve;
|
142 |
+
}
|
143 |
+
.myred{
|
144 |
+
background-color:#ffcab0;
|
145 |
+
color:black!important;
|
146 |
+
white-space-collapse:preserve;
|
147 |
+
}
|
148 |
+
"""
|
149 |
+
InputTextarea("Enter text and press enter when you're done:", value=text1, continuous_update=True)
|
150 |
+
if text1.value != "":
|
151 |
+
with solara.Column():
|
152 |
+
with solara.Row(gap="0px", justify="left"):
|
153 |
+
tokens = tokenizer.encode(text1.value, return_tensors="pt")
|
154 |
+
tokens = torch.concat((torch.tensor([tokenizer.eos_token_id]), tokens[0])).reshape(1,-1)
|
155 |
+
full_list = []
|
156 |
+
partial_list = []
|
157 |
+
for token in tokens[0]:
|
158 |
+
if token != 216:
|
159 |
+
partial_list.append(token)
|
160 |
+
else:
|
161 |
+
partial_list.append(torch.tensor(216))
|
162 |
+
full_list.append(partial_list)
|
163 |
+
partial_list = []
|
164 |
+
if len(partial_list) != 0:
|
165 |
+
full_list.append(partial_list)
|
166 |
+
tokens = torch.cat((torch.tensor([tokenizer.eos_token_id]), tokens[0])).reshape(1,-1)
|
167 |
+
# tokens = tokens[0].reshape(1,-1)
|
168 |
+
i = 0
|
169 |
+
for j in range(len(full_list)):
|
170 |
+
with solara.Column():
|
171 |
+
with solara.Div(style="display: inline;"):
|
172 |
+
for k in range(len(full_list[j])):
|
173 |
+
outputs = model.generate(tokens[0][:i+1].reshape(1,-1), max_new_tokens=1, output_scores=True, return_dict_in_generate=True, eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.eos_token_id)
|
174 |
+
scores = F.softmax(outputs.scores[0], dim=-1)
|
175 |
+
top_10 = torch.topk(scores, 10)
|
176 |
+
df = pd.DataFrame()
|
177 |
+
a = scores[0][tokens[0][i+1]]
|
178 |
+
b = top_10.values
|
179 |
+
df["probs"] = list(np.concatenate([a.reshape(-1,1).numpy()[0], b[0].numpy()]))
|
180 |
+
diff = 100*(df["probs"].iloc[0]-df["probs"].iloc[1])
|
181 |
+
if np.abs(diff)<1:
|
182 |
+
color = "mystronggreen"
|
183 |
+
elif np.abs(diff)<10:
|
184 |
+
color = "mygreen"
|
185 |
+
elif np.abs(diff)<20:
|
186 |
+
color = "myyellow"
|
187 |
+
elif np.abs(diff)<30:
|
188 |
+
color = "myorange"
|
189 |
+
else:
|
190 |
+
color = "myred"
|
191 |
+
df["probs"] = [f"{value:.2%}" for value in df["probs"].values]
|
192 |
+
aux = [tokenizer.decode(tokens[0][i+1])] + [tokenizer.decode(top_10.indices[0][i]) for i in range(10)]
|
193 |
+
df["predicted next token"] = aux
|
194 |
+
solara_df = solara.DataFrame(df, items_per_page=10)
|
195 |
+
with solara.Tooltip(solara_df, color="white"):
|
196 |
+
solara.Style(css)
|
197 |
+
if full_list[j][k] == 216:
|
198 |
+
solara.Text("↵", classes=[f"{color}"])
|
199 |
+
elif full_list[j][k] == 0:
|
200 |
+
solara.Text("")
|
201 |
+
else:
|
202 |
+
solara.Text(f"{tokenizer.decode(full_list[j][k])}", classes=[f"{color}"])
|
203 |
+
i+=1
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
solara
|
2 |
+
numpy
|
3 |
+
pandas
|
4 |
+
transformers
|