anktechsol commited on
Commit
d5f4c16
·
verified ·
1 Parent(s): 1624583

Fix app.py: Replace InferenceClient with direct model loading using transformers

Browse files
Files changed (1) hide show
  1. app.py +82 -37
app.py CHANGED
@@ -1,6 +1,18 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def respond(
6
  message,
@@ -9,36 +21,75 @@ def respond(
9
  max_tokens,
10
  temperature,
11
  top_p,
12
- hf_token: gr.OAuthToken,
13
  ):
14
  """
15
- 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
16
  """
17
- client = InferenceClient(token=hf_token.token, model="anktechsol/anki-2.5")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = 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
@@ -47,9 +98,9 @@ chatbot = gr.ChatInterface(
47
  respond,
48
  type="messages",
49
  additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
  gr.Slider(
54
  minimum=0.1,
55
  maximum=1.0,
@@ -60,11 +111,5 @@ chatbot = gr.ChatInterface(
60
  ],
61
  )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
68
-
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
 
5
+ # Load model and tokenizer at startup
6
+ model_name = "anktechsol/anki-2.5"
7
+ print(f"Loading model {model_name}...")
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ model_name,
11
+ torch_dtype=torch.float32,
12
+ device_map="auto",
13
+ low_cpu_mem_usage=True
14
+ )
15
+ print("Model loaded successfully!")
16
 
17
  def respond(
18
  message,
 
21
  max_tokens,
22
  temperature,
23
  top_p,
 
24
  ):
25
  """
26
+ Generate responses using the local Anki 2.5 model.
27
  """
28
+ # Build conversation history
29
+ conversation = []
30
+
31
+ # Add system message if provided
32
+ if system_message:
33
+ conversation.append({"role": "system", "content": system_message})
34
+
35
+ # Add chat history
36
+ for msg in history:
37
+ conversation.append(msg)
38
+
39
+ # Add current message
40
+ conversation.append({"role": "user", "content": message})
41
+
42
+ # Format prompt for the model
43
+ # Try to apply chat template if available, otherwise use simple format
44
+ try:
45
+ formatted_prompt = tokenizer.apply_chat_template(
46
+ conversation,
47
+ tokenize=False,
48
+ add_generation_prompt=True
49
+ )
50
+ except:
51
+ # Fallback to simple format if chat template not available
52
+ formatted_prompt = ""
53
+ for msg in conversation:
54
+ role = msg.get("role", "user")
55
+ content = msg.get("content", "")
56
+ if role == "system":
57
+ formatted_prompt += f"System: {content}\n"
58
+ elif role == "user":
59
+ formatted_prompt += f"User: {content}\n"
60
+ elif role == "assistant":
61
+ formatted_prompt += f"Assistant: {content}\n"
62
+ formatted_prompt += "Assistant: "
63
+
64
+ # Tokenize input
65
+ inputs = tokenizer(formatted_prompt, return_tensors="pt", truncation=True, max_length=2048)
66
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
67
+
68
+ # Generate response with streaming
69
  response = ""
70
+ with torch.no_grad():
71
+ for i in range(max_tokens):
72
+ outputs = model.generate(
73
+ **inputs,
74
+ max_new_tokens=1,
75
+ temperature=temperature,
76
+ top_p=top_p,
77
+ do_sample=True,
78
+ pad_token_id=tokenizer.eos_token_id,
79
+ )
80
+
81
+ # Decode only the new token
82
+ new_token = tokenizer.decode(outputs[0][-1], skip_special_tokens=True)
83
+
84
+ # Check for end of generation
85
+ if outputs[0][-1].item() == tokenizer.eos_token_id:
86
+ break
87
+
88
+ response += new_token
89
+ yield response
90
+
91
+ # Update inputs for next iteration
92
+ inputs = {"input_ids": outputs, "attention_mask": torch.ones_like(outputs)}
93
 
94
  """
95
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
 
98
  respond,
99
  type="messages",
100
  additional_inputs=[
101
+ gr.Textbox(value="You are a friendly Chatbot proficient in Indian languages.", label="System message"),
102
+ gr.Slider(minimum=1, maximum=512, value=256, step=1, label="Max new tokens"),
103
+ gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
104
  gr.Slider(
105
  minimum=0.1,
106
  maximum=1.0,
 
111
  ],
112
  )
113
 
 
 
 
 
 
 
114
  if __name__ == "__main__":
115
+ chatbot.launch()