Siva1995 commited on
Commit
9907b05
·
1 Parent(s): 8ec5afe

Upload proton_code_llama_fine_tuning_using_qlora_inferencing.py

Browse files
proton_code_llama_fine_tuning_using_qlora_inferencing.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Proton_Code_Llama_Fine_Tuning_using_QLora_Inferencing.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1snQ0jgdbZDXNuVpvryjfENfCjk8K2SE2
8
+ """
9
+
10
+ !pip install -q -U trl transformers accelerate git+https://github.com/huggingface/peft.git
11
+ !pip install -q datasets bitsandbytes einops wandb
12
+ !pip install peft
13
+ !pip install --upgrade gradio
14
+ !pip install sentence_transformers
15
+ !pip install accelerate
16
+ !pip install bitsandbytes
17
+
18
+ import pandas as pd
19
+ import torch
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, AutoTokenizer
21
+ from peft import PeftModel, PeftConfig
22
+ from sentence_transformers.util import semantic_search
23
+ import requests
24
+
25
+ model_id = "sentence-transformers/all-MiniLM-L6-v2"
26
+ hf_token = "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"
27
+
28
+ data = pd.read_excel('/content/sample_data/Proton Gen AI.xlsx')
29
+
30
+ text_col = []
31
+
32
+ for _, row in data.iterrows():
33
+
34
+ prompt = "Below is an instruction that describes a task to generate a domain specific code called a Proton UI. It is almost identical to YAML with some additions. Write a response that appropriately completes the request and generates the code. \n\n"
35
+
36
+ instruction = str(row['Description'])
37
+
38
+ response = str(row['UI'])
39
+
40
+ text = prompt + "### Instruction:\n" + instruction + "\n### Response:\n" + response
41
+
42
+ text_col.append(text)
43
+
44
+ data.loc[:, "text"] = text_col
45
+
46
+ api_url = f"https://api-inference.huggingface.co/pipeline/feature-extraction/{model_id}"
47
+ headers = {"Authorization": f"Bearer {hf_token}"}
48
+
49
+ def create_embeddings(texts):
50
+ response = requests.post(api_url, headers=headers, json={"inputs": texts, "options":{"wait_for_model":True}})
51
+ return response.json()
52
+
53
+ output = create_embeddings(data["Description"].to_list())
54
+ embeddings = pd.DataFrame(output)
55
+ dataset_embeddings = torch.from_numpy(embeddings.to_numpy()).to(torch.float)
56
+
57
+ bnb_config = BitsAndBytesConfig(
58
+ load_in_4bit=True,
59
+ bnb_4bit_quant_type="nf4",
60
+ bnb_4bit_compute_dtype=torch.bfloat16,
61
+ )
62
+ config = PeftConfig.from_pretrained("Siva1995/codellama_finetuned_proton_ui")
63
+ model = AutoModelForCausalLM.from_pretrained("codellama/CodeLlama-7b-Instruct-hf",quantization_config=bnb_config,
64
+ trust_remote_code=True)
65
+ model = PeftModel.from_pretrained(model, "Siva1995/codellama_finetuned_proton_ui")
66
+
67
+ model_tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path,trust_remote_code = True)
68
+ model_tokenizer.pad_token = model_tokenizer.eos_token
69
+
70
+ generation_config = model.generation_config
71
+ generation_config.max_new_token = 1000
72
+ generation_config.temperature = 0.1
73
+ generation_config.top_p = 0.5
74
+ generation_config.num_return_sequence = 1
75
+ generation_config.pad_token_id = model_tokenizer.pad_token_id
76
+ generation_config.eos_token_id = model_tokenizer.eos_token_id
77
+
78
+ device = 'cuda:0'
79
+
80
+ priming_text = "You are an expert at writing a complete Proton UI code. Here are the examples of Proton description and corresponding UI responses."
81
+ decorator = "Your response should follow the Proper Proton UI format as mentioned in the above examples"
82
+
83
+ def create_fewshot_examples(question):
84
+ # question = ["Create a dropdown type UI with Sports?"]
85
+ # print(question)
86
+ output = create_embeddings(question)
87
+ query_embeddings = torch.FloatTensor(output)
88
+ hits = semantic_search(query_embeddings, dataset_embeddings, top_k=3)
89
+ similar_description = [data["Description"].to_list()[hits[0][i]['corpus_id']] for i in range(len(hits[0]))]
90
+ similar_data = data[data['Description'].isin(similar_description)]
91
+ dyn_fewshot_examples = similar_data[['Description','UI']].to_dict(orient='records')
92
+ return dyn_fewshot_examples
93
+
94
+ def getExamples(question):
95
+ dyn_fewshot_examples = create_fewshot_examples(question)
96
+ r = ''
97
+ for example in dyn_fewshot_examples:
98
+ r = '\r\n'.join([r,'Description:',example['Description'],'UI:',example['UI']])
99
+ return r
100
+
101
+ def prepare_prompt(query):
102
+ prompt_prep = ''.join([priming_text,getExamples(query),'\n',decorator,'\n','Similar to the above examples, generate only one Proton UI for the following description:',query])
103
+ return prompt_prep
104
+
105
+ def generate(query):
106
+ prompt_prep = prepare_prompt(query)
107
+ encodings = model_tokenizer(prompt_prep, return_tensors = 'pt').to(device)
108
+
109
+ with torch.inference_mode():
110
+ outputs = model.generate(input_ids=encodings.input_ids,
111
+ attention_mask = encodings.attention_mask,
112
+ generation_config = generation_config,
113
+ max_new_tokens=1000,do_sample=True)
114
+
115
+ outputs = model_tokenizer.decode(outputs[0],skip_special_tokens=True,best_of=1)
116
+
117
+ return outputs[outputs.find(query): ]#outputs.find('Explanation')
118
+
119
+ output = generate('Create a choice type of Proton UI for choosing vegetables')
120
+ print(output)
121
+
122
+ import gradio as gr
123
+ with gr.Blocks() as demo:
124
+ gr.Markdown("****This application is built on fine-tuned on specific data on codellama 7b on 4 bit fine tuned****")
125
+ gr.Markdown("**No Paid service has been leveraged**")
126
+ gr.Markdown("**Type your Query Run to see the output**")
127
+ with gr.Row():
128
+ out = gr.Textbox()
129
+ with gr.Row():
130
+ inp = gr.Textbox(placeholder="Type your Question")
131
+ btn = gr.Button("Run")
132
+ btn.click(fn=output, inputs=inp, outputs=out)
133
+ demo.launch(auth=("user", "password"),share=True)
134
+
135
+ import random
136
+ import gradio as gr
137
+
138
+ def alternatingly_agree(message, history):
139
+ output = generate(str(message))
140
+ return output
141
+
142
+ gr.ChatInterface(alternatingly_agree).launch()
143
+