Zedel17 commited on
Commit
f732939
·
1 Parent(s): fd53736

test app.py fix

Browse files
Files changed (1) hide show
  1. app.py +118 -42
app.py CHANGED
@@ -1,53 +1,129 @@
 
 
1
  import gradio as gr
2
- from ctransformers import AutoModelForCausalLM
3
-
4
- # 🔍 Sanity test model: small, public GGUF that is known to work
5
- HF_REPO = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
6
- MODEL_FILE = "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf" # this file exists in that repo
7
-
8
- print("Loading TinyLlama GGUF model with ctransformers...\n")
9
-
10
- llm = AutoModelForCausalLM.from_pretrained(
11
- HF_REPO,
12
- model_file=MODEL_FILE,
13
- model_type="llama", # TinyLlama is LLaMA-family
14
- hf=True, # load from Hugging Face Hub
15
- gpu_layers=0, # CPU only (free HF Space)
16
- threads=2, # free Spaces usually have 2 vCPUs
17
- context_length=2048,
18
  )
 
19
 
 
 
 
 
 
 
 
20
  print("Model loaded successfully!")
21
 
22
- def chat(message, history):
23
- # Turn Gradio chat history into a simple prompt
24
- parts = []
25
- for user_msg, bot_msg in history:
26
- parts.append(f"User: {user_msg}\nAssistant: {bot_msg}")
27
- parts.append(f"User: {message}\nAssistant:")
28
- prompt = "\n".join(parts)
 
 
 
 
 
 
 
 
 
29
 
30
- response = llm(
 
 
 
 
 
 
 
 
 
31
  prompt,
32
- max_new_tokens=128,
33
  temperature=0.7,
34
- top_p=0.9,
35
- repetition_penalty=1.1,
36
  )
37
 
38
- return str(response).strip()
39
-
40
- demo = gr.ChatInterface(
41
- fn=chat,
42
- title="Sanity Test: TinyLlama 1.1B Chat",
43
- description="If this works, the Space + ctransformers setup is healthy.",
44
- examples=[
45
- "Hello! Who are you?",
46
- "Write a short poem about cats.",
47
- "Explain what an LLM is in simple terms.",
48
- ],
49
- cache_examples=False,
50
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- if __name__ == "__main__":
53
- demo.launch()
 
1
+ from llama_cpp import Llama
2
+ from huggingface_hub import hf_hub_download
3
  import gradio as gr
4
+ import os
5
+
6
+ # ==============================
7
+ # Model loading
8
+ # ==============================
9
+
10
+ # Get HF token from Space secrets (optional, for private repos)
11
+ hf_token = os.environ.get("HF_TOKEN")
12
+
13
+ print("Downloading GGUF model from HuggingFace...")
14
+ model_path = hf_hub_download(
15
+ repo_id="Zedel17/llama_1b_gguf",
16
+ filename="llama_1b_finetuned-Q4_K_M.gguf",
17
+ token=hf_token
 
 
18
  )
19
+ print(f"Model downloaded to: {model_path}")
20
 
21
+ print("Loading GGUF model with llama-cpp-python...")
22
+ llm = Llama(
23
+ model_path=model_path,
24
+ n_ctx=2048,
25
+ n_threads=2, # HF Spaces typically have 2 vCPUs
26
+ n_gpu_layers=0
27
+ )
28
  print("Model loaded successfully!")
29
 
30
+ # ==============================
31
+ # System prompt (kept short and stable)
32
+ # ==============================
33
+
34
+ SYSTEM_PROMPT = (
35
+ "You are a friendly and helpful AI assistant. "
36
+ "You respond in clear, concise, and structured English. "
37
+ "You NEVER ask follow-up questions. "
38
+ "You NEVER continue the conversation beyond one answer. "
39
+ "You ONLY answer the user's last message. "
40
+ "Be precise, helpful, and human-like."
41
+ )
42
+
43
+ # ==============================
44
+ # Safe one-turn chat function
45
+ # ==============================
46
 
47
+ def chat_fn(message, history):
48
+ # DO NOT rebuild the conversation. This prevents hallucinated follow-ups.
49
+ prompt = (
50
+ SYSTEM_PROMPT
51
+ + "\n\n"
52
+ + f"User: {message}\n"
53
+ + "Assistant:"
54
+ )
55
+
56
+ output = llm(
57
  prompt,
58
+ max_tokens=350,
59
  temperature=0.7,
 
 
60
  )
61
 
62
+ reply = output["choices"][0]["text"].strip()
63
+
64
+ # Guarantee no extra questions or turns
65
+ # Occasionally small models hallucinate "User:" — we clean that.
66
+ reply = reply.split("User:")[0].strip()
67
+ reply = reply.split("Assistant:")[0].strip()
68
+
69
+ return reply
70
+
71
+
72
+ # ==============================
73
+ # Gradio UI
74
+ # ==============================
75
+
76
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
77
+
78
+ gr.Markdown(
79
+ """
80
+ # 🤖 **Fine-Tuned Llama-3.2-1B Chat**
81
+ _Fine-tuned on FineTome-100k dataset by **Zedel17**_
82
+
83
+ This is a lightweight Llama-3.2-1B model fine-tuned using PEFT/LoRA
84
+ to generate clearer, more structured and more human-like responses
85
+ compared to the base model.
86
+
87
+ It uses GGUF quantization (Q4_K_M) and CPU-only inference through llama.cpp.
88
+ """
89
+ )
90
+
91
+ chatbot = gr.Chatbot(height=500, show_label=False)
92
+
93
+ with gr.Row():
94
+ msg = gr.Textbox(
95
+ placeholder="Type your message here...",
96
+ scale=8,
97
+ show_label=False
98
+ )
99
+ send_btn = gr.Button("Send", variant="primary", scale=1)
100
+
101
+ clear_btn = gr.Button("🧹 Clear conversation")
102
+
103
+ # ==============================
104
+ # Button logic
105
+ # ==============================
106
+
107
+ def respond(message, chat_history):
108
+ reply = chat_fn(message, chat_history)
109
+ chat_history.append((message, reply))
110
+ return "", chat_history
111
+
112
+ send_btn.click(respond, [msg, chatbot], [msg, chatbot])
113
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
114
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
115
+
116
+ gr.Markdown(
117
+ """
118
+ ---
119
+ ### ℹ️ Technical details
120
+ - **Base Model:** meta-llama/Llama-3.2-1B
121
+ - **Fine-tuning:** PEFT/LoRA on FineTome-100k dataset
122
+ - **Format:** GGUF Q4_K_M quantization
123
+ - **Inference:** llama-cpp-python (CPU only)
124
+ - **Training:** Supervised Fine-Tuning (SFT) with 100 steps
125
+ - **Context window:** 2048 tokens
126
+ """
127
+ )
128
 
129
+ demo.launch()