Views
No views yet
1from transformers import AutoTokenizer, MistralForCausalLM
2import torch
3import gradio as gr
4import random
5from textwrap import wrap
6from transformers import AutoConfig, AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForCausalLM, MistralForCausalLM
7from peft import PeftModel, PeftConfig
8import torch
9import gradio as gr
10import os
11
12hf_token = os.environ.get('HUGGINGFACE_TOKEN')
13
14# Functions to Wrap the Prompt Correctly
15def wrap_text(text, width=90):
16 lines = text.split('\n')
17 wrapped_lines = [textwrap.fill(line, width=width) for line in lines]
18 wrapped_text = '\n'.join(wrapped_lines)
19 return wrapped_text
20def multimodal_prompt(user_input, system_prompt="You are an expert medical analyst:"):
21
22 # Combine user input and system prompt
23 formatted_input = f"[INSTRUCTION]{system_prompt}[QUESTION]{user_input}"
24
25 # Encode the input text
26 encodeds = tokenizer(formatted_input, return_tensors="pt", add_special_tokens=False)
27 model_inputs = encodeds.to(device)
28
29 # Generate a response using the model
30 output = model.generate(
31 **model_inputs,
32 max_length=max_length,
33 use_cache=True,
34 early_stopping=True,
35 bos_token_id=model.config.bos_token_id,
36 eos_token_id=model.config.eos_token_id,
37 pad_token_id=model.config.eos_token_id,
38 temperature=0.1,
39 do_sample=True
40 )
41
42 # Decode the response
43 response_text = tokenizer.decode(output[0], skip_special_tokens=True)
44
45 return response_text
46
47# Define the device
48device = "cuda" if torch.cuda.is_available() else "cpu"
49
50# Use the base model's ID
51base_model_id = "stabilityai/stablelm-3b-4e1t"
52model_directory = "Tonic/stablemed"
53
54# Instantiate the Tokenizer
55tokenizer = AutoTokenizer.from_pretrained("stabilityai/stablelm-3b-4e1t", trust_remote_code=True, padding_side="left")
56# tokenizer = AutoTokenizer.from_pretrained("Tonic/stablemed", trust_remote_code=True, padding_side="left")
57tokenizer.pad_token = tokenizer.eos_token
58tokenizer.padding_side = 'left'
59
60# Load the PEFT model
61peft_config = PeftConfig.from_pretrained("Tonic/stablemed", token=hf_token)
62peft_model = MistralForCausalLM.from_pretrained("stabilityai/stablelm-3b-4e1t", trust_remote_code=True)
63peft_model = PeftModel.from_pretrained(peft_model, "Tonic/stablemed", token=hf_token)
64
65class ChatBot:
66 def __init__(self):
67 self.history = []
68
69 def predict(self, user_input, system_prompt="You are an expert medical analyst:"):
70 # Combine user input and system prompt
71 formatted_input = f"[INSTRUCTION:]{system_prompt}[QUESTION:] {user_input}"
72
73 # Encode user input
74 user_input_ids = tokenizer.encode(formatted_input, return_tensors="pt")
75
76 # Concatenate the user input with chat history
77 if len(self.history) > 0:
78 chat_history_ids = torch.cat([self.history, user_input_ids], dim=-1)
79 else:
80 chat_history_ids = user_input_ids
81
82 # Generate a response using the PEFT model
83 response = peft_model.generate(input_ids=chat_history_ids, max_length=400, pad_token_id=tokenizer.eos_token_id)
84
85 # Update chat history
86 self.history = chat_history_ids
87
88 # Decode and return the response
89 response_text = tokenizer.decode(response[0], skip_special_tokens=True)
90 return response_text
91
92bot = ChatBot()
93
94title = "👋🏻Welcome to Tonic's StableMed Chat🚀"
95description = """
96You can use this Space to test out the current model [StableMed](https://huggingface.co/Tonic/stablemed) or You can also use 😷StableMed⚕️ on your own data & in your own way by cloning this space. 🧬🔬🔍 Simply click here: <a style="display:inline-block" href="https://huggingface.co/spaces/Tonic/StableMed_Chat?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></h3>
97# Join us : 🌟TeamTonic🌟 is always making cool demos! Join our active builder's🛠️community on 👻Discord: [Discord](https://discord.gg/GWpVpekp) On 🤗Huggingface: [TeamTonic](https://huggingface.co/TeamTonic) & [MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Polytonic](https://github.com/tonic-ai) & contribute to 🌟 [PolyGPT](https://github.com/tonic-ai/polygpt-alpha)
98"""
99examples = [["What is the proper treatment for buccal herpes?", "Please provide information on the most effective antiviral medications and home remedies for treating buccal herpes."]]
100
101iface = gr.Interface(
102 fn=bot.predict,
103 title=title,
104 description=description,
105 examples=examples,
106 inputs=["text", "text"], # Take user input and system prompt separately
107 outputs="text",
108 theme="ParityError/Anime"
109)
110
111iface.launch()1output
2Dataset({
3 features: ['qtype', 'Question', 'Answer'],
4 num_rows: 16407
5})trainable params: 12940288 || all params: 1539606528 || trainable%: 0.84049318865969371StableLMEpochForCausalLM(
2 (model): StableLMEpochModel(
3 (embed_tokens): Embedding(50304, 2560)
4 (layers): ModuleList(
5 (0-31): 32 x DecoderLayer(
6 (self_attn): Attention(
7 (q_proj): Linear4bit(in_features=2560, out_features=2560, bias=False)
8 (k_proj): Linear4bit(in_features=2560, out_features=2560, bias=False)
9 (v_proj): Linear4bit(in_features=2560, out_features=2560, bias=False)
10 (o_proj): Linear4bit(in_features=2560, out_features=2560, bias=False)
11 (rotary_emb): RotaryEmbedding()
12 )
13 (mlp): MLP(
14 (gate_proj): Linear4bit(in_features=2560, out_features=6912, bias=False)
15 (up_proj): Linear4bit(in_features=2560, out_features=6912, bias=False)
16 (down_proj): Linear4bit(in_features=6912, out_features=2560, bias=False)
17 (act_fn): SiLU()
18 )
19 (input_layernorm): LayerNorm((2560,), eps=1e-05, elementwise_affine=True)
20 (post_attention_layernorm): LayerNorm((2560,), eps=1e-05, elementwise_affine=True)
21 )
22 )
23 (norm): LayerNorm((2560,), eps=1e-05, elementwise_affine=True)
24 )
25 (lm_head): Linear(in_features=2560, out_features=50304, bias=False)
26)1Given a target sentence construct the underlying meaning representation of the input sentence as a single function with attributes and attribute values.
2This function should describe the target string accurately and the function must be one of the following ['inform', 'request', 'give_opinion', 'confirm', 'verify_attribute', 'suggest', 'request_explanation', 'recommend', 'request_attribute'].
3The attributes must be one of the following: ['name', 'pathology', 'therapeutic', 'dosage', 'side_effects', 'contraindications', 'manufacturer', 'price', 'availability', 'administration', 'warnings', 'interactions', 'storage', 'expiration_date', 'formulation', 'strength', 'route_of_administration', 'class', 'prescription_required', 'generic_name', 'brand_name', 'patient_instructions']TrainOutput(global_step=2051, training_loss=0.6156479549198718, metrics={'train_runtime': 22971.4974, 'train_samples_per_second': 0.357, 'train_steps_per_second': 0.089, 'total_flos': 6.5950444363776e+16, 'train_loss': 0.6156479549198718, 'epoch': 0.5})| Value | Measurement |
|---|---|
| 50 | 1.427000 |
| 100 | 0.763200 |
| 150 | 0.708200 |
| 200 | 0.662300 |
| 250 | 0.650900 |
| 300 | 0.617400 |
| 350 | 0.602900 |
| 400 | 0.608900 |
| 450 | 0.596100 |
| 500 | 0.602000 |
| 550 | 0.594700 |
| 600 | 0.584700 |
| 650 | 0.611000 |
| 700 | 0.558700 |
| 750 | 0.616300 |
| 800 | 0.568700 |
| 850 | 0.597300 |
| 900 | 0.607400 |
| 950 | 0.563200 |
| 1000 | 0.602900 |
| 1050 | 0.594900 |
| 1100 | 0.583000 |
| 1150 | 0.604500 |
| 1200 | 0.547400 |
| 1250 | 0.586600 |
| 1300 | 0.554300 |
| 1350 | 0.581000 |
| 1400 | 0.578900 |
| 1450 | 0.563200 |
| 1500 | 0.556800 |
| 1550 | 0.570300 |
| 1600 | 0.599800 |
| 1650 | 0.556000 |
| 1700 | 0.592500 |
| 1750 | 0.597200 |
| 1800 | 0.559100 |
| 1850 | 0.586100 |
| 1900 | 0.581100 |
| 1950 | 0.589400 |
| 2000 | 0.581100 |
| 2050 | 0.533100 |
1PeftModelForCausalLM(
2 (base_model): LoraModel(
3 (model): StableLMEpochForCausalLM(
4 (model): StableLMEpochModel(
5 (embed_tokens): Embedding(50304, 2560)
6 (layers): ModuleList(
7 (0-31): 32 x DecoderLayer(
8 (self_attn): Attention(
9 (q_proj): Linear4bit(
10 (lora_dropout): ModuleDict(
11 (default): Dropout(p=0.05, inplace=False)
12 )
13 (lora_A): ModuleDict(
14 (default): Linear(in_features=2560, out_features=8, bias=False)
15 )
16 (lora_B): ModuleDict(
17 (default): Linear(in_features=8, out_features=2560, bias=False)
18 )
19 (lora_embedding_A): ParameterDict()
20 (lora_embedding_B): ParameterDict()
21 (base_layer): Linear4bit(in_features=2560, out_features=2560, bias=False)
22 )
23 (k_proj): Linear4bit(
24 (lora_dropout): ModuleDict(
25 (default): Dropout(p=0.05, inplace=False)
26 )
27 (lora_A): ModuleDict(
28 (default): Linear(in_features=2560, out_features=8, bias=False)
29 )
30 (lora_B): ModuleDict(
31 (default): Linear(in_features=8, out_features=2560, bias=False)
32 )
33 (lora_embedding_A): ParameterDict()
34 (lora_embedding_B): ParameterDict()
35 (base_layer): Linear4bit(in_features=2560, out_features=2560, bias=False)
36 )
37 (v_proj): Linear4bit(
38 (lora_dropout): ModuleDict(
39 (default): Dropout(p=0.05, inplace=False)
40 )
41 (lora_A): ModuleDict(
42 (default): Linear(in_features=2560, out_features=8, bias=False)
43 )
44 (lora_B): ModuleDict(
45 (default): Linear(in_features=8, out_features=2560, bias=False)
46 )
47 (lora_embedding_A): ParameterDict()
48 (lora_embedding_B): ParameterDict()
49 (base_layer): Linear4bit(in_features=2560, out_features=2560, bias=False)
50 )
51 (o_proj): Linear4bit(
52 (lora_dropout): ModuleDict(
53 (default): Dropout(p=0.05, inplace=False)
54 )
55 (lora_A): ModuleDict(
56 (default): Linear(in_features=2560, out_features=8, bias=False)
57 )
58 (lora_B): ModuleDict(
59 (default): Linear(in_features=8, out_features=2560, bias=False)
60 )
61 (lora_embedding_A): ParameterDict()
62 (lora_embedding_B): ParameterDict()
63 (base_layer): Linear4bit(in_features=2560, out_features=2560, bias=False)
64 )
65 (rotary_emb): RotaryEmbedding()
66 )
67 (mlp): MLP(
68 (gate_proj): Linear4bit(
69 (lora_dropout): ModuleDict(
70 (default): Dropout(p=0.05, inplace=False)
71 )
72 (lora_A): ModuleDict(
73 (default): Linear(in_features=2560, out_features=8, bias=False)
74 )
75 (lora_B): ModuleDict(
76 (default): Linear(in_features=8, out_features=6912, bias=False)
77 )
78 (lora_embedding_A): ParameterDict()
79 (lora_embedding_B): ParameterDict()
80 (base_layer): Linear4bit(in_features=2560, out_features=6912, bias=False)
81 )
82 (up_proj): Linear4bit(
83 (lora_dropout): ModuleDict(
84 (default): Dropout(p=0.05, inplace=False)
85 )
86 (lora_A): ModuleDict(
87 (default): Linear(in_features=2560, out_features=8, bias=False)
88 )
89 (lora_B): ModuleDict(
90 (default): Linear(in_features=8, out_features=6912, bias=False)
91 )
92 (lora_embedding_A): ParameterDict()
93 (lora_embedding_B): ParameterDict()
94 (base_layer): Linear4bit(in_features=2560, out_features=6912, bias=False)
95 )
96 (down_proj): Linear4bit(
97 (lora_dropout): ModuleDict(
98 (default): Dropout(p=0.05, inplace=False)
99 )
100 (lora_A): ModuleDict(
101 (default): Linear(in_features=6912, out_features=8, bias=False)
102 )
103 (lora_B): ModuleDict(
104 (default): Linear(in_features=8, out_features=2560, bias=False)
105 )
106 (lora_embedding_A): ParameterDict()
107 (lora_embedding_B): ParameterDict()
108 (base_layer): Linear4bit(in_features=6912, out_features=2560, bias=False)
109 )
110 (act_fn): SiLU()
111 )
112 (input_layernorm): LayerNorm((2560,), eps=1e-05, elementwise_affine=True)
113 (post_attention_layernorm): LayerNorm((2560,), eps=1e-05, elementwise_affine=True)
114 )
115 )
116 (norm): LayerNorm((2560,), eps=1e-05, elementwise_affine=True)
117 )
118 (lm_head): Linear(
119 in_features=2560, out_features=50304, bias=False
120 (lora_dropout): ModuleDict(
121 (default): Dropout(p=0.05, inplace=False)
122 )
123 (lora_A): ModuleDict(
124 (default): Linear(in_features=2560, out_features=8, bias=False)
125 )
126 (lora_B): ModuleDict(
127 (default): Linear(in_features=8, out_features=50304, bias=False)
128 )
129 (lora_embedding_A): ParameterDict()
130 (lora_embedding_B): ParameterDict()
131 )
132 )
133 )
134)bitsandbytes quantization config was used during training: