Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758592 unmodified lines626364656667686970717273747576777879808182838485import streamlit as stfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadimport torch# 1. Page Configuration (Centered and No Sidebar)st.set_page_config(page_title="Qwen 3 0.6B Chat",page_icon="⚡",layout="centered",initial_sidebar_state="collapsed")# Custom CSS to hide the sidebar toggle button entirelyst.markdown("<style>[data-testid='collapsedControl'] { display: none; }</style>", unsafe_allow_html=True)# 2. Model & Tokenizer Initialization (Using your direct load logic)MODEL_ID = "Qwen/Qwen3-0.6B"@st.cache_resourcedef load_llm():# Loading the tokenizer and model directly as requestedtokenizer = AutoTokenizer.from_pretrained(MODEL_ID)model = AutoModelForCausalLM.from_pretrained(MODEL_ID,device_map="auto",torch_dtype="auto")return tokenizer, modeltokenizer, model = load_llm()# 3. Chat UI Logicst.title("⚡ Qwen 3 0.6B")st.caption("Using your direct-load logic with real-time streaming.")if "messages" not in st.session_state:st.session_state.messages = []# Display historyfor msg in st.session_state.messages:with st.chat_message(msg["role"]):st.markdown(msg["content"])# 4. Input & Streaming Generationif prompt := st.chat_input("Ask Qwen 3..."):# Store and display user messagest.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)with st.chat_message("assistant"):# Initialize the streamerstreamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)# Using your chat template logicinputs = tokenizer.apply_chat_template(st.session_state.messages,add_generation_prompt=True,2 unmodified linesreturn_tensors="pt",).to(model.device)# Background thread for generationgeneration_kwargs = dict(**inputs,streamer=streamer,max_new_tokens=512,do_sample=True,temperature=0.7,top_p=0.8,pad_token_id=tokenizer.eos_token_id)thread = Thread(target=model.generate, kwargs=generation_kwargs)thread.start()# Update the UI as tokens arriveplaceholder = st.empty()full_response = ""for new_text in streamer:full_response += new_textplaceholder.markdown(full_response + "▌")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162632 unmodified lines66676869707172737475767778798081828384858687import streamlit as stfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfigfrom threading import Threadimport torch# UI Setup (No Sidebar as requested)st.set_page_config(page_title="Qwen 2.5 32B Chat", page_icon="🐘", layout="centered", initial_sidebar_state="collapsed")st.markdown("<style>[data-testid='collapsedControl'] { display: none; }</style>", unsafe_allow_html=True)# 1. Model Configuration (Quantized to fit on 24GB VRAM or 32GB RAM)MODEL_ID = "Qwen/Qwen2.5-32B-Instruct"@st.cache_resourcedef load_llm():tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)# 4-bit config allows this 64GB model to fit in ~18-20GB of memoryquant_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_compute_dtype=torch.float16,bnb_4bit_quant_type="nf4")model = AutoModelForCausalLM.from_pretrained(MODEL_ID,quantization_config=quant_config,device_map="auto" # Automatically splits between GPU and CPU)return tokenizer, modeltokenizer, model = load_llm()# 2. Chat Interfacest.title("🐘 Qwen 2.5 32B")st.caption("Running high-parameter model with 4-bit quantization")if "messages" not in st.session_state:st.session_state.messages = []# Action Buttonif st.button("Clear History"):st.session_state.messages = []st.rerun()# Display historyfor msg in st.session_state.messages:with st.chat_message(msg["role"]):st.markdown(msg["content"])# 3. Chat Logic with your exact Template Codeif prompt := st.chat_input("Message Qwen 2.5 32B..."):st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user"):st.markdown(prompt)with st.chat_message("assistant"):# Setup Streamerstreamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)# YOUR EXACT LOGIC: Applying the chat templateinputs = tokenizer.apply_chat_template(st.session_state.messages,add_generation_prompt=True,2 unmodified linesreturn_tensors="pt",).to(model.device)# Threading for live streaminggeneration_kwargs = dict(**inputs,streamer=streamer,max_new_tokens=512,do_sample=True,temperature=0.7,pad_token_id=tokenizer.eos_token_id)thread = Thread(target=model.generate, kwargs=generation_kwargs)thread.start()# Word-by-word UI updateplaceholder = st.empty()full_response = ""for new_text in streamer:full_response += new_textplaceholder.markdown(full_response + "▌")
app.py+29-27