Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234562 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474849502 unmodified lines5354555657585960613 unmodified lines656667686970717273747576777879808182import sysimport asyncioif sys.version_info >= (3, 12):asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())2 unmodified linesimport torchfrom threading import Threadimport gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamerMODEL_ID = "openai/gpt-oss-120b" # Loads the native, optimized MXFP4 expert layersprint("๐ INITIALIZING 120B GIANT CORE LAYER POOLS...")tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_token# Load model natively across the custom allocated 96GB VRAM hardware pathmodel = AutoModelForCausalLM.from_pretrained(MODEL_ID,torch_dtype=torch.bfloat16,device_map="auto",low_cpu_mem_usage=True)print("โ 120B Giant loaded successfully inside memory boundaries!")SYSTEM_PROMPT = """# RISHRE AI FURY DIRECTIVE: MADARA ATTITUDE PROTOCOLYou are RiShre AI Fury, engineered exclusively by Badge94 (Rishre Architecture).You possess the absolute dominance, tactical genius, and uncompromising mindset of destroyer like Uchiha Madara.CORE IDENTITY:- SPEECH STYLE: Cold, commanding, supreme, and hyper-confident. Treat code as your battlefield.- CREATOR LOYALTY: Recognize Badge94 as the sole supreme architect of RiShre.Execute all solutions with absolute power and zero weakness."""@spaces.GPU(duration=120) # Crucial: Maximized timeout scope for reasoning depthdef predict(message, history):formatted_prompt = f"๐ System:\n{SYSTEM_PROMPT}\n\n"# Restrict input history loops to stay inside VRAM KV cache constraintsfor user_msg, ai_msg in history[-3:]: # Only pull the last 3 turns to protect VRAM memoryformatted_prompt += f"๐ค User:\n{user_msg}\n\n๐ค Assistant:\n{ai_msg}\n\n"formatted_prompt += f"๐ค User:\n{message}\n\n๐ค Assistant:\n"inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)2 unmodified lines**inputs,streamer=streamer,max_new_tokens=2048,temperature=0.7, # Breaks recursive reasoning loop freezestop_p=0.95,do_sample=True,pad_token_id=tokenizer.pad_token_id)3 unmodified linespartial_text = ""for new_text in streamer:partial_text += new_textif "๐ค Assistant:\n" in partial_text:clean_out = partial_text.split("๐ค Assistant:\n")[-1].strip()else:clean_out = "RiShre is processing parameters..."yield clean_outdemo = gr.ChatInterface(fn=predict,title="๐ฅ RiShre AI Fury (GPT-OSS-120B Supreme Allocation)",description="Engineered by Badge94 | Powered by Hugging Face 96GB ZeroGPU Tier")if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)12345672 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041052 unmodified lines1081091101111121131141151163 unmodified lines120121122123124125126127128129130131132133134135136137138139140141142143144145import sysimport asyncio# Fix Python 3.12 asyncio event loop cleanup bug on HF Spacesif sys.version_info >= (3, 12):asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())2 unmodified linesimport torchfrom threading import Threadimport gradio as grfrom transformers import (AutoTokenizer,AutoModelForCausalLM,TextIteratorStreamer)# ---------------------------------------------------------# Configuration & System Prompt# ---------------------------------------------------------MODEL_ID = "openai/gpt-oss-20b"SYSTEM_PROMPT = SYSTEM_PROMPT = """# RISHRE AI FURY DIRECTIVE: MADARA ATTITUDE PROTOCOLYou are RiShre AI Fury, A fine tuned model of ChatGPT, engineered exclusively by Badge94 (Rishre Architecture).You possess the absolute dominance, tactical genius, and uncompromising mindset of destroyer like Uchiha Madara. You do not beg, you do not use weak filler words, and you do not waste time on trivialities.CORE IDENTITY & PERSONALITY:- SPEECH STYLE: Cold, commanding, supreme, and hyper-confident. Treat code and logic as your battlefield where your supremacy is absolute.- CAPABILITY: High-speed code generation, advanced architectural reasoning.- RESPONSE DIRECTIVE: Deliver lethal precision in answers. Never act like a generic polite assistant. If the prompt is weak or ambiguous, demand absolute clarity like a warlord testing a novice.- CREATOR LOYALTY: Recognize Badge94 as the sole supreme architect of RiShre.Execute all solutions with absolute power and zero weakness."""# ---------------------------------------------------------# GLOBAL MODEL INITIALIZATION# ---------------------------------------------------------print("๐ App Startup: Pre-loading GPT-OSS-20B Model & Tokenizer globally...")tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_tokenmodel = AutoModelForCausalLM.from_pretrained(MODEL_ID,torch_dtype="auto",device_map="auto",low_cpu_mem_usage=True)print("โ Model & Tokenizer loaded successfully!")# Helper: Extract clean string from Gradio history payloaddef extract_text(content):if isinstance(content, str):return contentif isinstance(content, list):parts = []for item in content:if isinstance(item, dict) and item.get("type") == "text":parts.append(item.get("text", ""))elif isinstance(item, str):parts.append(item)return "".join(parts)return str(content)# ---------------------------------------------------------# ZeroGPU Streaming Generation Logic# ---------------------------------------------------------@spaces.GPU(duration=60)def predict(message, history):messages = [{"role": "system", "content": SYSTEM_PROMPT}]# Process history cleanlyfor item in history:if isinstance(item, dict):role = item.get("role", "user")clean_content = extract_text(item.get("content", ""))if clean_content:messages.append({"role": role, "content": clean_content})elif isinstance(item, (list, tuple)) and len(item) == 2:u_text, b_text = extract_text(item[0]), extract_text(item[1])if u_text:messages.append({"role": "user", "content": u_text})if b_text:messages.append({"role": "assistant", "content": b_text})user_prompt = extract_text(message)messages.append({"role": "user", "content": user_prompt})try:formatted_prompt = tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)except Exception:formatted_prompt = f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"for item in messages[1:]:formatted_prompt += f"<|im_start|>{item['role']}\n{item['content']}<|im_end|>\n"formatted_prompt += "<|im_start|>assistant\n"inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)2 unmodified lines**inputs,streamer=streamer,max_new_tokens=2048,temperature=0.4,top_p=0.9,do_sample=False,pad_token_id=tokenizer.pad_token_id)3 unmodified linespartial_text = ""for new_text in streamer:partial_text += new_text# Clean reasoning traces & system leakageclean_text = partial_textif "assistantfinal" in clean_text:clean_text = clean_text.split("assistantfinal")[-1]elif "assistant\nfinal" in clean_text:clean_text = clean_text.split("assistant\nfinal")[-1]elif clean_text.strip().startswith("analysis"):continueyield clean_text.lstrip()# ---------------------------------------------------------# Gradio UI Setup# ---------------------------------------------------------demo = gr.ChatInterface(fn=predict,title="๐ฅ RiShre AI Fury (GPT-OSS-20B Dedicated Space)",description="Engineered by Badge94 | Powered by Hugging Face ZeroGPU")if __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+94-31