Titobsala commited on
Commit
7f54168
·
1 Parent(s): 3ae7e31

app para avalição do modelo treinado com interface

Browse files
Files changed (2) hide show
  1. app.py +66 -55
  2. requirements.txt +5 -1
app.py CHANGED
@@ -1,64 +1,75 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
+ import csv
5
+ from datetime import datetime
6
 
7
+ # Load models and tokenizers
8
+ base_model_name = "unsloth/Llama-3.2-1B-Instruct"
9
+ finetuned_model_name = "exo-is/esg-context-llama-1Bst-11M" # Replace with your model's path
 
10
 
11
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name)
12
+ base_model = AutoModelForCausalLM.from_pretrained(base_model_name, torch_dtype=torch.float32, low_cpu_mem_usage=True, device_map="cpu")
13
+ finetuned_model = AutoModelForCausalLM.from_pretrained(finetuned_model_name, torch_dtype=torch.float32, low_cpu_mem_usage=True, device_map="cpu")
14
 
15
+ def generate_text(model, prompt, max_new_tokens, temperature):
16
+ inputs = tokenizer(prompt, return_tensors="pt")
17
+
18
+ with torch.no_grad():
19
+ outputs = model.generate(
20
+ **inputs,
21
+ max_new_tokens=int(max_new_tokens),
22
+ temperature=temperature,
23
+ num_return_sequences=1,
24
+ do_sample=True,
25
+ )
26
+
27
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
28
 
29
+ def log_interaction(model, prompt, output, validation):
30
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
31
+ with open('interaction_log.csv', 'a', newline='') as file:
32
+ writer = csv.writer(file)
33
+ writer.writerow([timestamp, model, prompt, output, validation])
34
 
35
+ def generate_and_compare(prompt, max_new_tokens, temperature):
36
+ base_output = generate_text(base_model, prompt, max_new_tokens, temperature)
37
+ finetuned_output = generate_text(finetuned_model, prompt, max_new_tokens, temperature)
38
+ return base_output, finetuned_output
39
 
40
+ def evaluate(model, output, score):
41
+ log_interaction(model, gr.get_state('last_prompt'), output, score)
42
+ return f"Avaliação registrada: {score}"
43
 
44
+ with gr.Blocks() as demo:
45
+ gr.Markdown("# Comparação de Modelos: Llama-3.2-1B-Instruct vs. Modelo Fine-tuned para Sustentabilidade")
46
+
47
+ with gr.Row():
48
+ prompt = gr.Textbox(lines=5, label="Insira seu prompt aqui")
49
+ max_new_tokens = gr.Slider(50, 500, value=200, step=1, label="Máximo de Novos Tokens")
50
+ temperature = gr.Slider(0.1, 2.0, value=0.7, step=0.1, label="Temperatura")
51
+
52
+ generate_btn = gr.Button("Gerar")
53
+
54
+ with gr.Row():
55
+ with gr.Column():
56
+ base_output = gr.Textbox(label="Saída do Modelo Base", lines=10)
57
+ base_rating = gr.Radio(["1", "2", "3", "4", "5"], label="Avalie a resposta do Modelo Base")
58
+ base_submit = gr.Button("Enviar Avaliação (Base)")
59
+
60
+ with gr.Column():
61
+ finetuned_output = gr.Textbox(label="Saída do Modelo Fine-tuned", lines=10)
62
+ finetuned_rating = gr.Radio(["1", "2", "3", "4", "5"], label="Avalie a resposta do Modelo Fine-tuned")
63
+ finetuned_submit = gr.Button("Enviar Avaliação (Fine-tuned)")
64
+
65
+ base_feedback = gr.Textbox(label="Feedback da Avaliação (Base)")
66
+ finetuned_feedback = gr.Textbox(label="Feedback da Avaliação (Fine-tuned)")
67
+
68
+ generate_btn.click(generate_and_compare, inputs=[prompt, max_new_tokens, temperature], outputs=[base_output, finetuned_output])
69
+ base_submit.click(evaluate, inputs=["Base", base_output, base_rating], outputs=base_feedback)
70
+ finetuned_submit.click(evaluate, inputs=["Fine-tuned", finetuned_output, finetuned_rating], outputs=finetuned_feedback)
71
+
72
+ demo.load(lambda: gr.update(value=""), outputs=[prompt])
73
+ prompt.change(lambda x: gr.set_state(last_prompt=x), inputs=[prompt])
74
 
75
+ demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1 +1,5 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+
3
+ gradio
4
+ transformers
5
+ torch