File size: 11,391 Bytes
0ccf025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935aa5b
0ccf025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935aa5b
 
 
 
 
0ccf025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a51399
0ccf025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import os
import gradio as gr
from gradio.components import Slider
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
import torch

# Model, information and examples ----------------------------------------------
MODEL_NAMES = ["Carballo-bloom-1.3B","Carvalho_pt-gl","Carballo-cerebras-1.3B"]
markdown_description_gl = """
[*English below*]

Este espazo contén diferentes Grandes Modelos da Linguaxe feitos para o galego desenvolvidos polo [Proxecto Nós](https://nos.gal/en/proxecto-nos).

💐 **[Carballo-bloom-1.3B](https://huggingface.co/proxectonos/Carballo-bloom-1.3B)** é un modelo de 1.3B parámetros que é un preadestramento continuo de [FLOR-1.3B]( https://huggingface.co/projecte-aina/FLOR-1.3B), baseado a súa vez en [Bloom 1.7B](https://huggingface.co/bigscience/bloom-1b7).

🧠 **[Carballo-cerebras-1.3B](https://huggingface.co/proxectonos/Carballo-cerebras-1.3B)** é un modelo de 1.3B parámetros baseado en [Cerebras-GPT 1.3B](https://huggingface.co/cerebras/Cerebras-GPT-1.3B).

📖 **[Carvalho_pt-gl](https://huggingface.co/Nos-PT/Carvalho_pt-gl-1.3B)** é un modelo de 1.3B parámetros baseado en [Cerebras-GPT 1.3B](https://huggingface.co/cerebras/Cerebras-GPT-1.3B) que pode traballar en galego e portugués, feito en colaboración co [VISTA Lab](https://www.uevora.pt/en/research/R-D-Unit/vista-lab) da Universidade de Évora.
"""

markdown_description_en = """
## English description
This space contains the Galician language models developed by [Proxecto Nós](https://nos.gal/en/proxecto-nos).

💐 **[Carballo-bloom-1.3B](https://huggingface.co/proxectonos/Carballo-bloom-1.3B)** is a 1.3B parameters model which is a Continual pretraining from [FLOR-1.3B](https://huggingface.co/projecte-aina/FLOR-1.3B), which is based in [Bloom 1.7B](https://huggingface.co/bigscience/bloom-1b7).

🧠 **[Carballo-cerebras-1.3B](https://huggingface.co/proxectonos/Carballo-cerebras-1.3B)** is a 1.3B parameters model based in [Cerebras-GPT 1.3B](https://huggingface.co/cerebras/Cerebras-GPT-1.3B).

📖 **[Carvalho_pt-gl](https://huggingface.co/Nos-PT/Carvalho_pt-gl-1.3B)** is a 1.3B parameters model based in [Cerebras-GPT 1.3B](https://huggingface.co/cerebras/Cerebras-GPT-1.3B) that can work in Galician and Portuguese, developed in collaboration with the [VISTA Lab](https://www.uevora.pt/en/research/R-D-Unit/vista-lab) at the University of Évora.
"""

short_prompts_examples = [
    ["A receita tradicional das filloas é"], 
    ["O neno vivía preto de"]
]

few_shot_prompts_examples = [
    ["Responde á seguinte pregunta. \nPregunta: \"Cal é a capital de Noruega? \"\nResposta: \"A capital de Noruega é Oslo.\"\n---- \nResponde á seguinte pregunta.\nPregunta: \"Cal é a moeda de Portugal\" \nResposta: \"A moeda de Portugal é o euro.\" \n---- \nResponde á seguinte pregunta. \nPregunta: \"Cal é a capital de Suecia?\"\nResposta:"],
    ["Extrae as entidades nomeadas do seguinte texto: \nTexto: \"Chámome Wolfgang e vivo en Berlin\" \nEntidades: Wolfgang:PER, Berlin:LOC \n ---- \nExtrae as entidades nomeadas do seguinte texto: \nTexto: \"María e Miguel non teñen ningún problema\" \nEntidades: María:PER, Miguel:PER \n---- \nExtrae as entidades nomeadas do seguinte texto: \nTexto: \"O mellor de Barcelona é o bar do meu amigo Pablo\" \nEntidades: Pablo:PER, Barcelona:LOC \n---- \nExtrae as entidades nomeadas do seguinte texto: \nTexto: \"Carlos comparte cuarto con Marc\" \nEntidades:"],
    ["Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"Estou moi feliz\"\n Polaridade: Positivo\n ---- \n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"Non me gusta beber cervexa\"\n Polaridade: Negativo\n ----\n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"O meu pai detesta o seu traballo\"\n Polaridade: Negativo\n ----\n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"Uxía desfruta xogando ao fútbol\"\n Polaridade: Positivo\n ----\n Cualifica como Positivo ou Negativo o sentimento da seguinte frase:\n Texto: \"O neno non está contento coas notas\"\n Polaridade:"],
    ["Traduce ao galego esta frase en inglés:\n Inglés: \"my sister is studying Biology at the university.\"\n Galego: \"a miña irmá está a estudar bioloxía na universidade.\"\n ---- \nTraduce ao galego esta frase en inglés:\n Inglés: \"You are working with my mother on a very interesting project.\"\n Galego: \"Estás a traballar coa miña nai nun proxecto moi interesante\"\n ---- \n Traduce ao galego esta frase en inglés:\n Inglés: \"You have to fix the computer now\"\n Galego:"]
]
fronted_theme = 'Soft'

# Model charge ---------------------------------------------------------
model_id_bloom  = "proxectonos/Carballo-bloom-1.3B"
model_id_carvalho = "Nos-PT/Carvalho_pt-gl-1.3B"
model_id_cerebras  = "proxectonos/Carballo-cerebras-1.3B"

generator_model_gl = pipeline("text-generation", model=model_id_bloom)
generator_model_pt = pipeline("text-generation", model=model_id_carvalho)

# Generation functions ---------------------------------------------------------
def get_model(model_selection):
    global generator_model_gl
    if model_selection == "Carballo-bloom-1.3B":
        if generator_model_gl.model.name_or_path != model_id_bloom:
            generator_model_gl = pipeline("text-generation", model=model_id_bloom)
        return generator_model_gl
    elif model_selection == "Carballo-cerebras-1.3B":
        if generator_model_gl.model.name_or_path != model_id_cerebras:
            generator_model_gl = pipeline("text-generation", model=model_id_cerebras)
        return generator_model_gl
    else:
        return generator_model_pt

def remove_empty_lines(text):
    lines = text.strip().split("\n")
    non_empty_lines = [line for line in lines if line.strip()]
    return "\n".join(non_empty_lines)

def predict(prompt, model_select, max_length, repetition_penalty, temperature):
    print("Dentro da xeración...")
    generator_model = get_model(model_select)
    generated_text = generator_model(
        prompt,
        max_new_tokens = max_length, 
        pad_token_id = generator_model.tokenizer.eos_token_id, 
        repetition_penalty = repetition_penalty,
        temperature = temperature,
        do_sample = True)

    generated_sequence = generated_text[0]['generated_text']
    if generated_sequence is  None:
        gr.Warning('Inference endpoint is not available right now. Please try again later.')
        return
    
    generated_sequence = remove_empty_lines(generated_sequence)
    print("Xeración completada")
    return generated_sequence

# Gradio app ---------------------------------------------------------
def clear(): 
    return (
        None, 
        None,
        gr.update(value=20),
        gr.update(value=1.3),
        gr.update(value=0.5)
    )
def pass_to_input(generated_gl):
    return (
        gr.update(value=generated_gl),
        None
    )

def parameters_default(text):
    return (
        gr.update(value=30), # max_length
        gr.update(value=1.3), # repetition_penalty
        gr.update(value=0.5) # temperature
    )

def parameters_fewshot_prompt(text):
    return (
        gr.update(value=15), # max_length
        gr.update(value=1), # repetition_penalty
        gr.update(value=0.5) # temperature
    )

def gradio_app():
    with gr.Blocks(theme=fronted_theme) as demo:
        with gr.Row():
            gr.Markdown(
                """
                ## 🍂 Grandes Modelos da Linguaxe en galego / Galician Language Models
                """
            )
        with gr.Row():
            gr.Markdown(markdown_description_gl)
        with gr.Row(equal_height=True):            
                model_select = gr.Dropdown(
                    label="Selecione un modelo / Select a model",
                    choices=MODEL_NAMES,
                    value=MODEL_NAMES[0],
                    interactive=True
                )
        with gr.Row(equal_height=True):
            with gr.Column():
                text_gl = gr.Textbox(label="Entrada / Input", 
                                     lines=6, placeholder="e.g. O neno vai a escola con ")
                with gr.Row(variant="panel"):
                        with gr.Accordion("Parámetros do modelo / Model parameters", open=False):
                            max_length = Slider(
                                minimum=1,
                                maximum=200,
                                step=1,
                                value=30,
                                label="Max tokens"
                            )
                            repetition_penalty = Slider(
                                minimum=0.1,
                                maximum=4,
                                step=0.1,
                                value=1.3,
                                label="Penalización por repetición / Repetition penalty"
                            )
                            temperature = Slider(
                                minimum=0,
                                maximum=1,
                                value=0.5,
                                label="Temperatura / Temperature"
                            )
                generator_btn = gr.Button(value="Xerar / Generate",variant='primary')
            with gr.Column():
                generated_gl = gr.Textbox(label="Saída / Output", 
                                          lines=6, 
                                          placeholder="O texto xerado aparecerá aquí...",
                                          interactive=False,
                                          show_copy_button=True)
                pass_btn = gr.Button(value="Pasar texto xerado á entrada / Pass generated text to input",variant='secondary')
                clean_btn = gr.Button(value="Limpar / Clear",variant='secondary')

        generator_btn.click(predict, inputs=[text_gl, model_select, max_length, repetition_penalty, temperature], outputs=generated_gl, api_name="generate-flor-gl")
        clean_btn.click(fn=clear, inputs=[], outputs=[text_gl, generated_gl, max_length, repetition_penalty, temperature], queue=False, api_name=False)
        pass_btn.click(fn=pass_to_input, inputs=[generated_gl], outputs=[text_gl,generated_gl], queue=False, api_name=False)
         
        with gr.Row():
            with gr.Column(scale=0.5):
                gr.Examples(
                    label = "Prompts curtos / Short prompts",
                    examples = short_prompts_examples,
                    inputs = [text_gl],
                    outputs = [max_length, repetition_penalty, temperature],
                    fn = parameters_default,
                    run_on_click = True
                )
                gr.Examples(
                    label = "Prompts con poucos exemplos / Few-shot prompts",
                    examples = few_shot_prompts_examples,
                    inputs = [text_gl],
                    outputs = [max_length, repetition_penalty, temperature],
                    fn = parameters_fewshot_prompt,
                    run_on_click = True
                )
        with gr.Row():
            gr.Markdown(markdown_description_en)

    demo.launch()

if __name__ == "__main__":
    gradio_app()