Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
# BitsAndBytesConfigλ₯Ό import ν©λλ€.
|
3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
4 |
+
import time
|
5 |
+
import logging
|
6 |
+
import os
|
7 |
+
import json
|
8 |
+
from datetime import datetime
|
9 |
+
|
10 |
+
# --- μ€μ ---
|
11 |
+
# μ¬μ©ν μμνλ λͺ¨λΈ IDλ‘ λ³κ²½!
|
12 |
+
MODEL_ID = "unsloth/gemma-3-1b-it-bnb-4bit"
|
13 |
+
# CPU μ¬μ© (HF Spaces λ¬΄λ£ ν°μ΄ κΈ°μ€)
|
14 |
+
DEVICE = "cpu"
|
15 |
+
# λ©λͺ¨λ¦¬ νμΌ κ²½λ‘
|
16 |
+
MEMORY_FILE = "thought_memory.json"
|
17 |
+
# μκ° μ£ΌκΈ° (μ΄) - CPUμμλ μΆλ‘ μκ°μ΄ 걸릴 μ μμΌλ―λ‘ κ°κ²©μ λλν λ‘λλ€.
|
18 |
+
THINKING_INTERVAL_SECONDS = 120 # μ: 2λΆλ§λ€ μκ°
|
19 |
+
# μμ±ν μ΅λ ν ν° μ
|
20 |
+
MAX_NEW_TOKENS = 150
|
21 |
+
# μ΄κΈ° μκ° ν둬ννΈ
|
22 |
+
INITIAL_PROMPT = "λλ κ³μν΄μ μ€μ€λ‘ μκ°νλ AIμ
λλ€. λμ 첫 λ²μ§Έ μκ°μ λ€μκ³Ό κ°μ΅λλ€:"
|
23 |
+
|
24 |
+
# λ‘κΉ
μ€μ
|
25 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
26 |
+
|
27 |
+
def load_memory():
|
28 |
+
"""λ©λͺ¨λ¦¬ νμΌμμ μ΄μ μκ° κΈ°λ‘μ λ‘λν©λλ€."""
|
29 |
+
if os.path.exists(MEMORY_FILE):
|
30 |
+
try:
|
31 |
+
with open(MEMORY_FILE, 'r', encoding='utf-8') as f:
|
32 |
+
memory = json.load(f)
|
33 |
+
if not isinstance(memory, list):
|
34 |
+
logging.warning(f"{MEMORY_FILE} λ΄μ©μ΄ 리μ€νΈκ° μλλ―λ‘ μ΄κΈ°νν©λλ€.")
|
35 |
+
return []
|
36 |
+
logging.info(f"{len(memory)}κ°μ μ΄μ μκ°μ λ‘λνμ΅λλ€.")
|
37 |
+
return memory
|
38 |
+
except json.JSONDecodeError:
|
39 |
+
logging.error(f"{MEMORY_FILE} νμΌ νμ± μ€λ₯. λ©λͺ¨λ¦¬λ₯Ό μ΄κΈ°νν©λλ€.")
|
40 |
+
return []
|
41 |
+
except Exception as e:
|
42 |
+
logging.error(f"λ©λͺ¨λ¦¬ λ‘λ μ€ μ€λ₯ λ°μ: {e}", exc_info=True)
|
43 |
+
return []
|
44 |
+
else:
|
45 |
+
logging.info("λ©λͺ¨λ¦¬ νμΌμ΄ μμ΄ μλ‘ μμν©λλ€.")
|
46 |
+
return []
|
47 |
+
|
48 |
+
def save_memory(memory):
|
49 |
+
"""νμ¬ μκ° κΈ°λ‘μ λ©λͺ¨λ¦¬ νμΌμ μ μ₯ν©λλ€."""
|
50 |
+
try:
|
51 |
+
with open(MEMORY_FILE, 'w', encoding='utf-8') as f:
|
52 |
+
json.dump(memory, f, ensure_ascii=False, indent=2)
|
53 |
+
logging.debug(f"λ©λͺ¨λ¦¬λ₯Ό {MEMORY_FILE}μ μ μ₯νμ΅λλ€.")
|
54 |
+
except Exception as e:
|
55 |
+
logging.error(f"λ©λͺ¨λ¦¬ μ μ₯ μ€ μ€λ₯ λ°μ: {e}", exc_info=True)
|
56 |
+
|
57 |
+
def generate_thought(tokenizer, model, prompt_history):
|
58 |
+
"""μ£Όμ΄μ§ ν둬ννΈ κΈ°λ‘μ λ°νμΌλ‘ λ€μ μκ°μ μμ±ν©λλ€."""
|
59 |
+
if not prompt_history:
|
60 |
+
chat = [{"role": "user", "content": INITIAL_PROMPT}]
|
61 |
+
else:
|
62 |
+
last_thought = prompt_history[-1]['content']
|
63 |
+
prompt = f"μ΄μ μκ°: \"{last_thought}\"\n\nμ΄ μκ°μ λ°νμΌλ‘ λ€μμΌλ‘ λ μ€λ₯΄λ μκ°μ΄λ μ§λ¬Έ, λλ νμ₯λ κ°λ
μ 무μμΈκ°μ? κ°κ²°νκ² λ΅ν΄μ£ΌμΈμ."
|
64 |
+
chat = [{"role": "user", "content": prompt}]
|
65 |
+
|
66 |
+
prompt_formatted = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
|
67 |
+
logging.info(f"--- λͺ¨λΈ μ
λ ₯ ν둬ννΈ ---\n{prompt_formatted}\n-----------------------")
|
68 |
+
|
69 |
+
inputs = tokenizer(prompt_formatted, return_tensors="pt").to(DEVICE)
|
70 |
+
|
71 |
+
# λͺ¨λΈ μΆλ‘ (CPUμμλ μκ°μ΄ 걸릴 μ μμ΅λλ€)
|
72 |
+
start_time = time.time()
|
73 |
+
logging.info("λͺ¨λΈ μΆλ‘ μμ...")
|
74 |
+
with torch.no_grad():
|
75 |
+
outputs = model.generate(
|
76 |
+
**inputs,
|
77 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
78 |
+
pad_token_id=tokenizer.eos_token_id
|
79 |
+
)
|
80 |
+
end_time = time.time()
|
81 |
+
logging.info(f"λͺ¨λΈ μΆλ‘ μλ£ ({end_time - start_time:.2f}μ΄ μμ)")
|
82 |
+
|
83 |
+
input_token_length = inputs.input_ids.shape[1]
|
84 |
+
generated_ids = outputs[0, input_token_length:]
|
85 |
+
new_thought_raw = tokenizer.decode(generated_ids, skip_special_tokens=True)
|
86 |
+
|
87 |
+
logging.info(f"λͺ¨λΈ μμ± κ²°κ³Ό (Raw): {new_thought_raw}")
|
88 |
+
return new_thought_raw.strip()
|
89 |
+
|
90 |
+
if __name__ == "__main__":
|
91 |
+
logging.info("AI μκ° νλ‘μΈμ€ μμ...")
|
92 |
+
logging.info(f"λͺ¨λΈ ID: {MODEL_ID}")
|
93 |
+
logging.info(f"μ€ν μ₯μΉ: {DEVICE}")
|
94 |
+
|
95 |
+
hf_token = os.getenv("HF_TOKEN")
|
96 |
+
if hf_token:
|
97 |
+
logging.info("Hugging Face ν ν°μ μ¬μ©ν©λλ€.")
|
98 |
+
else:
|
99 |
+
logging.info("Hugging Face ν ν°μ΄ μ€μ λμ§ μμμ΅λλ€ (νμ μ Secretsμ μΆκ°).")
|
100 |
+
|
101 |
+
# --- BitsAndBytes μμν μ€μ ---
|
102 |
+
# 4λΉνΈ μμνλ₯Ό μ¬μ©νλλ‘ μ€μ ν©λλ€.
|
103 |
+
bnb_config = BitsAndBytesConfig(
|
104 |
+
load_in_4bit=True,
|
105 |
+
# bnb_4bit_use_double_quant=True, # μ΄μ€ μμν (λ©λͺ¨λ¦¬ μΆκ° μ μ½, μ½κ°μ μ±λ₯ μ ν κ°λ₯)
|
106 |
+
bnb_4bit_quant_type="nf4", # NF4 (Normal Float 4) νμ
μ¬μ© (μΌλ°μ μΌλ‘ κΆμ₯λ¨)
|
107 |
+
bnb_4bit_compute_dtype=torch.bfloat16 # κ³μ° μ μ¬μ©ν λ°μ΄ν° νμ
(CPUμμλ bfloat16 μ§μ μ¬λΆ νμΈ νμ, μλλ©΄ float32)
|
108 |
+
)
|
109 |
+
# CPUμμ bfloat16 μ§μ μλλ©΄ μλ μ£Όμ ν΄μ νκ³ μ λΌμΈ μ£Όμμ²λ¦¬
|
110 |
+
# bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="fp4", bnb_4bit_compute_dtype=torch.float32)
|
111 |
+
|
112 |
+
# λͺ¨λΈ λ° ν ν¬λμ΄μ λ‘λ
|
113 |
+
try:
|
114 |
+
logging.info("ν ν¬λμ΄μ λ‘λ© μ€...")
|
115 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, token=hf_token)
|
116 |
+
|
117 |
+
logging.info("μμνλ λͺ¨λΈ λ‘λ© μ€... (bitsandbytes μ€μ μ μ©)")
|
118 |
+
model = AutoModelForCausalLM.from_pretrained(
|
119 |
+
MODEL_ID,
|
120 |
+
quantization_config=bnb_config, # β
β
β
μμν μ€μ μ μ© β
β
β
|
121 |
+
device_map=DEVICE, # λͺ
μμ μΌλ‘ CPU μ§μ (λλ "auto"μ§λ§ CPUμμλ λͺ
μκ° λμ μ μμ)
|
122 |
+
# torch_dtype=torch.bfloat16, # quantization_config μμ compute_dtype λ‘ μ€μ ν¨
|
123 |
+
token=hf_token
|
124 |
+
)
|
125 |
+
# device_map μ¬μ© μ .to(DEVICE)λ λΆνμ
|
126 |
+
# model = model.to(DEVICE) # device_map μ μ°μ§ μλλ€λ©΄ μ΄ λΌμΈ μ¬μ©
|
127 |
+
|
128 |
+
model.eval()
|
129 |
+
logging.info("λͺ¨λΈ λ° ν ν¬λμ΄μ λ‘λ μλ£.")
|
130 |
+
|
131 |
+
except Exception as e:
|
132 |
+
logging.error(f"λͺ¨λΈ λ‘λ© μ€ μΉλͺ
μ μ€λ₯ λ°μ: {e}", exc_info=True)
|
133 |
+
# μ€λ₯ λ‘κ·Έμ CPUκ° bfloat16μ μ§μνμ§ μλλ€λ λ©μμ§κ° μμΌλ©΄,
|
134 |
+
# bnb_configμ compute_dtypeμ torch.float32λ‘ λ³κ²½ν΄λ³΄μΈμ.
|
135 |
+
exit(1)
|
136 |
+
|
137 |
+
thought_history = load_memory()
|
138 |
+
|
139 |
+
try:
|
140 |
+
while True:
|
141 |
+
logging.info("=== μλ‘μ΄ μκ° μ¬μ΄ν΄ μμ ===")
|
142 |
+
new_thought = generate_thought(tokenizer, model, thought_history)
|
143 |
+
|
144 |
+
if new_thought:
|
145 |
+
logging.info(f"μμ±λ μλ‘μ΄ μκ°: {new_thought}")
|
146 |
+
thought_entry = {"role": "assistant", "content": new_thought, "timestamp": datetime.now().isoformat()}
|
147 |
+
thought_history.append(thought_entry)
|
148 |
+
save_memory(thought_history)
|
149 |
+
else:
|
150 |
+
logging.warning("λͺ¨λΈμ΄ λΉ μκ°μ μμ±νμ΅λλ€.")
|
151 |
+
|
152 |
+
logging.info(f"λ€μ μκ°κΉμ§ {THINKING_INTERVAL_SECONDS}μ΄ λκΈ°...")
|
153 |
+
time.sleep(THINKING_INTERVAL_SECONDS)
|
154 |
+
|
155 |
+
except KeyboardInterrupt:
|
156 |
+
logging.info("μ¬μ©μ μμ²μΌλ‘ AI νλ‘μΈμ€ μ€μ§.")
|
157 |
+
except Exception as e:
|
158 |
+
logging.error(f"λ©μΈ 루νμμ μ€λ₯ λ°μ: {e}", exc_info=True)
|
159 |
+
finally:
|
160 |
+
logging.info("AI μκ° νλ‘μΈμ€ μ’
λ£. μ΅μ’
λ©λͺ¨λ¦¬ μ μ₯ μλ.")
|
161 |
+
save_memory(thought_history)
|