OrbitMC commited on
Commit
663bfbf
·
verified ·
1 Parent(s): 2539daa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -32
app.py CHANGED
@@ -1,7 +1,8 @@
1
  import gradio as gr
2
  import spaces
3
- from huggingface_hub import hf_hub_download
4
- from llama_cpp import Llama
 
5
 
6
  # 1. DUMMY GPU FUNCTION: satisfies the Hugging Face startup checker
7
  @spaces.GPU(duration=5)
@@ -12,56 +13,67 @@ def dummy_gpu():
12
  # Automatically execute it once right away
13
  dummy_gpu()
14
 
15
- # 2. LOAD MODEL DIRECTLY IN PYTHON
16
- print("Downloading model...")
17
- model_path = hf_hub_download(
18
- repo_id="Abiray/MiniCPM5-1B-GGUF",
19
- filename="minicpm5-1b-Q6_K.gguf"
20
- )
21
 
22
- print("Loading model into memory via llama-cpp-python...")
23
- llm = Llama(
24
- model_path=model_path,
25
- n_ctx=8192, # Safe 8k context limit to avoid RAM crashes
26
- n_threads=2, # Perfectly matches Hugging Face standard CPU cores
27
- verbose=False # Keeps the terminal clean
 
28
  )
29
  print("Model loaded successfully!")
30
 
31
- # 3. CHAT FUNCTION
32
- def chat_with_llama(message, history):
33
- # Format the conversation history
34
  messages = [{"role": "system", "content": "You are a helpful AI assistant."}]
35
-
36
  for user_msg, assistant_msg in history:
37
  messages.append({"role": "user", "content": user_msg})
38
  messages.append({"role": "assistant", "content": assistant_msg})
39
 
40
  messages.append({"role": "user", "content": message})
41
 
42
- # Generate the response in a stream
43
- stream = llm.create_chat_completion(
44
- messages=messages,
45
- stream=True,
 
 
 
 
 
 
 
 
 
 
 
46
  temperature=0.7,
47
- max_tokens=1024
 
48
  )
49
 
 
 
 
 
 
50
  partial_response = ""
51
- for chunk in stream:
52
- if "choices" in chunk and len(chunk["choices"]) > 0:
53
- delta = chunk["choices"][0].get("delta", {})
54
- if "content" in delta:
55
- partial_response += delta["content"]
56
- yield partial_response
57
 
58
  # 4. LAUNCH GRADIO APP
59
  with gr.Blocks() as demo:
60
- gr.Markdown("# Native CPU `llama-cpp-python` on ZeroGPU Space")
61
- gr.Markdown("Running **MiniCPM5-1B-GGUF** natively using Python bindings! No background servers, no zip downloads, and no compiling.")
62
 
63
  gr.ChatInterface(
64
- fn=chat_with_llama,
65
  examples=["Who are you?", "Write a python script to reverse a string.", "Explain quantum computing."],
66
  )
67
 
 
1
  import gradio as gr
2
  import spaces
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
5
+ from threading import Thread
6
 
7
  # 1. DUMMY GPU FUNCTION: satisfies the Hugging Face startup checker
8
  @spaces.GPU(duration=5)
 
13
  # Automatically execute it once right away
14
  dummy_gpu()
15
 
16
+ # 2. LOAD NATIVE PYTORCH MODEL
17
+ print("Loading model via native PyTorch & Transformers...")
18
+ model_id = "Qwen/Qwen2.5-1.5B-Instruct"
 
 
 
19
 
20
+ # Using standard safetensors natively supported by HF.
21
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
22
+ model = AutoModelForCausalLM.from_pretrained(
23
+ model_id,
24
+ torch_dtype=torch.float32, # Safe for standard CPU execution
25
+ device_map="cpu", # Force pure CPU execution
26
+ low_cpu_mem_usage=True
27
  )
28
  print("Model loaded successfully!")
29
 
30
+ # 3. CHAT FUNCTION WITH STREAMING
31
+ def chat_with_hf(message, history):
32
+ # Format the conversation for the model
33
  messages = [{"role": "system", "content": "You are a helpful AI assistant."}]
 
34
  for user_msg, assistant_msg in history:
35
  messages.append({"role": "user", "content": user_msg})
36
  messages.append({"role": "assistant", "content": assistant_msg})
37
 
38
  messages.append({"role": "user", "content": message})
39
 
40
+ # Convert chat to model tokens
41
+ input_ids = tokenizer.apply_chat_template(
42
+ messages,
43
+ add_generation_prompt=True,
44
+ return_tensors="pt"
45
+ ).to("cpu")
46
+
47
+ # Streamer to yield words one by one to Gradio
48
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
49
+
50
+ # Generation arguments
51
+ generate_kwargs = dict(
52
+ input_ids=input_ids,
53
+ streamer=streamer,
54
+ max_new_tokens=512,
55
  temperature=0.7,
56
+ top_p=0.9,
57
+ do_sample=True
58
  )
59
 
60
+ # Start generation in a background thread so the streamer can yield in real-time
61
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
62
+ t.start()
63
+
64
+ # Yield the text back to Gradio UI
65
  partial_response = ""
66
+ for new_text in streamer:
67
+ partial_response += new_text
68
+ yield partial_response
 
 
 
69
 
70
  # 4. LAUNCH GRADIO APP
71
  with gr.Blocks() as demo:
72
+ gr.Markdown("# Native CPU PyTorch Execution on ZeroGPU Space")
73
+ gr.Markdown("Running **Qwen2.5-1.5B** entirely via standard Hugging Face `transformers` and `torch`. No C++, no compilations, no GGUF.")
74
 
75
  gr.ChatInterface(
76
+ fn=chat_with_hf,
77
  examples=["Who are you?", "Write a python script to reverse a string.", "Explain quantum computing."],
78
  )
79