Fu01978 commited on
Commit
fc580f0
·
verified ·
1 Parent(s): d0bfe37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -33
app.py CHANGED
@@ -1,43 +1,78 @@
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
  import torch
4
 
5
- # MODEL_ID can be any HF model repo you want to load
6
- MODEL_ID = "unsloth/Llama-3.2-1B-Instruct" # replace with your own on the Hub
 
 
 
 
 
 
7
 
8
- # load tokenizer + model
9
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
10
- model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
11
-
12
- # chat function
13
- def chat(input_text, history=[]):
14
- # append user input to history
15
- history = history or []
16
- history.append(("You", input_text))
17
-
18
- # encode input
19
- inputs = tokenizer(
20
- input_text + tokenizer.eos_token,
21
- return_tensors="pt"
 
 
 
 
 
 
 
 
 
 
22
  )
23
-
24
- # generate a response
25
- output_ids = model.generate(
 
 
 
26
  **inputs,
27
- max_new_tokens=100,
 
 
 
28
  pad_token_id=tokenizer.eos_token_id
29
  )
 
 
 
 
 
 
 
 
30
 
31
- response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
32
- history.append(("Bot", response))
33
-
34
- # return formatted history
35
- return "", history
36
-
37
- # Gradio UI
38
- with gr.Blocks() as demo:
39
- chatbot = gr.Chatbot()
40
- user_input = gr.Textbox(placeholder="Type a message…")
41
- user_input.submit(chat, [user_input, chatbot], [user_input, chatbot])
 
 
 
 
42
 
43
- demo.launch()
 
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
 
5
+ # Load model and tokenizer
6
+ model_name = "unsloth/Llama-3.2-1B-Instruct"
7
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
8
+ model = AutoModelForCausalLM.from_pretrained(
9
+ model_name,
10
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
11
+ device_map="auto"
12
+ )
13
 
14
+ def chat(message, history):
15
+ """
16
+ Process chat messages and generate responses.
17
+
18
+ Args:
19
+ message: Current user message
20
+ history: List of [user_msg, bot_msg] pairs
21
+ """
22
+ # Build conversation with proper Llama format
23
+ messages = []
24
+
25
+ # Add chat history
26
+ for user_msg, bot_msg in history:
27
+ messages.append({"role": "user", "content": user_msg})
28
+ messages.append({"role": "assistant", "content": bot_msg})
29
+
30
+ # Add current message
31
+ messages.append({"role": "user", "content": message})
32
+
33
+ # Apply chat template
34
+ prompt = tokenizer.apply_chat_template(
35
+ messages,
36
+ tokenize=False,
37
+ add_generation_prompt=True
38
  )
39
+
40
+ # Tokenize
41
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
42
+
43
+ # Generate response
44
+ outputs = model.generate(
45
  **inputs,
46
+ max_new_tokens=512,
47
+ temperature=0.7,
48
+ top_p=0.9,
49
+ do_sample=True,
50
  pad_token_id=tokenizer.eos_token_id
51
  )
52
+
53
+ # Decode and extract only the new response
54
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
55
+
56
+ # Extract only the assistant's response (after the last prompt)
57
+ response = response.split("assistant")[-1].strip()
58
+
59
+ return response
60
 
61
+ # Create Gradio interface
62
+ demo = gr.ChatInterface(
63
+ fn=chat,
64
+ title="Llama 3.2 1B Instruct Chatbot",
65
+ description="Chat with Llama 3.2 1B Instruct model. Ask me anything!",
66
+ examples=[
67
+ "What is artificial intelligence?",
68
+ "Write a short poem about coding",
69
+ "Explain quantum computing in simple terms"
70
+ ],
71
+ theme=gr.themes.Soft(),
72
+ retry_btn="Retry",
73
+ undo_btn="Undo",
74
+ clear_btn="Clear"
75
+ )
76
 
77
+ if __name__ == "__main__":
78
+ demo.launch()