Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112132 unmodified lines1617181920212223242526272829303132333435363 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283841 unmodified line868788899091929394959697989910010110210310410510610710810911011111211311411512 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531542 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781792 unmodified lines1821831841851861871882 unmodified lines1911921931941951961971981992002012024 unmodified lines2072082092102112122131 unmodified line21521621721821922022122222322422522622722822923023123223323423523623710 unmodified lines24824925025125225325425525625725853 unmodified lines312313314315316317318319320321322323import osimport gradio as grimport torchimport numpy as npfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadfrom concurrent.futures import ThreadPoolExecutorimport loggingimport timeimport queueimport threadinglogging.basicConfig(level=logging.INFO)2 unmodified linesMODEL_ID = "YoussefElsafi/PlayerAI-1.2B-v1.5"# ── CPU Threading setup FIRST (before any torch ops) ─────────────────────────# On CPU, torch uses OpenMP/MKL threads internally.# Too many = thrashing. Formula: physical_cores / expected_concurrent_usersPHYSICAL_CORES = os.cpu_count() or 2MAX_CONCURRENT = 2 # how many generations run truly in parallelTHREADS_PER_GEN = max(1, PHYSICAL_CORES // MAX_CONCURRENT)torch.set_num_threads(THREADS_PER_GEN)torch.set_num_interop_threads(2)# Force MKL/OpenBLAS to respect our thread budget tooos.environ["OMP_NUM_THREADS"] = str(THREADS_PER_GEN)os.environ["MKL_NUM_THREADS"] = str(THREADS_PER_GEN)os.environ["OPENBLAS_NUM_THREADS"] = str(THREADS_PER_GEN)os.environ["VECLIB_MAXIMUM_THREADS"]= str(THREADS_PER_GEN)os.environ["NUMEXPR_NUM_THREADS"] = str(THREADS_PER_GEN)logger.info(f"CPU cores: {PHYSICAL_CORES} | "f"Concurrent gens: {MAX_CONCURRENT} | "3 unmodified linesprint("Loading model...")tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)# On CPU: bfloat16 is FASTER than float32 on modern x86 (AVX-512 bf16 support)# Falls back gracefully if not supportedif torch.cuda.is_available():DTYPE = torch.float16DEVICE = "cuda"elif hasattr(torch, 'bfloat16') and torch.backends.cpu.is_avx512_bf16_supported():DTYPE = torch.bfloat16DEVICE = "cpu"logger.info("AVX-512 BF16 detected — using bfloat16")else:DTYPE = torch.float32DEVICE = "cpu"model = AutoModelForCausalLM.from_pretrained(MODEL_ID,torch_dtype = DTYPE,device_map = "cpu" if DEVICE == "cpu" else "auto",trust_remote_code = True,low_cpu_mem_usage = True,)model.eval()# ── INT8 dynamic quantization (biggest CPU speedup: ~2x faster, ~2x less RAM) ─# Works on Linear layers — the bulk of transformer computetry:model = torch.quantization.quantize_dynamic(model,{torch.nn.Linear},dtype=torch.qint8,)logger.info("INT8 dynamic quantization applied ✓")except Exception as e:logger.warning(f"Quantization skipped: {e}")# ── torch.compile (PyTorch 2.0+) ──────────────────────────────────────────────# "default" mode works better than "reduce-overhead" on CPUif hasattr(torch, "compile"):try:model = torch.compile(model, mode="default", backend="inductor")logger.info("torch.compile applied ✓")except Exception as e:logger.warning(f"torch.compile skipped: {e}")1 unmodified lineprint("Model loaded!")# ── Generation config ─────────────────────────────────────────────────────────# Shorter = faster. For chat, 80 tokens is plenty.GEN_CONFIG = dict(max_new_tokens = 80, # was 120 — shaves ~33% off latencydo_sample = True,temperature = 0.85,top_p = 0.9,# repetition_penalty speeds up sampling by pruning logitsrepetition_penalty = 1.1,pad_token_id = tokenizer.eos_token_id,# Use cache — critical for autoregressive speeduse_cache = True,)# ── Thread pool ───────────────────────────────────────────────────────────────executor = ThreadPoolExecutor(max_workers = MAX_CONCURRENT,thread_name_prefix = "gen",)# ── Request queue + priority ───────────────────────────────────────────────────# Caps in-flight requests so we don't OOM with 16GB RAM# 1.2B model in int8 ≈ 1.2GB, each active KV cache ≈ 200MB# So 2 concurrent is safe, queue up to 8 waitingMAX_QUEUE = 8gen_semaphore = threading.Semaphore(MAX_CONCURRENT)queue_counter = threading.Semaphore(MAX_QUEUE)12 unmodified lines"Use lowercase, slang, and act like a real person chatting.")# ── Prompt cache ───────────────────────────────────────────────────────────────# System prompt tokenized once and reused — saves ~5ms per request_SYSTEM_MESSAGES = [{"role": "system", "content": SYSTEM_PROMPT}]try:_SYSTEM_PROMPT_PREFIX = tokenizer.apply_chat_template(_SYSTEM_MESSAGES,tokenize=False,add_generation_prompt=False,)except Exception:_SYSTEM_PROMPT_PREFIX = ""# ── Core generation ────────────────────────────────────────────────────────────def _run_generation(prompt: str, streamer: TextIteratorStreamer) -> None:inputs = tokenizer(prompt,return_tensors = "pt",truncation = True,max_length = 512, # hard cap — prevents runaway long contexts)# No .to(device) needed — model is already on cpuwith torch.inference_mode():model.generate(input_ids = inputs.input_ids,2 unmodified lines**GEN_CONFIG,)# ── Streaming response ────────────────────────────────────────────────────────def respond(message: str, history: list, api_key: str):if not validate_key(api_key):yield "[error] unauthorized"return# Queue guard — reject if backlog is fullif not queue_counter.acquire(blocking=False):yield "[error] server busy — try again in a moment"returntry:# Build prompt — keep history short to limit context length# Long contexts = slow prefill on CPUMAX_HISTORY = 4 # last 4 turns onlytrimmed_history = history[-MAX_HISTORY:] if len(history) > MAX_HISTORY else historymessages = [{"role": "system", "content": SYSTEM_PROMPT}]messages.extend(trimmed_history)2 unmodified linestry:prompt = tokenizer.apply_chat_template(messages,tokenize = False,add_generation_prompt = True,)except Exception as e:2 unmodified linesstreamer = TextIteratorStreamer(tokenizer,skip_prompt = True,skip_special_tokens= True,timeout = 60.0,)# Acquire generation slot (blocks if MAX_CONCURRENT already running)gen_semaphore.acquire()try:future = executor.submit(_run_generation, prompt, streamer)4 unmodified linesyield responsefuture.result(timeout=10)finally:gen_semaphore.release()1 unmodified linequeue_counter.release()# ── Warm-up ────────────────────────────────────────────────────────────────────# Run one dummy generation at startup so the first real user isn't slow.# torch.compile needs a first pass to JIT-compile the graph.def _warmup():logger.info("Running warmup generation...")t0 = time.time()try:dummy_streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=120.0)dummy_prompt = tokenizer.apply_chat_template([{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": "hi"}],tokenize=False,add_generation_prompt=True,)inputs = tokenizer(dummy_prompt, return_tensors="pt", truncation=True, max_length=256)warmup_cfg = {**GEN_CONFIG, "max_new_tokens": 20}def _gen():10 unmodified linesfor _ in dummy_streamer:passt.join()logger.info(f"Warmup done in {time.time()-t0:.2f}s ✓")except Exception as e:logger.warning(f"Warmup failed (non-fatal): {e}")# Run warmup in background so server starts immediatelyThread(target=_warmup, daemon=True).start()53 unmodified linesstored_key = gr.Textbox(value="", visible=False)chatbot = gr.Chatbot(type = "messages",avatar_images = (USER_AVATAR, BOT_AVATAR),height = 500,show_label = False,bubble_full_width= False,show_copy_button = False,)gr.ChatInterface(12345678910112 unmodified lines1415161718192021222324252627282930313 unmodified lines353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified line88899091929394959697989910010110210310410510612 unmodified lines1191201211221231241251261271281291301311322 unmodified lines1351361371381391401411421431441451461471481491501511521532 unmodified lines1561571581591601611622 unmodified lines1651661671681691701711721731741754 unmodified lines1801811821831841851 unmodified line18718818919019119219319419519619719819920020120220320420520620720820921021110 unmodified lines22222322422522622722822923023153 unmodified lines285286287288289290291292293294295296import osimport gradio as grimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamerfrom threading import Threadfrom concurrent.futures import ThreadPoolExecutorimport loggingimport timeimport threadinglogging.basicConfig(level=logging.INFO)2 unmodified linesMODEL_ID = "YoussefElsafi/PlayerAI-1.2B-v1.5"# ── CPU Threading setup FIRST (before any torch ops) ─────────────────────────PHYSICAL_CORES = os.cpu_count() or 2MAX_CONCURRENT = 2THREADS_PER_GEN = max(1, PHYSICAL_CORES // MAX_CONCURRENT)torch.set_num_threads(THREADS_PER_GEN)torch.set_num_interop_threads(2)os.environ["OMP_NUM_THREADS"] = str(THREADS_PER_GEN)os.environ["MKL_NUM_THREADS"] = str(THREADS_PER_GEN)os.environ["OPENBLAS_NUM_THREADS"] = str(THREADS_PER_GEN)os.environ["VECLIB_MAXIMUM_THREADS"] = str(THREADS_PER_GEN)os.environ["NUMEXPR_NUM_THREADS"] = str(THREADS_PER_GEN)logger.info(f"CPU cores: {PHYSICAL_CORES} | "f"Concurrent gens: {MAX_CONCURRENT} | "3 unmodified linesprint("Loading model...")tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)# ── Safe dtype detection (works on ALL torch versions) ────────────────────────def _pick_dtype() -> torch.dtype:if torch.cuda.is_available():logger.info("Device: CUDA — using float16")return torch.float16# bfloat16 on CPU: supported natively on Ampere+ and some Intel CPUs.# We probe by actually trying a small bf16 op instead of relying on# version-specific API calls that may not exist.try:_ = torch.zeros(4, dtype=torch.bfloat16) @ torch.zeros(4, dtype=torch.bfloat16)logger.info("Device: CPU — bfloat16 probe passed, using bfloat16")return torch.bfloat16except Exception:logger.info("Device: CPU — bfloat16 not supported, using float32")return torch.float32DTYPE = _pick_dtype()DEVICE = "cuda" if torch.cuda.is_available() else "cpu"model = AutoModelForCausalLM.from_pretrained(MODEL_ID,torch_dtype = DTYPE,device_map = "auto" if DEVICE == "cuda" else "cpu",trust_remote_code = True,low_cpu_mem_usage = True,)model.eval()# ── INT8 dynamic quantization ─────────────────────────────────────────────────# ~2× faster inference, ~50% less RAM. Only apply on CPU.if DEVICE == "cpu":try:model = torch.quantization.quantize_dynamic(model,{torch.nn.Linear},dtype=torch.qint8,)logger.info("INT8 dynamic quantization applied ✓")except Exception as e:logger.warning(f"Quantization skipped: {e}")# ── torch.compile ─────────────────────────────────────────────────────────────if hasattr(torch, "compile"):try:model = torch.compile(model, mode="default")logger.info("torch.compile applied ✓")except Exception as e:logger.warning(f"torch.compile skipped: {e}")1 unmodified lineprint("Model loaded!")# ── Generation config ─────────────────────────────────────────────────────────GEN_CONFIG = dict(max_new_tokens = 80,do_sample = True,temperature = 0.85,top_p = 0.9,repetition_penalty = 1.1,pad_token_id = tokenizer.eos_token_id,use_cache = True,)# ── Thread pool + semaphores ──────────────────────────────────────────────────executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT, thread_name_prefix="gen")MAX_QUEUE = 8gen_semaphore = threading.Semaphore(MAX_CONCURRENT)queue_counter = threading.Semaphore(MAX_QUEUE)12 unmodified lines"Use lowercase, slang, and act like a real person chatting.")# ── Core generation ────────────────────────────────────────────────────────────def _run_generation(prompt: str, streamer: TextIteratorStreamer) -> None:inputs = tokenizer(prompt,return_tensors = "pt",truncation = True,max_length = 512,)with torch.inference_mode():model.generate(input_ids = inputs.input_ids,2 unmodified lines**GEN_CONFIG,)# ── Streaming response ─────────────────────────────────────────────────────────def respond(message: str, history: list, api_key: str):if not validate_key(api_key):yield "[error] unauthorized"returnif not queue_counter.acquire(blocking=False):yield "[error] server busy — try again in a moment"returntry:MAX_HISTORY = 4trimmed_history = history[-MAX_HISTORY:]messages = [{"role": "system", "content": SYSTEM_PROMPT}]messages.extend(trimmed_history)2 unmodified linestry:prompt = tokenizer.apply_chat_template(messages,tokenize = False,add_generation_prompt = True,)except Exception as e:2 unmodified linesstreamer = TextIteratorStreamer(tokenizer,skip_prompt = True,skip_special_tokens = True,timeout = 60.0,)gen_semaphore.acquire()try:future = executor.submit(_run_generation, prompt, streamer)4 unmodified linesyield responsefuture.result(timeout=10)finally:gen_semaphore.release()1 unmodified linequeue_counter.release()# ── Warmup ────────────────────────────────────────────────────────────────────def _warmup():logger.info("Running warmup generation...")t0 = time.time()try:dummy_streamer = TextIteratorStreamer(tokenizer,skip_prompt = True,skip_special_tokens = True,timeout = 120.0,)dummy_prompt = tokenizer.apply_chat_template([{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": "hi"}],tokenize = False,add_generation_prompt = True,)inputs = tokenizer(dummy_prompt, return_tensors="pt",truncation=True, max_length=256)warmup_cfg = {**GEN_CONFIG, "max_new_tokens": 20}def _gen():10 unmodified linesfor _ in dummy_streamer:passt.join()logger.info(f"Warmup done in {time.time() - t0:.2f}s ✓")except Exception as e:logger.warning(f"Warmup failed (non-fatal): {e}")Thread(target=_warmup, daemon=True).start()53 unmodified linesstored_key = gr.Textbox(value="", visible=False)chatbot = gr.Chatbot(type = "messages",avatar_images = (USER_AVATAR, BOT_AVATAR),height = 500,show_label = False,bubble_full_width = False,show_copy_button = False,)gr.ChatInterface(
app.py+78-105