File size: 4,343 Bytes
d1896c8 fe25d18 734bf41 d1896c8 d12d0ed fe25d18 99a12ec d1896c8 fe25d18 d1896c8 fe25d18 d12d0ed d1896c8 fe25d18 d1896c8 fe25d18 d1896c8 fe25d18 d1896c8 d12d0ed fe25d18 d12d0ed fe25d18 d1896c8 d12d0ed d1896c8 fe25d18 d1896c8 fe25d18 d1896c8 fe25d18 d1896c8 d12d0ed fe25d18 d12d0ed fe25d18 d12d0ed fe25d18 d12d0ed fe25d18 d1896c8 d12d0ed d1896c8 fe25d18 d1896c8 d12d0ed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# ✅ Naya Model Name: Qwen/Qwen2.5-0.3B-Instruct
MODEL_NAME = "Qwen/Qwen2.5-0.3B-Instruct"
print("⏳ Loading model...")
# Model aur Tokenizer load kar rahe hain
# Qwen ke liye 'trust_remote_code=True' ki zarurat nahi hai, par use rakha hai toh koi dikkat nahi
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto"
)
print("✅ Model loaded!")
# CUSTOM PROMPT BUILDING FUNCTION HATA DIYA HAI (Kyunki Qwen ke liye inbuilt template better hai)
def chat_fn(message, history):
# System prompt se conversation shuru karte hain
# Note: Qwen ke official template mein system message automatically add ho jaati hai.
messages = []
# History ko 'messages' list mein add karte hain, Gradio ka format use karte hue
for user, assistant in history:
messages.append({"role": "user", "content": user})
messages.append({"role": "assistant", "content": assistant})
# Ab user ka naya message add karte hain
messages.append({"role": "user", "content": message})
# ✅ Qwen ke liye sahi template application logic:
# `apply_chat_template` use kar rahe hain jo khud hi sahi format mein convert kar dega.
# Agar pehle wala ValueError aaye toh `add_special_tokens=False` use kar sakte ho.
# Lekin Qwen models ke latest version mein yeh theek se kaam karta hai.
# Hum pehle wala (bug-free) Qwen logic use kar rahe hain, jo 7B mein kaam kar raha tha.
inputs = tokenizer.apply_chat_template(
messages,
add_special_tokens=True, # Qwen ka default template
return_tensors="pt"
)
inputs = inputs.to(model.device) # Input ko model ki device (GPU/CPU) par bhejte hain
# Model se response generate karte hain
output = model.generate(
inputs,
max_new_tokens=300,
temperature=0.7,
top_p=0.95,
# Agar response ruk jaye toh yeh zaroor daalna:
eos_token_id=tokenizer.eos_token_id
)
# Generated token IDs ko human-readable string mein decode karte hain
decoded = tokenizer.decode(output[0], skip_special_tokens=True)
# ✅ Qwen-specific reply extraction:
# Qwen ke output mein poora conversation history hota hai.
# Hum bas naye assistant response ko nikalenge.
# Pehle poori decoded string se 'system' prompt hata do, agar woh generated output mein ho.
# Example: <|im_start|>system...<|im_end|>
# Phir last 'assistant' turn ke baad wala part extract karo
try:
# Puraani conversation se naya reply nikalne ka try
# Qwen ka template `<|im_start|>assistant` se start hota hai
# Sahi extraction logic: last assistant tag ke baad wala text lo.
assistant_tag = tokenizer.chat_template.split("<|im_start|>assistant")[-1].split(tokenizer.eos_token)[0].strip()
# Simple split logic:
# decoded string se last "assistant" tag aur uske baad ke text ko nikalo
# NOTE: Agar pehle wala splitting logic (jo tumne use kiya tha) fail ho, toh yeh use karo:
# 1. Output se user ke last message ko nikal do, jo input mein tha.
# reply_start = decoded.rfind(message)
# partial_decoded = decoded[reply_start:]
# 2. Simplest logic: Last message ke baad ka part nikal lo
reply = decoded.split(message)[-1].strip()
# Agar reply mein koi bacha hua instruction tag aa raha ho, toh use hata do
if "assistant" in reply:
reply = reply.split("assistant")[-1].strip()
except Exception as e:
print(f"Extraction error: {e}")
# Agar splitting mein dikkat aaye toh poora decode kiya hua text return kar do.
# User ko kam se kam response mil jayega.
reply = decoded.split("assistant")[-1].strip() if "assistant" in decoded else decoded.strip()
return reply
# Gradio Chat Interface setup karte hain
ui = gr.ChatInterface(
chat_fn,
title="Captain Ambar — HF GPT Assistant",
# Description update kar diya hai
description="Running on HuggingFace 🟦 — Qwen2.5 0.3B Instruct",
)
ui.launch() |