|
|
```python |
|
|
import spaces |
|
|
import torch |
|
|
import numpy as np |
|
|
from typing import Generator |
|
|
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer |
|
|
from config import MODEL_NAME, MAX_NEW_TOKENS, TEMPERATURE, DO_SAMPLE |
|
|
|
|
|
|
|
|
|
|
|
tokenizer = None |
|
|
model = None |
|
|
|
|
|
def initialize_model(): |
|
|
"""Initializes and loads the model and tokenizer once onto the GPU.""" |
|
|
global tokenizer, model |
|
|
if model is None: |
|
|
try: |
|
|
print(f"Loading model {MODEL_NAME}...") |
|
|
|
|
|
|
|
|
dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32 |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) |
|
|
model = AutoModelForCausalLM.from_pretrained( |
|
|
MODEL_NAME, |
|
|
torch_dtype=dtype, |
|
|
device_map="auto" |
|
|
) |
|
|
model.eval() |
|
|
|
|
|
|
|
|
if tokenizer.pad_token_id is None: |
|
|
tokenizer.pad_token_id = tokenizer.eos_token_id |
|
|
|
|
|
print("Model loaded successfully.") |
|
|
except Exception as e: |
|
|
print(f"Failed to load model: {e}") |
|
|
raise |
|
|
return tokenizer, model |
|
|
|
|
|
|
|
|
|
|
|
try: |
|
|
initialize_model() |
|
|
except Exception as e: |
|
|
print(f"Warning: Global model initialization failed: {e}. It will be re-attempted during the first inference call.") |
|
|
|
|
|
|
|
|
@spaces.GPU(duration=120) |
|
|
def stream_generate_response(prompt: str, history: list) -> Generator[str, None, None]: |
|
|
""" |
|
|
Generates a response from the KAT model, streaming output token by token. |
|
|
|
|
|
Args: |
|
|
prompt: The current user input. |
|
|
history: The accumulated chat history (list of [user_msg, bot_msg] tuples). |
|
|
|
|
|
Yields: |
|
|
str: Accumulated text response chunk. |
|
|
""" |
|
|
global tokenizer, model |
|
|
|
|
|
|
|
|
if model is None or tokenizer is None: |
|
|
initialize_model() |
|
|
|
|
|
|
|
|
messages = [] |
|
|
for human, bot in history: |
|
|
|
|
|
if human: |
|
|
messages.append({"role": "user", "content": human}) |
|
|
if bot: |
|
|
messages.append({"role": "assistant", "content": bot}) |
|
|
|
|
|
|
|
|
messages.append({"role": "user", "content": prompt}) |
|
|
|
|
|
|
|
|
text = tokenizer.apply_chat_template( |
|
|
messages, |
|
|
tokenize=False, |
|
|
add_generation_prompt=True, |
|
|
) |
|
|
|
|
|
|
|
|
model_inputs = tokenizer([text], return_tensors="pt").to(model.device) |
|
|
|
|
|
|
|
|
streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
input_ids = model_inputs.input_ids |
|
|
|
|
|
generated_ids = model.generate( |
|
|
input_ids=input_ids, |
|
|
max_new_tokens=MAX_NEW_TOKENS, |
|
|
do_sample=DO_SAMPLE, |
|
|
temperature=TEMPERATURE, |
|
|
pad_token_id=tokenizer.eos_token_id, |
|
|
return_dict_in_generate=True, |
|
|
output_scores=True, |
|
|
min_new_tokens=1, |
|
|
|
|
|
repetition_penalty=1.1, |
|
|
) |
|
|
|
|
|
full_response = "" |
|
|
|
|
|
for seq in generated_ids.sequences: |
|
|
|
|
|
new_tokens = seq[input_ids.shape[-1]:] |
|
|
|
|
|
|
|
|
current_response = tokenizer.decode(new_tokens, skip_special_tokens=True) |
|
|
|
|
|
|
|
|
if len(current_response) > len(full_response): |
|
|
new_text = current_response[len(full_response):] |
|
|
full_response = current_response |
|
|
yield new_text |
|
|
|
|
|
|
|
|
if full_response: |
|
|
yield full_response.strip() |
|
|
``` |