kanana / app.py
r0mi's picture
Add application file
7c327a1
import gradio as gr
import torch
import time
from transformers import AutoTokenizer, AutoModelForCausalLM
# 모델 ID 설정
model_id = 'kakaocorp/kanana-nano-2.1b-instruct'
# 모델 및 토크나이저 로드 (모델은 한 번만 로드)
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.float32, # CPU 전용
)
# 텍스트 생성 함수
def generate_text(prompt):
try:
start_time = time.time()
messages = [{"role": "user", "content": prompt}]
input_ids = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt"
).to(model.device)
# 종료 토큰 (일반적으로 "<|endoftext|>" 하나로 충분)
eos_token_id = tokenizer.eos_token_id or tokenizer.convert_tokens_to_ids("<|endoftext|>")
outputs = model.generate(
input_ids,
max_new_tokens=512,
eos_token_id=eos_token_id,
do_sample=True,
temperature=0.4,
top_p=0.9,
top_k=50, # 안정성 향상
)
result = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
elapsed = round(time.time() - start_time, 3)
return f"{result}\n\n[응답 시간]: {elapsed}초"
except Exception as e:
return f"[오류 발생]: {str(e)}"
# Gradio UI 정의
iface = gr.Interface(
fn=generate_text,
inputs=gr.Textbox(lines=4, placeholder="프롬프트를 입력하세요...", label="입력"),
outputs=gr.Textbox(label="모델 응답"),
title="kanana-nano-2.1b-instruct 데모",
description="카카오브레인의 경량화 LLM: kakaocorp/kanana-nano-2.1b-instruct 기반 텍스트 생성",
)
# 실행
iface.launch()