Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -28,145 +28,154 @@ except ImportError:
|
|
| 28 |
SPACES_AVAILABLE = False
|
| 29 |
|
| 30 |
class CreedBrattonAI:
|
| 31 |
-
"""Real Creed AI using Mark's trained model"""
|
| 32 |
|
| 33 |
def __init__(self):
|
| 34 |
self.model = None
|
| 35 |
self.tokenizer = None
|
| 36 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 37 |
self.model_loaded = False
|
| 38 |
self.loading = False
|
| 39 |
|
| 40 |
-
print(f"πΈ Initializing Creed AI
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
self.
|
| 44 |
|
| 45 |
-
def
|
| 46 |
-
"""Load the model
|
| 47 |
if self.loading or self.model_loaded:
|
| 48 |
return
|
| 49 |
|
| 50 |
self.loading = True
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
# Load base model and tokenizer
|
| 57 |
-
model_name = "phxdev/creed-qwen-0.5b-lora"
|
| 58 |
-
|
| 59 |
-
print("π¦ Loading tokenizer...")
|
| 60 |
-
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 61 |
-
model_name,
|
| 62 |
-
trust_remote_code=True,
|
| 63 |
-
padding_side="left"
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
# Add Creed's custom tokens
|
| 67 |
-
custom_tokens = ["<thinking>", "<conspiracy>", "<tangent>"]
|
| 68 |
-
print(f"πΈ Adding Creed's custom tokens: {custom_tokens}")
|
| 69 |
-
|
| 70 |
-
# Add custom tokens to tokenizer
|
| 71 |
-
num_added_tokens = self.tokenizer.add_tokens(custom_tokens)
|
| 72 |
-
print(f"β
Added {num_added_tokens} custom tokens")
|
| 73 |
-
|
| 74 |
-
# Add padding token if not present
|
| 75 |
-
if self.tokenizer.pad_token is None:
|
| 76 |
-
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 77 |
-
|
| 78 |
-
print("π€ Loading model...")
|
| 79 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 80 |
-
|
| 81 |
-
torch_dtype=torch.
|
| 82 |
-
device_map=
|
| 83 |
-
trust_remote_code=True,
|
| 84 |
-
low_cpu_mem_usage=True
|
| 85 |
)
|
| 86 |
-
|
| 87 |
-
# Resize embeddings for custom tokens
|
| 88 |
-
if num_added_tokens > 0:
|
| 89 |
-
print(f"π§ Resizing model embeddings for {num_added_tokens} custom tokens")
|
| 90 |
-
self.model.resize_token_embeddings(len(self.tokenizer))
|
| 91 |
-
|
| 92 |
-
if self.device == "cpu":
|
| 93 |
-
self.model = self.model.to(self.device)
|
| 94 |
-
|
| 95 |
-
# Put model in eval mode
|
| 96 |
self.model.eval()
|
| 97 |
-
|
| 98 |
self.model_loaded = True
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
base_model = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 108 |
-
self.tokenizer = AutoTokenizer.from_pretrained(base_model)
|
| 109 |
-
self.model = AutoModelForCausalLM.from_pretrained(
|
| 110 |
-
base_model,
|
| 111 |
-
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
|
| 112 |
-
device_map="auto" if self.device == "cuda" else None
|
| 113 |
-
)
|
| 114 |
-
if self.device == "cpu":
|
| 115 |
-
self.model = self.model.to(self.device)
|
| 116 |
-
self.model.eval()
|
| 117 |
-
self.model_loaded = True
|
| 118 |
-
print("β
Fallback model loaded")
|
| 119 |
-
except Exception as fallback_error:
|
| 120 |
-
print(f"β Fallback also failed: {fallback_error}")
|
| 121 |
-
self.loading = False
|
| 122 |
-
|
| 123 |
-
# Load in background thread
|
| 124 |
-
threading.Thread(target=load_model, daemon=True).start()
|
| 125 |
-
|
| 126 |
-
def generate_response(self, message: str, history: List[List[str]]) -> Iterator[str]:
|
| 127 |
-
"""Generate response using the trained Creed model"""
|
| 128 |
|
| 129 |
if not self.model_loaded:
|
| 130 |
-
|
| 131 |
-
yield "π§ Creed's consciousness is still loading... give me a moment..."
|
| 132 |
-
return
|
| 133 |
-
else:
|
| 134 |
-
yield "β Something went wrong loading Creed's mind. Try refreshing the page."
|
| 135 |
-
return
|
| 136 |
|
| 137 |
try:
|
| 138 |
-
#
|
| 139 |
-
|
|
|
|
| 140 |
|
| 141 |
# Tokenize input
|
| 142 |
-
inputs = self.tokenizer.encode(conversation, return_tensors="pt").to(
|
| 143 |
|
| 144 |
# Generate response
|
| 145 |
with torch.no_grad():
|
| 146 |
-
|
| 147 |
-
outputs = self.model.generate(
|
| 148 |
inputs,
|
| 149 |
-
max_new_tokens=200,
|
| 150 |
do_sample=True,
|
| 151 |
-
temperature=0.9,
|
| 152 |
top_p=0.95,
|
| 153 |
top_k=40,
|
| 154 |
repetition_penalty=1.15,
|
| 155 |
pad_token_id=self.tokenizer.eos_token_id,
|
| 156 |
eos_token_id=self.tokenizer.eos_token_id,
|
| 157 |
use_cache=True,
|
| 158 |
-
# Allow custom tokens to be generated
|
| 159 |
bad_words_ids=None
|
| 160 |
)
|
| 161 |
|
| 162 |
# Decode response
|
| 163 |
full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 164 |
-
|
| 165 |
-
# Extract just the new response
|
| 166 |
response = full_response[len(self.tokenizer.decode(inputs[0], skip_special_tokens=True)):].strip()
|
| 167 |
|
| 168 |
-
#
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
# Stream the response word by word for effect
|
| 172 |
words = response.split()
|
|
@@ -174,7 +183,7 @@ class CreedBrattonAI:
|
|
| 174 |
|
| 175 |
for word in words:
|
| 176 |
current_response += word + " "
|
| 177 |
-
time.sleep(0.05)
|
| 178 |
yield current_response.strip()
|
| 179 |
|
| 180 |
except Exception as e:
|
|
|
|
| 28 |
SPACES_AVAILABLE = False
|
| 29 |
|
| 30 |
class CreedBrattonAI:
|
| 31 |
+
"""Real Creed AI using Mark's trained model - Spaces GPU compatible"""
|
| 32 |
|
| 33 |
def __init__(self):
|
| 34 |
self.model = None
|
| 35 |
self.tokenizer = None
|
|
|
|
| 36 |
self.model_loaded = False
|
| 37 |
self.loading = False
|
| 38 |
|
| 39 |
+
print(f"πΈ Initializing Creed AI (CPU-only for Spaces compatibility)")
|
| 40 |
|
| 41 |
+
# Load model on CPU only - GPU operations happen in @spaces.GPU functions
|
| 42 |
+
self.load_model_cpu()
|
| 43 |
|
| 44 |
+
def load_model_cpu(self):
|
| 45 |
+
"""Load the model on CPU only for Spaces compatibility"""
|
| 46 |
if self.loading or self.model_loaded:
|
| 47 |
return
|
| 48 |
|
| 49 |
self.loading = True
|
| 50 |
|
| 51 |
+
try:
|
| 52 |
+
print("π§ Loading Creed's consciousness (CPU mode for Spaces)...")
|
| 53 |
+
|
| 54 |
+
# Load model and tokenizer on CPU
|
| 55 |
+
model_name = "phxdev/creed-qwen-0.5b-lora"
|
| 56 |
+
|
| 57 |
+
print("π¦ Loading tokenizer...")
|
| 58 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 59 |
+
model_name,
|
| 60 |
+
trust_remote_code=True,
|
| 61 |
+
padding_side="left"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Add Creed's custom tokens
|
| 65 |
+
custom_tokens = ["<thinking>", "<conspiracy>", "<tangent>"]
|
| 66 |
+
print(f"πΈ Adding Creed's custom tokens: {custom_tokens}")
|
| 67 |
+
|
| 68 |
+
num_added_tokens = self.tokenizer.add_tokens(custom_tokens)
|
| 69 |
+
print(f"β
Added {num_added_tokens} custom tokens")
|
| 70 |
+
|
| 71 |
+
if self.tokenizer.pad_token is None:
|
| 72 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 73 |
+
|
| 74 |
+
print("π€ Loading model (CPU only)...")
|
| 75 |
+
# Load model on CPU only - no device_map, no CUDA
|
| 76 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 77 |
+
model_name,
|
| 78 |
+
torch_dtype=torch.float32, # Use float32 for CPU
|
| 79 |
+
device_map=None, # No device mapping
|
| 80 |
+
trust_remote_code=True,
|
| 81 |
+
low_cpu_mem_usage=True
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# Resize embeddings for custom tokens
|
| 85 |
+
if num_added_tokens > 0:
|
| 86 |
+
print(f"π§ Resizing model embeddings for {num_added_tokens} custom tokens")
|
| 87 |
+
self.model.resize_token_embeddings(len(self.tokenizer))
|
| 88 |
+
|
| 89 |
+
# Keep model on CPU
|
| 90 |
+
self.model = self.model.to("cpu")
|
| 91 |
+
self.model.eval()
|
| 92 |
+
|
| 93 |
+
self.model_loaded = True
|
| 94 |
+
self.loading = False
|
| 95 |
+
print("β
Creed's consciousness loaded on CPU!")
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
print(f"β Error loading Creed model: {e}")
|
| 99 |
+
print("π Falling back to base model...")
|
| 100 |
try:
|
| 101 |
+
base_model = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 102 |
+
self.tokenizer = AutoTokenizer.from_pretrained(base_model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
self.model = AutoModelForCausalLM.from_pretrained(
|
| 104 |
+
base_model,
|
| 105 |
+
torch_dtype=torch.float32,
|
| 106 |
+
device_map=None
|
|
|
|
|
|
|
| 107 |
)
|
| 108 |
+
self.model = self.model.to("cpu")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
self.model.eval()
|
|
|
|
| 110 |
self.model_loaded = True
|
| 111 |
+
print("β
Fallback model loaded on CPU")
|
| 112 |
+
except Exception as fallback_error:
|
| 113 |
+
print(f"β Fallback also failed: {fallback_error}")
|
| 114 |
+
self.loading = False
|
| 115 |
+
|
| 116 |
+
@spaces.GPU if SPACES_AVAILABLE else lambda func: func
|
| 117 |
+
def generate_response_gpu(self, conversation: str) -> str:
|
| 118 |
+
"""GPU-accelerated response generation (only called within @spaces.GPU)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
if not self.model_loaded:
|
| 121 |
+
return "β Model not loaded"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
try:
|
| 124 |
+
# Move model to GPU only within this function
|
| 125 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 126 |
+
model = self.model.to(device)
|
| 127 |
|
| 128 |
# Tokenize input
|
| 129 |
+
inputs = self.tokenizer.encode(conversation, return_tensors="pt").to(device)
|
| 130 |
|
| 131 |
# Generate response
|
| 132 |
with torch.no_grad():
|
| 133 |
+
outputs = model.generate(
|
|
|
|
| 134 |
inputs,
|
| 135 |
+
max_new_tokens=200,
|
| 136 |
do_sample=True,
|
| 137 |
+
temperature=0.9,
|
| 138 |
top_p=0.95,
|
| 139 |
top_k=40,
|
| 140 |
repetition_penalty=1.15,
|
| 141 |
pad_token_id=self.tokenizer.eos_token_id,
|
| 142 |
eos_token_id=self.tokenizer.eos_token_id,
|
| 143 |
use_cache=True,
|
|
|
|
| 144 |
bad_words_ids=None
|
| 145 |
)
|
| 146 |
|
| 147 |
# Decode response
|
| 148 |
full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
|
|
|
| 149 |
response = full_response[len(self.tokenizer.decode(inputs[0], skip_special_tokens=True)):].strip()
|
| 150 |
|
| 151 |
+
# Move model back to CPU to free GPU memory
|
| 152 |
+
self.model = self.model.to("cpu")
|
| 153 |
+
|
| 154 |
+
return self._clean_response(response)
|
| 155 |
+
|
| 156 |
+
except Exception as e:
|
| 157 |
+
# Ensure model is back on CPU
|
| 158 |
+
if hasattr(self, 'model') and self.model is not None:
|
| 159 |
+
self.model = self.model.to("cpu")
|
| 160 |
+
return f"πΈ *Creed scratches his head* Something weird happened... {str(e)[:100]}"
|
| 161 |
+
|
| 162 |
+
def generate_response(self, message: str, history: List[List[str]]) -> Iterator[str]:
|
| 163 |
+
"""Generate response using the trained Creed model"""
|
| 164 |
+
|
| 165 |
+
if not self.model_loaded:
|
| 166 |
+
if self.loading:
|
| 167 |
+
yield "π§ Creed's consciousness is still loading... give me a moment..."
|
| 168 |
+
return
|
| 169 |
+
else:
|
| 170 |
+
yield "β Something went wrong loading Creed's mind. Try refreshing the page."
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
# Format the conversation
|
| 175 |
+
conversation = self._format_conversation(message, history)
|
| 176 |
+
|
| 177 |
+
# Generate response using GPU function
|
| 178 |
+
response = self.generate_response_gpu(conversation)
|
| 179 |
|
| 180 |
# Stream the response word by word for effect
|
| 181 |
words = response.split()
|
|
|
|
| 183 |
|
| 184 |
for word in words:
|
| 185 |
current_response += word + " "
|
| 186 |
+
time.sleep(0.05)
|
| 187 |
yield current_response.strip()
|
| 188 |
|
| 189 |
except Exception as e:
|