Views
No views yet
1
2# Gaia MiniMed ⚕️🦅 Quick Start
3
4from transformers import AutoConfig, AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForCausalLM, MistralForCausalLM
5from peft import PeftModel, PeftConfig
6import torch
7import gradio as gr
8import random
9from textwrap import wrap
10
11def wrap_text(text, width=90):
12 lines = text.split('\n')
13 wrapped_lines = [textwrap.fill(line, width=width) for line in lines]
14 wrapped_text = '\n'.join(wrapped_lines)
15 return wrapped_text
16
17def multimodal_prompt(user_input, system_prompt):
18 formatted_input = f"{{{{ {system_prompt} }}}}\nUser: {user_input}\nFalcon:"
19 encodeds = tokenizer(formatted_input, return_tensors="pt", add_special_tokens=False)
20 model_inputs = encodeds.to(device)
21 output = peft_model.generate(
22 **model_inputs,
23 max_length=500,
24 use_cache=True,
25 early_stopping=False,
26 bos_token_id=peft_model.config.bos_token_id,
27 eos_token_id=peft_model.config.eos_token_id,
28 pad_token_id=peft_model.config.eos_token_id,
29 temperature=0.4,
30 do_sample=True
31 )
32 response_text = tokenizer.decode(output[0], skip_special_tokens=True)
33
34 return response_text
35
36device = "cuda" if torch.cuda.is_available() else "cpu"
37base_model_id = "tiiuae/falcon-7b-instruct"
38model_directory = "Tonic/GaiaMiniMed"
39
40tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True, padding_side="left")
41model_config = AutoConfig.from_pretrained(base_model_id)
42peft_model = AutoModelForCausalLM.from_pretrained(model_directory, config=model_config)
43peft_model = PeftModel.from_pretrained(peft_model, model_directory)
44
45class ChatBot:
46 def __init__(self, system_prompt="You are an expert medical analyst:"):
47 self.system_prompt = system_prompt
48 self.history = []
49
50 def predict(self, user_input, system_prompt):
51 formatted_input = f"{{{{ {self.system_prompt} }}}}\nUser: {user_input}\nFalcon:"
52 input_ids = tokenizer.encode(formatted_input, return_tensors="pt", add_special_tokens=False)
53 response = peft_model.generate(input_ids=input_ids, max_length=900, use_cache=False, early_stopping=False, bos_token_id=peft_model.config.bos_token_id, eos_token_id=peft_model.config.eos_token_id, pad_token_id=peft_model.config.eos_token_id, temperature=0.4, do_sample=True)
54 response_text = tokenizer.decode(response[0], skip_special_tokens=True)
55 self.history.append(formatted_input)
56 self.history.append(response_text)
57 return response_text
58
59bot = ChatBot()
60
61title = "👋🏻Welcome to Tonic's GaiaMiniMed Chat🚀"
62description = "You can use this Space to test out the current model [(Tonic/GaiaMiniMed)](https://huggingface.co/Tonic/GaiaMiniMed) or duplicate this Space and use it locally or on 🤗HuggingFace. [Join me on Discord to build together](https://discord.gg/VqTxc76K3u)."
63examples = [["What is the proper treatment for buccal herpes?", "You are a medicine and public health expert, you will receive a question, answer the question, and provide a complete answer"]]
64
65iface = gr.Interface(
66 fn=bot.predict,
67 title=title,
68 description=description,
69 examples=examples,
70 inputs=["text", "text"],
71 outputs="text",
72 theme="ParityError/Anime"
73)
74
75iface.launch()
761
2# Gaia MiniMed⚕️🦅Falcon Chat
3
4from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM
5from peft import PeftModel, PeftConfig
6import torch
7import gradio as gr
8import json
9import os
10import shutil
11import requests
12
13# Define the device
14device = "cuda" if torch.cuda.is_available() else "cpu"
15#Define variables
16temperature=0.4
17max_new_tokens=240
18top_p=0.92
19repetition_penalty=1.7
20max_length=2048
21
22# Use model IDs as variables
23base_model_id = "tiiuae/falcon-7b-instruct"
24model_directory = "Tonic/GaiaMiniMed"
25
26# Instantiate the Tokenizer
27tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True, padding_side="left")
28tokenizer.pad_token = tokenizer.eos_token
29tokenizer.padding_side = 'left'
30
31
32# Load the GaiaMiniMed model with the specified configuration
33# Load the Peft model with a specific configuration
34# Specify the configuration class for the model
35model_config = AutoConfig.from_pretrained(base_model_id)
36# Load the PEFT model with the specified configuration
37peft_model = AutoModelForCausalLM.from_pretrained(model_directory, config=model_config)
38peft_model = PeftModel.from_pretrained(peft_model, model_directory)
39
40
41
42# Class to encapsulate the Falcon chatbot
43class FalconChatBot:
44 def __init__(self, system_prompt="You are an expert medical analyst:"):
45 self.system_prompt = system_prompt
46
47 def process_history(self, history):
48 if history is None:
49 return []
50
51 # Ensure that history is a list of dictionaries
52 if not isinstance(history, list):
53 return []
54
55 # Filter out special commands from the history
56 filtered_history = []
57 for message in history:
58 if isinstance(message, dict):
59 user_message = message.get("user", "")
60 assistant_message = message.get("assistant", "")
61 # Check if the user_message is not a special command
62 if not user_message.startswith("Falcon:"):
63 filtered_history.append({"user": user_message, "assistant": assistant_message})
64 return filtered_history
65
66 def predict(self, user_message, assistant_message, history, temperature=0.4, max_new_tokens=700, top_p=0.99, repetition_penalty=1.9):
67
68 # Process the history to remove special commands
69 processed_history = self.process_history(history)
70 # Combine the user and assistant messages into a conversation
71 conversation = f"{self.system_prompt}\nFalcon: {assistant_message if assistant_message else ''} User: {user_message}\nFalcon:\n"
72 # Encode the conversation using the tokenizer
73 input_ids = tokenizer.encode(conversation, return_tensors="pt", add_special_tokens=False)
74 # Generate a response using the Falcon model
75 response = peft_model.generate(input_ids=input_ids, max_length=max_length, use_cache=False, early_stopping=False, bos_token_id=peft_model.config.bos_token_id, eos_token_id=peft_model.config.eos_token_id, pad_token_id=peft_model.config.eos_token_id, temperature=0.4, do_sample=True)
76 # Decode the generated response to text
77 response_text = tokenizer.decode(response[0], skip_special_tokens=True)
78 # Append the Falcon-like conversation to the history
79 self.history.append(conversation)
80 self.history.append(response_text)
81
82 return response_text
83
84
85# Create the Falcon chatbot instance
86falcon_bot = FalconChatBot()
87
88# Define the Gradio interface
89title = "👋🏻Welcome to Tonic's 🦅Falcon's Medical👨🏻⚕️Expert Chat🚀"
90description = "You can use this Space to test out the GaiaMiniMed model [(Tonic/GaiaMiniMed)](https://huggingface.co/Tonic/GaiaMiniMed) or duplicate this Space and use it locally or on 🤗HuggingFace. [Join me on Discord to build together](https://discord.gg/VqTxc76K3u). Please be patient as we "
91
92history = [
93 {"user": "hi there how can you help me?", "assistant": "Hello, my name is Gaia, i'm created by Tonic, i can answer questions about medicine and public health!"},
94 # Add more user and assistant messages as needed
95]
96examples = [
97 [
98 {
99 "user_message": "What is the proper treatment for buccal herpes?",
100 "assistant_message": "My name is Gaia, I'm a health and sanitation expert ready to answer your medical questions.",
101 "history": [],
102 "temperature": 0.4,
103 "max_new_tokens": 700,
104 "top_p": 0.90,
105 "repetition_penalty": 1.9,
106 }
107 ]
108]
109
110
111
112
113
114additional_inputs=[
115 gr.Textbox("", label="Optional system prompt"),
116 gr.Slider(
117 label="Temperature",
118 value=0.9,
119 minimum=0.0,
120 maximum=1.0,
121 step=0.05,
122 interactive=True,
123 info="Higher values produce more diverse outputs",
124 ),
125 gr.Slider(
126 label="Max new tokens",
127 value=256,
128 minimum=0,
129 maximum=3000,
130 step=64,
131 interactive=True,
132 info="The maximum numbers of new tokens",
133 ),
134 gr.Slider(
135 label="Top-p (nucleus sampling)",
136 value=0.90,
137 minimum=0.01,
138 maximum=0.99,
139 step=0.05,
140 interactive=True,
141 info="Higher values sample more low-probability tokens",
142 ),
143 gr.Slider(
144 label="Repetition penalty",
145 value=1.2,
146 minimum=1.0,
147 maximum=2.0,
148 step=0.05,
149 interactive=True,
150 info="Penalize repeated tokens",
151 )
152]
153
154iface = gr.Interface(
155 fn=falcon_bot.predict,
156 title=title,
157 description=description,
158 examples=examples,
159 inputs=[
160 gr.inputs.Textbox(label="Input Parameters", type="text", lines=5),
161 ] + additional_inputs,
162 outputs="text",
163 theme="ParityError/Anime"
164)
165
166# Launch the Gradio interface for the Falcon model
167iface.launch()
168
1
2TrainOutput(global_step=6150, training_loss=1.0597990553941183,
3{'epoch': 6.0})1
2DatasetDict({
3 train: Dataset({
4 features: ['qtype', 'Question', 'Answer'],
5 num_rows: 16407
6 })
7})
8
trainable params: 4718592 || all params: 3613463424 || trainables%: 0.13058363808693696
1
2metrics={'train_runtime': 30766.4612, 'train_samples_per_second': 3.2, 'train_steps_per_second': 0.2,
3'total_flos': 1.1252790565109983e+18, 'train_loss': 1.0597990553941183,", true)}}
41
2PeftModelForCausalLM(
3 (base_model): LoraModel(
4 (model): FalconForCausalLM(
5 (transformer): FalconModel(
6 (word_embeddings): Embedding(65024, 4544)
7 (h): ModuleList(
8 (0-31): 32 x FalconDecoderLayer(
9 (self_attention): FalconAttention(
10 (maybe_rotary): FalconRotaryEmbedding()
11 (query_key_value): Linear4bit(
12 in_features=4544, out_features=4672, bias=False
13 (lora_dropout): ModuleDict(
14 (default): Dropout(p=0.05, inplace=False)
15 )
16 (lora_A): ModuleDict(
17 (default): Linear(in_features=4544, out_features=16, bias=False)
18 )
19 (lora_B): ModuleDict(
20 (default): Linear(in_features=16, out_features=4672, bias=False)
21 )
22 (lora_embedding_A): ParameterDict()
23 (lora_embedding_B): ParameterDict()
24 )
25 (dense): Linear4bit(in_features=4544, out_features=4544, bias=False)
26 (attention_dropout): Dropout(p=0.0, inplace=False)
27 )
28 (mlp): FalconMLP(
29 (dense_h_to_4h): Linear4bit(in_features=4544, out_features=18176, bias=False)
30 (act): GELU(approximate='none')
31 (dense_4h_to_h): Linear4bit(in_features=18176, out_features=4544, bias=False)
32 )
33 (input_layernorm): LayerNorm((4544,), eps=1e-05, elementwise_affine=True)
34 )
35 )
36 (ln_f): LayerNorm((4544,), eps=1e-05, elementwise_affine=True)
37 )
38 (lm_head): Linear(in_features=4544, out_features=65024, bias=False)
39 )
40 )
41)
42