Spaces:
Sleeping
Sleeping
Update app.py
Browse files12 unmodified lines1314151617181915 unmodified lines353637383940414243444546474849505152535455565758596061626364656667686970711 unmodified line7374757677787918 unmodified lines989910010110210310410510610710810 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515610 unmodified lines1671681691701711721735 unmodified lines1791801811821831841851 unmodified line18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423533 unmodified lines26927027127227327427512 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)15 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(1 unmodified line{torch.nn.Linear},dtype=torch.qint8,)logger.info("INT8 dynamic quantization applied ✓")except Exception as e:logger.warning(f"Quantization skipped: {e}")18 unmodified linesuse_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)# ── Auth ──────────────────────────────────────────────────────────────────────ALLOWED_TOKEN = os.environ.get("PLAYERAI_API_KEYS", "")10 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,attention_mask = inputs.attention_mask,streamer = streamer,**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)messages.append({"role": "user", "content": message})try:10 unmodified linestokenizer,skip_prompt = True,skip_special_tokens = True,timeout = 60.0,)gen_semaphore.acquire()5 unmodified linesresponse += tokenyield 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():with torch.inference_mode():model.generate(input_ids = inputs.input_ids,attention_mask = inputs.attention_mask,streamer = dummy_streamer,**warmup_cfg,)t = Thread(target=_gen)t.start()for _ 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()# ── CSS ────────────────────────────────────────────────────────────────────────custom_css = """@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');* { font-family: 'Press Start 2P', monospace !important; border-radius: 0 !important; }33 unmodified linesUSER_AVATAR = "face.png"BOT_AVATAR = "question.png"# ── UI ─────────────────────────────────────────────────────────────────────────with gr.Blocks(css=custom_css, theme=gr.themes.Base()) as demo:with gr.Column(elem_id="lock-screen", visible=True) as lock_screen:12 unmodified lines1314151617181915 unmodified lines35363738394041424344454647484950515253545556575859606162636465661 unmodified line6869707172737418 unmodified lines9394959697989910010110210 unmodified lines11311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615710 unmodified lines1681691701711721731745 unmodified lines1801811821831841851861871881891901911921 unmodified line19419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825933 unmodified lines29329429529629729829912 unmodified linesMODEL_ID = "YoussefElsafi/PlayerAI-1.2B-v1.5"# ── CPU threading (set BEFORE any torch ops) ──────────────────────────────────PHYSICAL_CORES = os.cpu_count() or 2MAX_CONCURRENT = 2THREADS_PER_GEN = max(1, PHYSICAL_CORES // MAX_CONCURRENT)15 unmodified linesprint("Loading model...")tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)# Detect deviceif torch.cuda.is_available():DEVICE = "cuda"DTYPE = torch.float16logger.info("Device: CUDA — float16")else:DEVICE = "cpu"# INT8 quantization REQUIRES float32 weights as input.# bfloat16 + quantize_dynamic = RuntimeError.# So always load as float32 on CPU — quantization shrinks it afterwards.DTYPE = torch.float32logger.info("Device: CPU — float32 (INT8 quantization will halve this)")model = AutoModelForCausalLM.from_pretrained(MODEL_ID,dtype = DTYPE, # 'dtype' replaces deprecated 'torch_dtype'device_map = "auto" if DEVICE == "cuda" else "cpu",trust_remote_code = True,low_cpu_mem_usage = True,)model.eval()# ── INT8 dynamic quantization (CPU only, after loading as float32) ────────────# Converts Linear weight storage to int8 at runtime.# Result: ~2× faster matmuls, ~50% less RAM, no accuracy loss for inference.# Must happen BEFORE torch.compile.if DEVICE == "cpu":try:model = torch.quantization.quantize_dynamic(1 unmodified line{torch.nn.Linear},dtype=torch.qint8,)logger.info("INT8 quantization applied ✓")except Exception as e:logger.warning(f"Quantization skipped: {e}")18 unmodified linesuse_cache = True,)# ── Thread pool + concurrency guards ─────────────────────────────────────────executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT, thread_name_prefix="gen")gen_semaphore = threading.Semaphore(MAX_CONCURRENT)queue_counter = threading.Semaphore(8) # max 8 requests waiting# ── Auth ──────────────────────────────────────────────────────────────────────ALLOWED_TOKEN = os.environ.get("PLAYERAI_API_KEYS", "")10 unmodified lines"Use lowercase, slang, and act like a real person chatting.")# ── Core generation (runs in thread pool) ─────────────────────────────────────def _run_generation(prompt: str, streamer: TextIteratorStreamer) -> None:try:inputs = tokenizer(prompt,return_tensors = "pt",truncation = True,max_length = 512,)with torch.inference_mode():model.generate(input_ids = inputs.input_ids,attention_mask = inputs.attention_mask,streamer = streamer,**GEN_CONFIG,)except Exception as e:# Put the error into the streamer queue so the iterator unblocks# instead of hanging until timeoutlogger.error(f"Generation error: {e}")streamer.text_queue.put(streamer.stop_signal)raise# ── 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 shortly"returntry:# Trim history to keep context short (long context = slow CPU prefill)trimmed = history[-4:] if len(history) > 4 else historymessages = [{"role": "system", "content": SYSTEM_PROMPT}]messages.extend(trimmed)messages.append({"role": "user", "content": message})try:10 unmodified linestokenizer,skip_prompt = True,skip_special_tokens = True,timeout = 120.0, # generous — CPU is slow)gen_semaphore.acquire()5 unmodified linesresponse += tokenyield response# Raise any exception from the worker threadfuture.result(timeout=10)except Exception as e:logger.error(f"respond() error: {e}")if not response:yield f"[error] generation failed"finally:gen_semaphore.release()1 unmodified linequeue_counter.release()# ── Warmup (runs in background, errors are non-fatal) ────────────────────────def _warmup():logger.info("Warmup starting...")t0 = time.time()try: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 = 128,)dummy_streamer = TextIteratorStreamer(tokenizer,skip_prompt = True,skip_special_tokens = True,timeout = 300.0, # first compile pass can take minutes)warmup_cfg = {**GEN_CONFIG, "max_new_tokens": 10}def _gen():try:with torch.inference_mode():model.generate(input_ids = inputs.input_ids,attention_mask = inputs.attention_mask,streamer = dummy_streamer,**warmup_cfg,)except Exception as e:logger.error(f"Warmup _gen error: {e}")# Unblock the iterator so warmup doesn't hang foreverdummy_streamer.text_queue.put(dummy_streamer.stop_signal)t = Thread(target=_gen, daemon=True)t.start()tokens_generated = 0for tok in dummy_streamer:tokens_generated += 1t.join(timeout=30)logger.info(f"Warmup done in {time.time()-t0:.1f}s "f"({tokens_generated} tokens) ✓")except Exception as e:# Warmup failing is OK — first real request will be slow but it workslogger.warning(f"Warmup failed (non-fatal): {e}")Thread(target=_warmup, daemon=True).start()# ── CSS ───────────────────────────────────────────────────────────────────────custom_css = """@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');* { font-family: 'Press Start 2P', monospace !important; border-radius: 0 !important; }33 unmodified linesUSER_AVATAR = "face.png"BOT_AVATAR = "question.png"# ── UI ────────────────────────────────────────────────────────────────────────with gr.Blocks(css=custom_css, theme=gr.themes.Base()) as demo:with gr.Column(elem_id="lock-screen", visible=True) as lock_screen:
app.py+96-72