lap096 commited on
Commit
e87f143
·
verified ·
1 Parent(s): 20e6b7b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -34
app.py CHANGED
@@ -2,55 +2,52 @@ import gradio as gr
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
 
5
- # Modern, tiny model trained for instruction following
6
- MODEL_NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
 
 
9
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
10
- model = AutoModelForCausalLM.from_pretrained(MODEL_NAME).to(device)
11
 
12
  def respond(message, history):
13
- # Format the prompt so the model knows it's a chat
14
- # We keep it simple to ensure it follows the "Thoughts/Response" rule
15
- prompt = f"<|im_start|>system\nYou are agent_1. Rules: Show reasoning under [Thoughts] (1 line), then final answer under [Response]. Stay concise.<|im_end|>\n"
16
 
17
- # Add conversation history for actual "smart" context
18
- for user_msg, bot_msg in history[-3:]: # Last 3 turns to save memory
19
- prompt += f"<|im_start|>user\n{user_msg}<|im_end|>\n<|im_start|>assistant\n{bot_msg}<|im_end|>\n"
20
-
21
- prompt += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
 
 
 
 
 
22
 
23
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
24
-
25
  with torch.no_grad():
26
  outputs = model.generate(
27
  **inputs,
28
- max_new_tokens=100,
29
- temperature=0.4, # Lower temp = more logical/less "crazy"
30
  do_sample=True,
31
- repetition_penalty=1.2,
32
- eos_token_id=tokenizer.eos_token_id
33
  )
34
 
35
- # Extract only the new generated text
36
- full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
37
- response_part = full_output.split("assistant")[-1].strip()
38
-
39
- # Ensure it follows the [Thoughts] format even if it forgets
40
- if "[Thoughts]" not in response_part:
41
- response_part = f"[Thoughts] Analyzing... \n[Response] {response_part}"
42
-
43
- # Clean up any "User:" hallucinations
44
- final_output = response_part.split("<|im_start|>")[0].strip()
45
-
46
- return final_output
47
 
48
  demo = gr.ChatInterface(
49
  fn=respond,
50
- title="Agent_1: Enhanced SmolLM",
51
- description="Swapped DistilGPT2 for SmolLM2-135M ",
52
- examples=["Who are you?", "What is 2+2?", "Tell me a joke."],
53
- theme="soft"
54
  )
55
 
56
  if __name__ == "__main__":
 
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
 
5
+ MODEL_NAME = "Agent_1.5"
 
 
6
 
7
+ # Fast tokenizer and CPU-optimized loading
8
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
9
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float32)
10
 
11
  def respond(message, history):
12
+ # System prompt to enforce the "Agent_1" persona and formatting
13
+ system_instruction = "You are agent_1. Rules: 1. Start with [Thoughts] (one sentence). 2. End with [Response]. 3. Be concise."
 
14
 
15
+ # Building the chat template
16
+ messages = [{"role": "system", "content": system_instruction}]
17
+ for user_msg, bot_msg in history[-2:]: # Last 2 turns to keep CPU speed high
18
+ messages.append({"role": "user", "content": user_msg})
19
+ messages.append({"role": "assistant", "content": bot_msg})
20
+ messages.append({"role": "user", "content": message})
21
+
22
+ # Use the official chat template for better logic
23
+ input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
24
+ inputs = tokenizer(input_text, return_tensors="pt")
25
 
 
 
26
  with torch.no_grad():
27
  outputs = model.generate(
28
  **inputs,
29
+ max_new_tokens=80,
30
+ temperature=0.3, # Low temp = smarter, less "rambling"
31
  do_sample=True,
32
+ repetition_penalty=1.1,
33
+ pad_token_id=tokenizer.eos_token_id
34
  )
35
 
36
+ # Decode only the new part (the assistant's response)
37
+ full_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
38
+ # Extract response after the last "assistant" block
39
+ response = full_text.split("assistant")[-1].strip()
40
+
41
+ # Fallback if the model forgets the [Thoughts] tag
42
+ if "[Thoughts]" not in response:
43
+ response = f"[Thoughts] Processing request...\n[Response] {response.replace('[Response]', '').strip()}"
44
+
45
+ return response
 
 
46
 
47
  demo = gr.ChatInterface(
48
  fn=respond,
49
+ title="Agent_1 (Smol-Instruct)",
50
+ description=" using SmolLM2-135M. ",
 
 
51
  )
52
 
53
  if __name__ == "__main__":