File size: 2,773 Bytes
cd6952b e24d0f6 cd6952b 5fb9d86 cd6952b e24d0f6 cd6952b e24d0f6 e7375f4 cd6952b |
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 |
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
AutoTokenizer,
)
from peft import PeftModel, PeftConfig
import torch
import gradio as gr
d_map = {"": torch.cuda.current_device()} if torch.cuda.is_available() else None
local_model_path = "outputs/checkpoint-100" # Path to the combined weights
# Loading the base Model
config = PeftConfig.from_pretrained(local_model_path)
model = AutoModelForCausalLM.from_pretrained(
config.base_model_name_or_path,
return_dict=True,
torch_dtype=torch.float16,
device_map=d_map,
)
tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path, trust_remote_code=True)
# load the base model with the Lora model
mergedModel = PeftModel.from_pretrained(model, local_model_path)
# model = model.merge_and_unload()
mergedModel.eval()
def extract_answer(message):
# Find the index of '### Answer:'
start_index = message.find('### Answer:')
if start_index != -1:
# Extract the part of the message after '### Answer:'
answer_part = message[start_index + len('### Answer:'):].strip()
# Find the index of the last full stop
last_full_stop_index = answer_part.rfind('.')
if last_full_stop_index != -1:
# Remove the part after the last full stop
answer_part = answer_part[:last_full_stop_index + 1]
return answer_part.strip() # Remove leading and trailing whitespace
else:
return "I don't have the answer to this question....."
def inferance(query: str, model, tokenizer, temp = 1.0, limit = 200) -> str:
device = "cuda:0"
prompt_template = """
Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Question:
{query}
### Answer:
"""
prompt = prompt_template.format(query=query)
encodeds = tokenizer(prompt, return_tensors="pt", add_special_tokens=True)
model_inputs = encodeds.to(device)
generated_ids = model.generate(**model_inputs, max_new_tokens=int(limit), temperature=temp, do_sample=True, pad_token_id=tokenizer.eos_token_id)
decoded = tokenizer.batch_decode(generated_ids)
return (decoded[0])
def predict(temp, limit, text):
prompt = text
out = inferance(prompt, mergedModel, tokenizer, temp = 1.0, limit = 200)
display = extract_answer(out)
return display
pred = gr.Interface(
predict,
inputs=[
gr.Slider(0.001, 10, value=0.1, label="Temperature"),
gr.Slider(1, 1024, value=128, label="Token Limit"),
gr.Textbox(
label="Input",
lines=1,
value="#### Human: What's the capital of Australia?#### Assistant: ",
),
],
outputs='text',
)
pred.launch(share=True)
|