loubnabnl HF staff commited on
Commit
b061e46
β€’
1 Parent(s): ccabd7d

Create app_threading.py

Browse files
Files changed (1) hide show
  1. app_threading.py +208 -0
app_threading.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import pandas as pd
4
+ import requests
5
+ import threading
6
+ import streamlit as st
7
+ from datasets import load_dataset, load_metric
8
+
9
+ MODELS = ["CodeParrot", "InCoder", "CodeGen", "PolyCoder"]
10
+ GENERATION_MODELS = ["CodeParrot", "InCoder", "CodeGen"]
11
+
12
+
13
+ @st.cache()
14
+ def load_examples():
15
+ with open("utils/examples.json", "r") as f:
16
+ examples = json.load(f)
17
+ return examples
18
+
19
+
20
+ def load_evaluation():
21
+ # load task 2 of HumanEval and code_eval_metric
22
+ os.environ["HF_ALLOW_CODE_EVAL"] = "1"
23
+ human_eval = load_dataset("openai_humaneval")
24
+ entry_point = f"check({human_eval['test'][2]['entry_point']})"
25
+ test_func = "\n" + human_eval["test"][2]["test"] + "\n" + entry_point
26
+ code_eval = load_metric("code_eval")
27
+ return code_eval, test_func
28
+
29
+
30
+ def read_markdown(path):
31
+ with open(path, "r") as f:
32
+ output = f.read()
33
+ st.markdown(output, unsafe_allow_html=True)
34
+
35
+
36
+ def generate_code(
37
+ generations, model_name, gen_prompt, max_new_tokens, temperature, seed
38
+ ):
39
+ # call space using its API endpoint
40
+ url = (
41
+ f"https://hf.space/embed/loubnabnl/{model_name.lower()}-subspace/+/api/predict/"
42
+ )
43
+ r = requests.post(
44
+ url=url, json={"data": [gen_prompt, max_new_tokens, temperature, seed]}
45
+ )
46
+ generated_text = r.json()["data"][0]
47
+ generations.append(generated_text)
48
+
49
+
50
+ def generate_code_threads(
51
+ generations, models, gen_prompt, max_new_tokens, temperature, seed
52
+ ):
53
+ threads = []
54
+ for model_name in models:
55
+ # create the thread
56
+ threads.append(
57
+ threading.Thread(
58
+ target=generate_code,
59
+ args=(
60
+ generations,
61
+ model_name,
62
+ gen_prompt,
63
+ max_new_tokens,
64
+ temperature,
65
+ seed,
66
+ ),
67
+ )
68
+ )
69
+ threads[-1].start()
70
+
71
+ for t in threads:
72
+ t.join()
73
+
74
+ @st.cache(show_spinner=False)
75
+ def generate_teaser(gen_prompt):
76
+ generations = []
77
+ generate_code(generations, "CodeGen", gen_prompt, 10, 0.2, 42)
78
+ return generations[0]
79
+
80
+ st.set_page_config(page_icon=":laptop:", layout="wide")
81
+ with open("utils/table_contents.md", "r") as f:
82
+ contents = f.read()
83
+
84
+ st.sidebar.markdown(contents)
85
+
86
+ # Introduction
87
+ st.title("Code generation with πŸ€—")
88
+ read_markdown("utils/summary.md")
89
+ ## teaser
90
+ example_text = "def print_hello_world():"
91
+ col1, col2, col3 = st.columns([1, 2, 1])
92
+ with col2:
93
+ gen_prompt = st.text_area(
94
+ "",
95
+ value=example_text,
96
+ height=100,
97
+ ).strip()
98
+ if st.button("Generate code!", key=1):
99
+ with st.spinner("Generating code..."):
100
+ st.code(generate_teaser(gen_prompt))
101
+ read_markdown("utils/intro.md")
102
+
103
+ # Code datasets
104
+ st.subheader("1 - Code datasets")
105
+ read_markdown("datasets/intro.md")
106
+ read_markdown("datasets/github_code.md")
107
+ col1, col2 = st.columns([1, 2])
108
+ with col1:
109
+ selected_model = st.selectbox("", MODELS, key=1)
110
+ read_markdown(f"datasets/{selected_model.lower()}.md")
111
+
112
+
113
+ # Model architecture
114
+ st.subheader("2 - Model architecture")
115
+ read_markdown("architectures/intro.md")
116
+ col1, col2 = st.columns([1, 2])
117
+ with col1:
118
+ selected_model = st.selectbox("", MODELS, key=2)
119
+ read_markdown(f"architectures/{selected_model.lower()}.md")
120
+
121
+ # Model evaluation
122
+ st.subheader("3 - Code model evaluation")
123
+ read_markdown("evaluation/intro.md")
124
+ read_markdown("evaluation/demo_humaneval.md")
125
+ ## quiz
126
+ st.markdown("Below you can try solving this problem or visualize the solution of CodeParrot:")
127
+ with open("evaluation/problem.md", "r") as f:
128
+ problem = f.read()
129
+ with open("evaluation/solution.md", "r") as f:
130
+ solution = f.read()
131
+
132
+ candidate_solution = st.text_area(
133
+ "Complete the problem:",
134
+ value=problem,
135
+ height=240,
136
+ ).strip()
137
+ if st.button("Test my solution", key=2):
138
+ with st.spinner("Testing..."):
139
+ code_eval, test_func = load_evaluation()
140
+ test_cases = [test_func]
141
+ candidates = [[candidate_solution]]
142
+ pass_at_k, _ = code_eval.compute(references=test_cases, predictions=candidates)
143
+ text = "Your solution didn't pass the test, pass@1 is 0 πŸ˜•" if pass_at_k['pass@1'] < 1 else "Congrats your pass@1 is 1! πŸŽ‰"
144
+ st.markdown(text)
145
+ if st.button("Show model solution", key=3):
146
+ st.markdown(solution)
147
+
148
+ # Code generation
149
+ st.subheader("4 - Code generation ✨")
150
+ read_markdown("generation/intro.md")
151
+ col1, col2, col3 = st.columns([7, 1, 6])
152
+ with col1:
153
+ st.markdown("**Models**")
154
+ selected_models = st.multiselect(
155
+ "Select code generation models to compare:",
156
+ GENERATION_MODELS,
157
+ default=GENERATION_MODELS,
158
+ key=3,
159
+ )
160
+ st.markdown(" ")
161
+ st.markdown("**Examples**")
162
+ examples = load_examples()
163
+ example_names = [example["name"] for example in examples]
164
+ name2id = dict([(name, i) for i, name in enumerate(example_names)])
165
+ selected_example = st.selectbox(
166
+ "Select one of the following examples or implement yours:", example_names
167
+ )
168
+ example_text = examples[name2id[selected_example]]["value"]
169
+ default_length = examples[name2id[selected_example]]["length"]
170
+ with col3:
171
+ st.markdown("**Generation settings**")
172
+ temperature = st.slider(
173
+ "Temperature:", value=0.2, min_value=0.0, step=0.1, max_value=2.0
174
+ )
175
+ max_new_tokens = st.slider(
176
+ "Number of tokens to generate:",
177
+ value=default_length,
178
+ min_value=8,
179
+ step=4,
180
+ max_value=256,
181
+ )
182
+ seed = st.slider("Random seed:", value=42, min_value=0, step=1, max_value=1000)
183
+ gen_prompt = st.text_area(
184
+ "Generate code with prompt:",
185
+ value=example_text,
186
+ height=200,
187
+ ).strip()
188
+ if st.button("Generate code!", key=4):
189
+ with st.spinner("Generating code..."):
190
+ # use threading
191
+ generations = []
192
+ generate_code_threads(
193
+ generations,
194
+ selected_models,
195
+ gen_prompt=gen_prompt,
196
+ max_new_tokens=max_new_tokens,
197
+ temperature=temperature,
198
+ seed=seed,
199
+ )
200
+ for i in range(len(generations)):
201
+ st.markdown(f"**{selected_models[i]}**")
202
+ st.code(generations[i])
203
+ if len(generations) < len(selected_models):
204
+ st.markdown("<span style='color:red'>Warning: Some models run into timeout, you can try generating code using the original subspaces: [InCoder](https://huggingface.co/spaces/loubnabnl/incoder-subspace), [CodeGen](https://huggingface.co/spaces/loubnabnl/codegen-subspace), [CodeParrot](https://huggingface.co/spaces/loubnabnl/codeparrot-subspace)</span>", unsafe_allow_html=True)
205
+
206
+ # Resources
207
+ st.subheader("Resources")
208
+ read_markdown("utils/resources.md")