AradhyaAlva commited on
Commit
1ba809f
·
1 Parent(s): acd3d14
Files changed (2) hide show
  1. app.py +118 -50
  2. requirements.txt +11 -1
app.py CHANGED
@@ -1,64 +1,132 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
8
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
27
 
28
- response = ""
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ from peft import PeftModel
4
+ from dotenv import load_dotenv
5
+ import torch
6
+ import cohere
7
+ from pinecone import Pinecone, ServerlessSpec
8
+ import os
9
 
10
+ # Load the environment variables
11
+ load_dotenv()
12
+ # Model configuration
13
+ max_seq_length = 2048
14
+ dtype = None
15
+ load_in_4bit = True
16
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
17
 
18
+ class ModelInterface:
19
+ def __init__(self):
20
+ # Model names and paths
21
+ model_name = "Aradhya15/Mistral7b_hypertuned" # Replace with your Hugging Face model path
22
+ base_model_name = "mistralai/Mistral-7B-v0.1"
23
 
24
+ base_model = AutoModelForCausalLM.from_pretrained(base_model_name)
 
 
 
 
 
 
 
 
25
 
26
+ # Load the tokenizer
27
+ self.tokenizer = AutoTokenizer.from_pretrained(base_model_name)
28
+ self.tokenizer.pad_token = self.tokenizer.eos_token
29
+
30
+ # Load the PEFT adapter
31
+ self.model = PeftModel.from_pretrained(base_model, model_name)
32
+ if torch.cuda.is_available():
33
+ print("GPU is available and ready to use:", torch.cuda.get_device_name(0))
34
+ else:
35
+ print("GPU not detected; using CPU.")
36
+ # Check for GPU availability
37
+ if torch.cuda.is_available():
38
+ device = torch.device("cuda") # Use the first available GPU
39
+ else:
40
+ device = torch.device("cpu") # Fallback to CPU
41
 
42
+ # Convert the model to half-precision (optional)
43
+ self.model = self.model.half()
44
 
45
+ # Move the model to the chosen device (GPU or CPU)
46
+ self.model = self.model.to(device)
47
 
48
+ print(f"Model is moved to {device}")
49
+
50
+ # Initialize Cohere
51
+ self.cohere_client = cohere.Client(api_key=os.getenv("COHERE_API_KEY"))
52
+
53
+ # Initialize Pinecone with your API key
54
+ pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))
55
+ self.index = pc.Index("cohere-pinecone-tree")
56
 
57
+ def generate_response(self, query):
58
+ try:
59
+ # Generate query embedding
60
+ response = self.cohere_client.embed(
61
+ texts=[query],
62
+ model="embed-english-light-v2.0"
63
+ )
64
+ query_embedding = response.embeddings[0]
65
 
66
+ # Retrieve documents
67
+ results = self.index.query(
68
+ vector=query_embedding,
69
+ top_k=5,
70
+ include_metadata=True
71
+ )
72
+ retrieved_context = "\n".join(
73
+ [result["metadata"]["text"] for result in results["matches"]]
74
+ )
75
 
76
+ # Prepare input for model
77
+ messages = [
78
+ {"role": "system", "content": f"Context: {retrieved_context}"},
79
+ {"role": "user", "content": query},
80
+ ]
81
+
82
+ # Tokenize input
83
+ inputs = self.tokenizer(
84
+ f"Context: {retrieved_context}\nUser: {query}",
85
+ return_tensors="pt",
86
+ truncation=True,
87
+ padding=True,
88
+ max_length=max_seq_length
89
+ ).to("cuda")
 
 
 
 
90
 
91
+ # Generate response from model
92
+ outputs = self.model.generate(
93
+ inputs["input_ids"],
94
+ max_new_tokens=64,
95
+ temperature=0.3,
96
+ top_p=0.9,
97
+ repetition_penalty=1.2
98
+ )
99
+
100
+ response_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
101
+ return response_text
102
 
103
+ except Exception as e:
104
+ return f"Error generating response: {str(e)}"
105
+
106
+ # Create Gradio interface
107
+ def create_interface():
108
+ interface = ModelInterface()
109
+
110
+ def predict(message):
111
+ return interface.generate_response(message)
112
+
113
+ iface = gr.Interface(
114
+ fn=predict,
115
+ inputs=gr.Textbox(label="Enter your question"),
116
+ outputs=gr.Textbox(label="Response"),
117
+ title="RAG-Enhanced LLM Assistant",
118
+ description="Ask a question and get a response enhanced with retrieved context.",
119
+ examples=[["What are the best practices for tree planting?"], ["How can I improve soil quality in my garden?"]]
120
+ )
121
+
122
+ return iface
123
+
124
+ # Launch the interface
125
  if __name__ == "__main__":
126
+ iface = create_interface()
127
+ iface.launch()
128
+
129
+ # import torch
130
+ # print(torch.__version__)
131
+ # print(torch.cuda.is_available())
132
+ # print(torch.version.cuda) # This should show "12.6" or compatible
requirements.txt CHANGED
@@ -1 +1,11 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+ gradio
3
+ torch>=2.0.0
4
+ transformers>=4.36.0
5
+ unsloth
6
+ cohere
7
+ pinecone-client
8
+ accelerate
9
+ bitsandbytes
10
+ peft
11
+ python-dotenv