ChriLLM / app.py
Mashbox41's picture
Update app.py
cb0d386 verified
Raw History Blame Contribute Delete
2.07 kB
import torch
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
BASE_MODEL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
LORA_MODEL = "Mashbox41/ChriLLM-lora"
device = "cpu"
dtype = torch.float32
print("[info] Loading tokenizer…")
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, use_fast=True)
if tokenizer.pad_token_id is None:
tokenizer.pad_token = tokenizer.eos_token
print("[info] Loading base model on CPU…")
base_model = AutoModelForCausalLM.from_pretrained(
BASE_MODEL,
torch_dtype=torch.float32,
low_cpu_mem_usage=True
)
print("[info] Attaching LoRA…")
model = PeftModel.from_pretrained(
base_model,
LORA_MODEL,
torch_dtype=torch.float32
)
# Merge the LoRA weights into the base model (IMPORTANT!)
model = model.merge_and_unload()
model.to(device)
model.eval()
SYSTEM_PROMPT = (
"system: You are ChriLLM, a gentle, Bible-informed assistant. "
"You answer with kindness, clarity, humility, and sound doctrine.\n"
)
def build_prompt(message: str) -> str:
# simple 1-turn prompt for now (no history to avoid extra complexity)
return SYSTEM_PROMPT + f"user: {message}\nassistant:"
@torch.no_grad()
def chat_fn(message, history):
prompt = build_prompt(message)
inputs = tokenizer(prompt, return_tensors="pt").to(device)
outputs = model.generate(
**inputs,
max_new_tokens=150,
temperature=0.7,
top_p=0.9,
do_sample=True,
pad_token_id=tokenizer.eos_token_id,
)
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# keep only last assistant bit
if "assistant:" in text:
reply = text.split("assistant:")[-1].strip()
else:
reply = text.strip()
# IMPORTANT: ChatInterface in Gradio 4 expects JUST the reply string
return reply
demo = gr.ChatInterface(
fn=chat_fn,
title="🕊️ ChriLLM – TinyLlama + LoRA",
description="A small, faith-guided helper fine-tuned by Mashbox41."
)
if __name__ == "__main__":
demo.launch()