Spaces:
Sleeping
Sleeping
Update app.py
Browse files12 unmodified lines131415161617181915 unmodified lines3536373839404142434445464748495051525354555638394041424344454647484950515260535455565758596768606162636465661 unmodified line686970767172737418 unmodified lines9394951019697103981059910010110210 unmodified lines11311411512211611712412512612712812913013113213313413511811912012112212312412512612712812913013113213313413513613713813813914014114214314414514514614714814914915015015115215315315415515615710 unmodified lines1681691701701711721731745 unmodified lines1801811821831841851861871881891901911921 unmodified line19419519619019719819219920020119519619719819920020220320420520620720720820920820921021121221321421521621721821922022122222322422521221321421521621721821922022622722822923023123223323423523623723823922222322422524024124224324424524624724824925025125225325425523225625725825933 unmodified lines29329429527229629729829912 unmodified lines
MODEL_ID = "YoussefElsafi/PlayerAI-1.2B-v1.5"
# ── CPU Threading setup FIRST (before any torch ops) ─────────────────────────# ── 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)
# ── 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.bfloat16 except Exception: logger.info("Device: CPU — bfloat16 not supported, using float32") return torch.float32
DTYPE = _pick_dtype()DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Detect deviceif torch.cuda.is_available(): DEVICE = "cuda" DTYPE = torch.float16 logger.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.float32 logger.info("Device: CPU — float32 (INT8 quantization will halve this)")
model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype = DTYPE, 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 ─────────────────────────────────────────────────# ~2× faster inference, ~50% less RAM. Only apply on CPU.# ── 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 dynamic quantization applied ✓") logger.info("INT8 quantization applied ✓") except Exception as e: logger.warning(f"Quantization skipped: {e}")
18 unmodified lines use_cache = True,)
# ── Thread pool + semaphores ──────────────────────────────────────────────────# ── Thread pool + concurrency guards ─────────────────────────────────────────executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT, thread_name_prefix="gen")MAX_QUEUE = 8gen_semaphore = threading.Semaphore(MAX_CONCURRENT)queue_counter = threading.Semaphore(MAX_QUEUE)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 ────────────────────────────────────────────────────────────# ── Core generation (runs in thread pool) ─────────────────────────────────────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, 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 timeout logger.error(f"Generation error: {e}") streamer.text_queue.put(streamer.stop_signal) raise
# ── Streaming response ─────────────────────────────────────────────────────────# ── Streaming response ────────────────────────────────────────────────────────def respond(message: str, history: list, api_key: str): if not validate_key(api_key): yield "[error] unauthorized" return
if not queue_counter.acquire(blocking=False): yield "[error] server busy — try again in a moment" yield "[error] server busy — try again shortly" return
try: MAX_HISTORY = 4 trimmed_history = history[-MAX_HISTORY:] # Trim history to keep context short (long context = slow CPU prefill) trimmed = history[-4:] if len(history) > 4 else history
messages = [{"role": "system", "content": SYSTEM_PROMPT}] messages.extend(trimmed_history) messages.extend(trimmed) messages.append({"role": "user", "content": message})
try:10 unmodified lines tokenizer, skip_prompt = True, skip_special_tokens = True, timeout = 60.0, timeout = 120.0, # generous — CPU is slow )
gen_semaphore.acquire()5 unmodified lines response += token yield response
# Raise any exception from the worker thread future.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 line queue_counter.release()
# ── Warmup ────────────────────────────────────────────────────────────────────# ── Warmup (runs in background, errors are non-fatal) ────────────────────────def _warmup(): logger.info("Running warmup generation...") logger.info("Warmup starting...") 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} 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, )
t = Thread(target=_gen) 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 forever dummy_streamer.text_queue.put(dummy_streamer.stop_signal)
t = Thread(target=_gen, daemon=True) t.start() for _ in dummy_streamer: pass t.join() logger.info(f"Warmup done in {time.time() - t0:.2f}s ✓")
tokens_generated = 0 for tok in dummy_streamer: tokens_generated += 1
t.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 works logger.warning(f"Warmup failed (non-fatal): {e}")
Thread(target=_warmup, daemon=True).start()
# ── CSS ────────────────────────────────────────────────────────────────────────# ── 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 ─────────────────────────────────────────────────────────────────────────# ── 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