ruhzi commited on
Commit
9aed480
·
verified ·
1 Parent(s): 10f8f06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -30
app.py CHANGED
@@ -1,10 +1,17 @@
 
 
 
 
1
  import gradio as gr
2
  import torch
3
- import gc
4
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, StoppingCriteria, StoppingCriteriaList
5
  from huggingface_hub import hf_hub_download
6
  from threading import Thread
7
 
 
 
 
8
  model_path = "ruhzi/Indian_History_SLM"
9
 
10
  tokenizer = AutoTokenizer.from_pretrained(model_path)
@@ -13,22 +20,17 @@ template_file = hf_hub_download(repo_id=model_path, filename="chat_template.jinj
13
  with open(template_file, "r", encoding="utf-8") as f:
14
  tokenizer.chat_template = f.read()
15
 
 
16
  model = AutoModelForCausalLM.from_pretrained(
17
  model_path,
18
- torch_dtype=torch.float16,
19
- device_map="auto"
20
  )
21
 
22
- class StopGeneration(StoppingCriteria):
23
- def __init__(self):
24
- self.stop_now = False
25
-
26
- def __call__(self, input_ids, scores, **kwargs) -> bool:
27
- return self.stop_now
28
-
29
  def chat_inference(message, history):
30
  messages = []
31
 
 
32
  recent_history = history[-3:] if len(history) > 3 else history
33
 
34
  for user_msg, assistant_msg in recent_history:
@@ -43,45 +45,37 @@ def chat_inference(message, history):
43
  enable_thinking=False
44
  )
45
 
46
- inputs = tokenizer([input_text], return_tensors="pt").to(model.device)
 
47
 
48
  streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
49
- kill_switch = StopGeneration()
50
 
51
  generate_kwargs = dict(
52
  **inputs,
53
  streamer=streamer,
54
- max_new_tokens=1024,
55
  do_sample=True,
56
  temperature=0.7,
57
  top_p=0.8,
58
- stopping_criteria=StoppingCriteriaList([kill_switch])
59
  )
60
 
61
- t = Thread(target=model.generate, kwargs=generate_kwargs, daemon=True)
62
  t.start()
63
 
64
  partial_message = ""
65
-
66
- try:
67
- for new_token in streamer:
68
- partial_message += new_token
69
- yield partial_message
70
-
71
- # BaseException catches GeneratorExit and Gradio's internal Stop signals instantly
72
- except BaseException:
73
- pass
74
 
75
- finally:
76
- # Flip the switch to kill the model thread, then immediately free up the UI
77
- kill_switch.stop_now = True
78
- del inputs
79
- gc.collect()
80
 
81
  demo = gr.ChatInterface(
82
  fn=chat_inference,
83
  title="Indian History SLM",
84
  description="Ask me anything about Indian History!",
 
85
  concurrency_limit=1
86
  )
87
 
 
1
+ import os
2
+ # SPEED FIX 1: Maximize CPU core usage for Hugging Face Free Tier (2 vCPUs)
3
+ os.environ["OMP_NUM_THREADS"] = "2"
4
+
5
  import gradio as gr
6
  import torch
7
+ import gc
8
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
9
  from huggingface_hub import hf_hub_download
10
  from threading import Thread
11
 
12
+ # SPEED FIX 2: Explicitly tell PyTorch to use both CPU cores
13
+ torch.set_num_threads(2)
14
+
15
  model_path = "ruhzi/Indian_History_SLM"
16
 
17
  tokenizer = AutoTokenizer.from_pretrained(model_path)
 
20
  with open(template_file, "r", encoding="utf-8") as f:
21
  tokenizer.chat_template = f.read()
22
 
23
+ # SPEED FIX 3: Removed device_map and used float32 (Native CPU math is faster)
24
  model = AutoModelForCausalLM.from_pretrained(
25
  model_path,
26
+ torch_dtype=torch.float32,
27
+ low_cpu_mem_usage=True
28
  )
29
 
 
 
 
 
 
 
 
30
  def chat_inference(message, history):
31
  messages = []
32
 
33
+ # MEMORY PROTECTION: Only keep the last 3 conversational turns
34
  recent_history = history[-3:] if len(history) > 3 else history
35
 
36
  for user_msg, assistant_msg in recent_history:
 
45
  enable_thinking=False
46
  )
47
 
48
+ # Explicitly send to CPU
49
+ inputs = tokenizer([input_text], return_tensors="pt").to("cpu")
50
 
51
  streamer = TextIteratorStreamer(tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
 
52
 
53
  generate_kwargs = dict(
54
  **inputs,
55
  streamer=streamer,
56
+ max_new_tokens=512, # SPEED FIX 4: Kept at 512 for faster, punchier demo responses
57
  do_sample=True,
58
  temperature=0.7,
59
  top_p=0.8,
 
60
  )
61
 
62
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
63
  t.start()
64
 
65
  partial_message = ""
66
+ for new_token in streamer:
67
+ partial_message += new_token
68
+ yield partial_message
 
 
 
 
 
 
69
 
70
+ # MEMORY PROTECTION: Cleanup after generation finishes
71
+ del inputs
72
+ gc.collect()
 
 
73
 
74
  demo = gr.ChatInterface(
75
  fn=chat_inference,
76
  title="Indian History SLM",
77
  description="Ask me anything about Indian History!",
78
+ # CRASH PROTECTION: The strict queue. 1 user at a time.
79
  concurrency_limit=1
80
  )
81