PaulNdrei commited on
Commit
6cba6d8
0 Parent(s):

Initial commit

Browse files
Files changed (7) hide show
  1. .gitignore +5 -0
  2. README.md +11 -0
  3. app.py +198 -0
  4. ginesta_small.jpg +0 -0
  5. handler.py +14 -0
  6. requirements.txt +4 -0
  7. sagemaker_endpoint.py +35 -0
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ venv
2
+ **/__pycache__
3
+ .env
4
+ flagged_data_points
5
+ json_dataset
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Flor 6.3B Inference
3
+ emoji: 馃尭
4
+ colorFrom: green
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 4.8.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
app.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import gradio as gr
4
+ from gradio.components import Textbox, Button, Slider, Checkbox
5
+ from AinaTheme import AinaGradioTheme
6
+ from sagemaker_endpoint import invoke_endpoint
7
+
8
+ load_dotenv()
9
+
10
+ MAX_NEW_TOKENS = int(os.environ.get("MAX_NEW_TOKENS", default=100))
11
+ MAX_INPUT_CHARACTERS= int(os.environ.get("MAX_INPUT_CHARACTERS", default=100))
12
+ SHOW_MODEL_PARAMETERS_IN_UI = os.environ.get("SHOW_MODEL_PARAMETERS_IN_UI", default=True) == "True"
13
+
14
+
15
+ def submit_input(input_, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, num_beams, temperature):
16
+ if input_.strip() == "":
17
+ gr.Warning('Not possible to inference an empty input')
18
+ return None
19
+
20
+ model_parameters = {
21
+ "max_new_tokens": max_new_tokens,
22
+ "repetition_penalty": repetition_penalty,
23
+ "top_k": top_k,
24
+ "top_p": top_p,
25
+ "do_sample": do_sample,
26
+ "num_beams": num_beams,
27
+ "temperature": temperature
28
+ }
29
+
30
+ output = invoke_endpoint(input_, model_parameters=model_parameters)
31
+
32
+
33
+ if output is None:
34
+ gr.Warning('Inference endpoint is not available right now. Please try again later.')
35
+ return output
36
+
37
+ def change_interactive(text):
38
+ if len(text.strip()) > MAX_INPUT_CHARACTERS:
39
+ return gr.update(interactive = True), gr.update(interactive = False)
40
+ return gr.update(interactive = True), gr.update(interactive = True)
41
+
42
+ def clear():
43
+ return (
44
+ None,
45
+ None,
46
+ gr.Slider.update(value=100),
47
+ gr.Slider.update(value=1.2),
48
+ gr.Slider.update(value=50),
49
+ gr.Slider.update(value=0.95),
50
+ gr.Checkbox.update(value=True),
51
+ gr.Slider.update(value=4),
52
+ gr.Slider.update(value=0.5),
53
+ )
54
+
55
+ def gradio_app():
56
+ with gr.Blocks(**AinaGradioTheme().get_kwargs()) as demo:
57
+ with gr.Row():
58
+ with gr.Column(scale=0.1):
59
+ gr.Image("ginesta_small.jpg", elem_id="flor-banner", scale=1, height=256, width=256, show_label=False, show_download_button = False, show_share_button = False)
60
+ with gr.Column():
61
+ gr.Markdown(
62
+ """# Flor-6.3B (experimental)
63
+
64
+ 馃 **[Flor](https://huggingface.co/projecte-aina/FLOR-6.3B)** is a 6.3B parameters multilingual LLM that has been trained on a massive mixture of Spanish, Catalan and English data. It is a new open-source Large Language Model (LLM), licensed for both research and commercial use. It uses the [Bloom-7b](https://huggingface.co/bigscience/bloom-7b1) model as a starting point, a state-of-the-art multilingual language model.
65
+
66
+ 鈿狅笍 **Limitations**: This version is for beta testing only. The content generated by these models is unsupervised and might be judged as inappropriate or offensive. Please bear this in mind when exploring this resource.
67
+
68
+ 馃憖 **Learn more about Flor:** [HF official model card](https://huggingface.co/projecte-aina/FLOR-6.3B) and the [Instruct version](https://huggingface.co/projecte-aina/FLOR_63B_Instruit).
69
+
70
+ """
71
+ )
72
+ with gr.Row( equal_height=False):
73
+ with gr.Column(variant="panel"):
74
+ placeholder_max_token = Textbox(
75
+ visible=False,
76
+ interactive=False,
77
+ value= MAX_INPUT_CHARACTERS
78
+ )
79
+ input_ = Textbox(
80
+ lines=11,
81
+ label="Input",
82
+ placeholder="e.g. El mercat del barri 茅s fant脿stic hi pots trobar."
83
+ )
84
+ with gr.Row(variant="panel", equal_height=True):
85
+ gr.HTML("""<span id="countertext" style="display: flex; justify-content: start; color:#ef4444; font-weight: bold;"></span>""")
86
+ gr.HTML(f"""<span id="counter" style="display: flex; justify-content: end;"> <span id="inputlenght">0</span>&nbsp;/&nbsp;{MAX_INPUT_CHARACTERS}</span>""")
87
+
88
+ with gr.Row(variant="panel"):
89
+ with gr.Accordion("Model parameters", open=False, visible=SHOW_MODEL_PARAMETERS_IN_UI):
90
+ max_new_tokens = Slider(
91
+ minimum=1,
92
+ maximum=200,
93
+ step=1,
94
+ value=MAX_NEW_TOKENS,
95
+ label="Max tokens"
96
+ )
97
+ repetition_penalty = Slider(
98
+ minimum=0.1,
99
+ maximum=10,
100
+ step=0.1,
101
+ value=1.2,
102
+ label="Repetition penalty"
103
+ )
104
+ top_k = Slider(
105
+ minimum=1,
106
+ maximum=100,
107
+ step=1,
108
+ value=50,
109
+ label="Top k"
110
+ )
111
+ top_p = Slider(
112
+ minimum=0.01,
113
+ maximum=0.99,
114
+ value=0.95,
115
+ label="Top p"
116
+ )
117
+ do_sample = Checkbox(
118
+ value=True,
119
+ label="Do sample"
120
+ )
121
+ num_beams = Slider(
122
+ minimum=1,
123
+ maximum=8,
124
+ step=1,
125
+ value=4,
126
+ label="Beams"
127
+ )
128
+ temperature = Slider(
129
+ minimum=0,
130
+ maximum=1,
131
+ value=0.5,
132
+ label="Temperature"
133
+ )
134
+ with gr.Column(variant="panel"):
135
+ output = Textbox(
136
+ lines=11,
137
+ label="Output",
138
+ interactive=False,
139
+ show_copy_button=True
140
+ )
141
+ with gr.Row(variant="panel"):
142
+ clear_btn = Button(
143
+ "Clear",
144
+ )
145
+ submit_btn = Button(
146
+ "Submit",
147
+ variant="primary",
148
+ )
149
+
150
+ with gr.Row():
151
+ with gr.Column(scale=0.5):
152
+ gr.Examples(
153
+ label="Short prompts:",
154
+ examples=[
155
+ ["""La capital de Su猫cia"""],
156
+ ],
157
+ inputs=[input_, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, num_beams, temperature],
158
+ outputs=output,
159
+ fn=submit_input,
160
+ )
161
+
162
+ gr.Examples(
163
+ label="Zero-shot prompts",
164
+ examples=[
165
+ ["Tradueix del Castell脿 al Catal脿 la seg眉ent frase: \"Eso es pan comido.\" \nTraducci贸:"],
166
+ ],
167
+ inputs=[input_, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, num_beams, temperature],
168
+ outputs=output,
169
+ fn=submit_input,
170
+ )
171
+ gr.Examples(
172
+ label="Few-Shot prompts:",
173
+ examples=[
174
+ ["""Oraci贸: Els sons mel貌dics produeixen una sensaci贸 de calma i benestar en l'individu. \nPar脿frasi: La m煤sica 茅s molt relaxant i reconfortant.\n----\nOraci贸: L'animal dom猫stic mostra una gran alegria i satisfacci贸. \nPar脿frasi: El gos 茅s molt feli莽. \n----\nOraci贸: El vehicle es va trencar i vaig haver de contactar amb el servei de remolc perqu猫 el transport茅s. \nPar脿frasi: El cotxe es va trencar i vaig haver de trucar la grua. \n----\nOraci贸: El professor va explicar els conceptes de manera clara i concisa. \nPar脿frasi:"""],
175
+ ],
176
+ inputs=[input_, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, num_beams, temperature],
177
+ outputs=output,
178
+ fn=submit_input,
179
+ )
180
+
181
+
182
+
183
+ input_.change(fn=change_interactive, inputs=[input_], outputs=[clear_btn, submit_btn])
184
+
185
+ input_.change(fn=None, inputs=[input_], js=f"""(i) => document.getElementById('countertext').textContent = i.length > {MAX_INPUT_CHARACTERS} && 'Max length {MAX_INPUT_CHARACTERS} characters. ' || '' """)
186
+
187
+ input_.change(fn=None, inputs=[input_, placeholder_max_token], js="""(i, m) => {
188
+ document.getElementById('inputlenght').textContent = i.length + ' '
189
+ document.getElementById('inputlenght').style.color = (i.length > m) ? "#ef4444" : "";
190
+ }""")
191
+
192
+ clear_btn.click(fn=clear, inputs=[], outputs=[input_, output, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, num_beams, temperature], queue=False)
193
+ submit_btn.click(fn=submit_input, inputs=[input_, max_new_tokens, repetition_penalty, top_k, top_p, do_sample, num_beams, temperature], outputs=[output])
194
+
195
+ demo.launch(show_api=True)
196
+
197
+ if __name__ == "__main__":
198
+ gradio_app()
ginesta_small.jpg ADDED
handler.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ class ContentHandler():
4
+ content_type = "application/json"
5
+ accepts = "application/json"
6
+
7
+ def transform_input(self, prompt: str, model_kwargs: dict) -> bytes:
8
+ input_str = json.dumps({'inputs': prompt, 'parameters': model_kwargs})
9
+ return input_str.encode('utf-8')
10
+
11
+ def transform_output(self, output: bytes) -> str:
12
+ response_json = json.loads(output.read().decode("utf-8"))
13
+ return response_json[0]["generated_text"]
14
+
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ aina-gradio-theme==1.0
2
+ gradio==4.8.0
3
+ python-dotenv==1.0.0
4
+ boto3==1.28.20
sagemaker_endpoint.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from traceback import print_exc
3
+ import boto3
4
+ from handler import ContentHandler
5
+ from dotenv import load_dotenv
6
+
7
+ load_dotenv()
8
+
9
+ endpoint_name = os.environ.get("AWS_ENDPOINT_NAME")
10
+ aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID")
11
+ aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY")
12
+ aws_region_name = os.environ.get("AWS_REGION_NAME")
13
+
14
+ boto_client = boto3.client(
15
+ service_name='sagemaker-runtime',
16
+ aws_access_key_id=aws_access_key_id,
17
+ aws_secret_access_key=aws_secret_access_key,
18
+ region_name=aws_region_name)
19
+
20
+ content_handler = ContentHandler()
21
+
22
+ def invoke_endpoint(
23
+ input_,
24
+ model_parameters,
25
+ ):
26
+ try:
27
+ response = boto_client.invoke_endpoint(
28
+ EndpointName=endpoint_name,
29
+ ContentType='application/json',
30
+ Body=content_handler.transform_input(prompt=input_, model_kwargs=model_parameters)
31
+ )
32
+ return content_handler.transform_output(response['Body'])
33
+ except:
34
+ print_exc()
35
+ return None