Spaces:
Sleeping
Sleeping
File size: 2,457 Bytes
959e1eb 4ead390 959e1eb bdc9656 a38cd38 bdc9656 a38cd38 bdc9656 a38cd38 bdc9656 |
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 |
import subprocess
import os
# Ensure the required libraries are installed
def install(package):
subprocess.check_call([os.sys.executable, "-m", "pip", "install", package])
# Install transformers, huggingface_hub
install("transformers")
install("huggingface_hub")
from transformers import AutoModelForCausalLM, AutoTokenizer
from huggingface_hub import login
import torch
import gradio as gr
import spaces
token = os.environ.get("HF_TOKEN_READ")
login(token)
model_id = "meta-llama/Llama-3.2-1B-Instruct"
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
token=token
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
if torch.cuda.is_available():
device = torch.device("cuda")
print(f"Usando GPU: {torch.cuda.get_device_name(device)}")
else:
device = torch.device("cpu")
print("Usando CPU")
model = model.to(device)
@spaces.GPU
def respond(
message,
history,
system_message,
max_tokens,
temperature,
top_p
):
messages = [{"role": "system", "content": system_message}]
for val in history:
if val[0]:
messages.append({"role": "user", "content": val[0]})
if val[1]:
messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": message})
input_ids = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors='pt'
).to(model.device)
terminators = [
tokenizer.eos_token_id,
tokenizer.convert_tokens_to_ids("<|eot_id|>")
]
outputs = model.generate(
input_ids,
max_new_tokens=max_tokens,
eos_token_id=terminators,
do_sample=True,
temperature=temperature,
top_p=top_p
)
response = ""
for message in tokenizer.decode(
outputs[0][input_ids.shape[-1]:],
skip_special_tokens=True
):
response += message
yield response
demo = gr.ChatInterface(
respond,
additional_inputs=[
gr.Textbox(value="Tu eres un asistente amigable", label="System Message"),
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
gr.Slider(minimum=0.1, maximum=3, value=0.7, step=0.1, label="Temperature"),
gr.Slider(minimum=0.1, maximum=1, value=0.95, step=0.05, label="Top p")
]
)
if __name__ == "__main__":
demo.launch() |