Spaces:
Paused
Paused
File size: 6,101 Bytes
dc3c90f ec8c77c dc3c90f 0000060 dc3c90f | 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | import spaces
import gradio as gr
import torch
import time
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
# ============================================================
# CONFIG
# ============================================================
MODEL_NAME = "rikunarita/Qwen3-4B-Thinking-2507-Genius-Coder"
LORA_MODEL_NAME = "rahul7star/Qwen3-4B-Thinking-2509-Genius-Coder-AI"
MAX_INPUT_TOKENS = 4096
MAX_NEW_TOKENS = 4096
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# ============================================================
# LOAD TOKENIZER
# ============================================================
print("Loading tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
# ============================================================
# LOAD BASE MODEL
# ============================================================
print("Loading base model...")
base_model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME,
torch_dtype="auto",
device_map="auto",
)
base_model.eval()
print("Base model loaded successfully")
# ============================================================
# OPTIONAL LORA LOAD
# ============================================================
model = base_model
lora_loaded = False
try:
print("Attempting to load LoRA adapter...")
model = PeftModel.from_pretrained(
base_model,
LORA_MODEL_NAME,
torch_dtype="auto",
)
model.eval()
lora_loaded = True
print("β
LoRA loaded successfully")
except Exception as e:
print("β οΈ LoRA not loaded:", e)
model = base_model
lora_loaded = False
# ============================================================
# SYSTEM PROMPT
# ============================================================
SYSTEM_PROMPT = """You are a professional AI Coding Assistant.
Your responses must be:
- Clear and concise
- Well-structured with headings and bullet points
- Technically accurate
- Written in a formal, professional tone
- Focused on best practices and production-quality code
"""
# ============================================================
# GENERATION FUNCTION
# ============================================================
@spaces.GPU()
def generate_answer(question, max_tokens, use_lora):
print("\n================ GENERATE ANSWER START ================")
if not question or not question.strip():
return "Please enter a valid question."
try:
start_time = time.time()
active_model = model if (use_lora and lora_loaded) else base_model
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question.strip()},
]
prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
inputs = tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=MAX_INPUT_TOKENS,
).to(DEVICE)
input_token_count = inputs.input_ids.shape[-1]
print(f"Input tokens: {input_token_count}")
max_tokens = min(int(max_tokens), MAX_NEW_TOKENS)
print(f"Final max_new_tokens: {max_tokens}")
print("π Starting generation...")
with torch.no_grad():
output = active_model.generate(
**inputs,
max_new_tokens=max_tokens,
do_sample=False,
repetition_penalty=1.05,
use_cache=True,
pad_token_id=tokenizer.eos_token_id,
eos_token_id=tokenizer.eos_token_id,
)
print("β
Generation finished")
generated_tokens = output[0][input_token_count:]
response = tokenizer.decode(
generated_tokens,
skip_special_tokens=True,
)
print(response)
print(f"Generated tokens: {generated_tokens.shape[-1]}")
print(f"β± Total time: {time.time() - start_time:.2f} sec")
print("================ GENERATE ANSWER END ==================\n")
return response.strip() or "No output generated."
except Exception as e:
import traceback
traceback.print_exc()
if torch.cuda.is_available():
torch.cuda.empty_cache()
return f"Error occurred: {str(e)}"
# ============================================================
# UI
# ============================================================
with gr.Blocks() as demo:
gr.Markdown(
"""
# π€ Professional Coding Assistant
**Qwen3-4B + Optional LoRA**
- β‘ Stable GPU inference
- π§ Deterministic responses
- π» Production-quality code
"""
)
question = gr.Textbox(
label="Your Question",
placeholder="Explain Quick Sort with complexity and a Python example",
value="write a python code using pytorch for a simple neural network demo",
lines=4,
)
answer = gr.Markdown(label="AI Response", elem_id="answer_box")
max_tokens = gr.Slider(
64, 4096, value=1024, step=32, label="Max New Tokens"
)
use_lora = gr.Checkbox(
value=lora_loaded,
label="Enable LoRA Adapter"
)
with gr.Row():
submit = gr.Button("Generate Answer", variant="primary")
copy_btn = gr.Button("π Copy Response")
clear = gr.Button("Clear")
submit.click(
fn=generate_answer,
inputs=[question, max_tokens, use_lora],
outputs=answer,
)
clear.click(
fn=lambda: ("", ""),
outputs=[question, answer],
)
copy_btn.click(
fn=None,
js="""
() => {
const el = document.querySelector('#answer_box');
navigator.clipboard.writeText(el.innerText);
}
""",
)
demo.launch(
theme=gr.themes.Soft(),
css="""
.gradio-container { max-width: 900px !important; margin: auto; }
textarea { font-size: 14px !important; }
""",
) |