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|
7 |
+
|
8 |
+
import gradio as gr
|
9 |
+
import torch
|
10 |
+
import torch.nn.functional as F
|
11 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
12 |
+
import random
|
13 |
+
import numpy as np
|
14 |
+
import re
|
15 |
+
import time
|
16 |
+
from typing import List, Tuple, Generator
|
17 |
+
import os
|
18 |
+
import gc
|
19 |
+
import spaces
|
20 |
+
|
21 |
+
# Global model variables for memory efficiency
|
22 |
+
tokenizer = None
|
23 |
+
model = None
|
24 |
+
current_generator = None
|
25 |
+
device = None
|
26 |
+
|
27 |
+
def get_noising_schedule(i, max_it, sharpness=5.0):
|
28 |
+
"""Exponential noise schedule for denoising"""
|
29 |
+
x = i / max_it
|
30 |
+
return (np.exp(-sharpness * x) - np.exp(-sharpness)) / (1 - np.exp(-sharpness))
|
31 |
+
|
32 |
+
class ARDiffusionGenerator:
|
33 |
+
"""Base AR-Diffusion generator with shared functionality"""
|
34 |
+
|
35 |
+
def __init__(self, tokenizer, model, device):
|
36 |
+
self.tokenizer = tokenizer
|
37 |
+
self.model = model
|
38 |
+
self.device = device
|
39 |
+
self.mask_token_id = self._find_mask_token()
|
40 |
+
|
41 |
+
def _find_mask_token(self) -> int:
|
42 |
+
"""Find MASK token ID"""
|
43 |
+
for candidate in ['MASK', '<mask>', '[MASK]', '<|mask|>']:
|
44 |
+
try:
|
45 |
+
tokens = self.tokenizer.encode(candidate, add_special_tokens=False)
|
46 |
+
if len(tokens) == 1:
|
47 |
+
return tokens[0]
|
48 |
+
except:
|
49 |
+
continue
|
50 |
+
return getattr(self.tokenizer, 'unk_token_id', 50257) or 50257
|
51 |
+
|
52 |
+
def create_prompt(self, instruction: str) -> str:
|
53 |
+
"""Create Alpaca-style prompt"""
|
54 |
+
return f"""### Instruction:
|
55 |
+
{instruction}
|
56 |
+
|
57 |
+
### Response:
|
58 |
+
"""
|
59 |
+
|
60 |
+
class QualityGenerator(ARDiffusionGenerator):
|
61 |
+
"""Quality-focused AR-Diffusion generator (from first script)"""
|
62 |
+
|
63 |
+
def filter_logits(self, logits: torch.Tensor, top_k: int = 0, top_p: float = 1.0,
|
64 |
+
temperature: float = 1.0) -> torch.Tensor:
|
65 |
+
"""Research-grade filtering with proper order"""
|
66 |
+
original_shape = logits.shape
|
67 |
+
if logits.dim() == 3:
|
68 |
+
logits = logits.squeeze(0)
|
69 |
+
elif logits.dim() == 1:
|
70 |
+
logits = logits.unsqueeze(0)
|
71 |
+
|
72 |
+
logits = logits.clone()
|
73 |
+
|
74 |
+
# Temperature scaling first
|
75 |
+
if temperature != 1.0:
|
76 |
+
logits = logits / temperature
|
77 |
+
|
78 |
+
# Top-k filtering
|
79 |
+
if top_k > 0 and top_k < logits.size(-1):
|
80 |
+
topk_vals, _ = torch.topk(logits, top_k, dim=-1)
|
81 |
+
thresholds = topk_vals[:, -1].unsqueeze(-1)
|
82 |
+
logits = torch.where(logits < thresholds,
|
83 |
+
torch.full_like(logits, float("-inf")), logits)
|
84 |
+
|
85 |
+
# Top-p filtering
|
86 |
+
if top_p > 0.0 and top_p < 1.0:
|
87 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
88 |
+
probs = torch.softmax(sorted_logits, dim=-1)
|
89 |
+
cum_probs = probs.cumsum(dim=-1)
|
90 |
+
|
91 |
+
mask = cum_probs > top_p
|
92 |
+
mask[:, 0] = False
|
93 |
+
|
94 |
+
scatter_mask = torch.zeros_like(logits, dtype=torch.bool).scatter(
|
95 |
+
dim=-1, index=sorted_indices, src=mask)
|
96 |
+
logits = torch.where(scatter_mask,
|
97 |
+
torch.full_like(logits, float("-inf")), logits)
|
98 |
+
|
99 |
+
# Restore original shape
|
100 |
+
if len(original_shape) == 1:
|
101 |
+
logits = logits.squeeze(0)
|
102 |
+
elif original_shape[0] == 1 and logits.dim() == 2:
|
103 |
+
logits = logits.unsqueeze(0)
|
104 |
+
|
105 |
+
return logits
|
106 |
+
|
107 |
+
def generate_start(self, prompt: str, length: int = 8) -> List[int]:
|
108 |
+
"""Generate natural start"""
|
109 |
+
tokens = self.tokenizer(prompt, return_tensors="pt").to(self.device)
|
110 |
+
input_ids = tokens['input_ids'][0]
|
111 |
+
|
112 |
+
generated = []
|
113 |
+
current = input_ids.clone()
|
114 |
+
|
115 |
+
with torch.no_grad():
|
116 |
+
for _ in range(length):
|
117 |
+
outputs = self.model(input_ids=current.unsqueeze(0))
|
118 |
+
logits = outputs.logits[0, -1]
|
119 |
+
|
120 |
+
filtered_logits = self.filter_logits(
|
121 |
+
logits, top_k=50, top_p=0.9, temperature=0.8
|
122 |
+
)
|
123 |
+
|
124 |
+
probs = F.softmax(filtered_logits, dim=-1)
|
125 |
+
next_token = torch.multinomial(probs, 1).item()
|
126 |
+
|
127 |
+
if next_token in [self.tokenizer.eos_token_id, 128001, 13]:
|
128 |
+
break
|
129 |
+
|
130 |
+
generated.append(next_token)
|
131 |
+
current = torch.cat([current, torch.tensor([next_token], device=self.device)])
|
132 |
+
|
133 |
+
return generated
|
134 |
+
|
135 |
+
def create_sequence(self, prompt: str) -> Tuple[str, torch.Tensor]:
|
136 |
+
"""Create corrupted sequence for quality mode"""
|
137 |
+
prompt_tokens = self.tokenizer(prompt, return_tensors="pt")['input_ids'][0]
|
138 |
+
natural_start = self.generate_start(prompt, length=random.randint(8, 12))
|
139 |
+
|
140 |
+
# Longer sequences for better quality
|
141 |
+
prompt_length = len(prompt_tokens)
|
142 |
+
if prompt_length > 25:
|
143 |
+
num_masks = random.randint(35, 50)
|
144 |
+
elif prompt_length > 15:
|
145 |
+
num_masks = random.randint(25, 40)
|
146 |
+
else:
|
147 |
+
num_masks = random.randint(20, 35)
|
148 |
+
|
149 |
+
sequence = (
|
150 |
+
prompt_tokens.tolist() +
|
151 |
+
natural_start +
|
152 |
+
[self.mask_token_id] * num_masks +
|
153 |
+
[13]
|
154 |
+
)
|
155 |
+
|
156 |
+
tensor = torch.tensor(sequence)
|
157 |
+
text = self.tokenizer.decode(tensor, skip_special_tokens=False)
|
158 |
+
return text, tensor
|
159 |
+
|
160 |
+
def generate(self, prompt: str, progress_callback=None) -> Tuple[str, dict]:
|
161 |
+
"""Quality generation with progress updates and speed tracking"""
|
162 |
+
steps = 40
|
163 |
+
temperature = 0.7
|
164 |
+
start_time = time.time()
|
165 |
+
|
166 |
+
if progress_callback:
|
167 |
+
progress_callback(0.1, "Creating sequence...")
|
168 |
+
|
169 |
+
full_prompt = self.create_prompt(prompt)
|
170 |
+
corrupted_text, corrupted_ids = self.create_sequence(full_prompt)
|
171 |
+
|
172 |
+
if progress_callback:
|
173 |
+
progress_callback(0.2, "Starting quality denoising...")
|
174 |
+
|
175 |
+
result, stats = self._denoise_quality(corrupted_ids, steps, temperature, progress_callback)
|
176 |
+
|
177 |
+
# Calculate overall stats
|
178 |
+
total_time = time.time() - start_time
|
179 |
+
response = self._clean_response(result)
|
180 |
+
word_count = len(response.split())
|
181 |
+
|
182 |
+
stats.update({
|
183 |
+
'total_time': total_time,
|
184 |
+
'word_count': word_count,
|
185 |
+
'words_per_second': word_count / total_time if total_time > 0 else 0
|
186 |
+
})
|
187 |
+
|
188 |
+
return response, stats
|
189 |
+
|
190 |
+
def _denoise_quality(self, corrupted_ids: torch.Tensor, steps: int, temperature: float, progress_callback=None) -> Tuple[str, dict]:
|
191 |
+
"""Quality denoising with progress updates and speed tracking"""
|
192 |
+
current_ids = corrupted_ids.clone()
|
193 |
+
total_replacements = 0
|
194 |
+
start_time = time.time()
|
195 |
+
|
196 |
+
for step in range(steps):
|
197 |
+
step_start = time.time()
|
198 |
+
|
199 |
+
if progress_callback:
|
200 |
+
progress = 0.2 + (step / steps) * 0.7
|
201 |
+
elapsed = time.time() - start_time
|
202 |
+
tokens_per_sec = total_replacements / elapsed if elapsed > 0 else 0
|
203 |
+
progress_callback(progress, f"Quality step {step+1}/{steps} | {tokens_per_sec:.1f} tok/s")
|
204 |
+
|
205 |
+
mask_positions = (current_ids == self.mask_token_id).nonzero(as_tuple=True)[0]
|
206 |
+
|
207 |
+
if len(mask_positions) == 0:
|
208 |
+
break
|
209 |
+
|
210 |
+
with torch.no_grad():
|
211 |
+
outputs = self.model(input_ids=current_ids.unsqueeze(0).to(self.device))
|
212 |
+
logits = outputs.logits[0]
|
213 |
+
|
214 |
+
current_temp = max(0.4, temperature * (1 - step / steps))
|
215 |
+
|
216 |
+
# Conservative replacement for quality
|
217 |
+
if step < steps // 4:
|
218 |
+
max_replacements = min(1, len(mask_positions))
|
219 |
+
elif step < steps // 2:
|
220 |
+
max_replacements = min(2, len(mask_positions))
|
221 |
+
else:
|
222 |
+
max_replacements = min(3, len(mask_positions))
|
223 |
+
|
224 |
+
sorted_positions = sorted(mask_positions.tolist())
|
225 |
+
step_replacements = 0
|
226 |
+
|
227 |
+
for pos in sorted_positions[:max_replacements]:
|
228 |
+
if pos < len(logits):
|
229 |
+
token_logits = logits[pos].clone()
|
230 |
+
|
231 |
+
# Anti-repetition
|
232 |
+
context_start = max(0, pos - 5)
|
233 |
+
recent_tokens = set(current_ids[context_start:pos].tolist())
|
234 |
+
for recent_token in recent_tokens:
|
235 |
+
if recent_token < len(token_logits):
|
236 |
+
token_logits[recent_token] -= 8.0
|
237 |
+
|
238 |
+
# Quality filtering
|
239 |
+
filtered_logits = self.filter_logits(
|
240 |
+
token_logits,
|
241 |
+
top_k=30,
|
242 |
+
top_p=0.75,
|
243 |
+
temperature=current_temp
|
244 |
+
)
|
245 |
+
|
246 |
+
probs = F.softmax(filtered_logits, dim=-1)
|
247 |
+
probs = torch.clamp(probs, min=1e-8, max=1.0)
|
248 |
+
new_token = torch.multinomial(probs, 1).item()
|
249 |
+
|
250 |
+
# Filter unwanted tokens
|
251 |
+
unwanted = [self.mask_token_id, 128001, 128000]
|
252 |
+
if new_token in unwanted:
|
253 |
+
top_k_vals, top_k_indices = torch.topk(filtered_logits, 10)
|
254 |
+
for alternative in top_k_indices:
|
255 |
+
if alternative.item() not in unwanted:
|
256 |
+
new_token = alternative.item()
|
257 |
+
break
|
258 |
+
|
259 |
+
current_ids[pos] = new_token
|
260 |
+
step_replacements += 1
|
261 |
+
total_replacements += 1
|
262 |
+
|
263 |
+
if progress_callback:
|
264 |
+
elapsed = time.time() - start_time
|
265 |
+
final_speed = total_replacements / elapsed if elapsed > 0 else 0
|
266 |
+
progress_callback(0.95, f"Finalizing... | Final speed: {final_speed:.1f} tok/s")
|
267 |
+
|
268 |
+
# Calculate final statistics
|
269 |
+
total_time = time.time() - start_time
|
270 |
+
stats = {
|
271 |
+
'mode': 'Quality',
|
272 |
+
'steps': steps,
|
273 |
+
'tokens_replaced': total_replacements,
|
274 |
+
'generation_time': total_time,
|
275 |
+
'tokens_per_second': total_replacements / total_time if total_time > 0 else 0
|
276 |
+
}
|
277 |
+
|
278 |
+
result = self.tokenizer.decode(current_ids, skip_special_tokens=True)
|
279 |
+
return result, stats
|
280 |
+
|
281 |
+
def _clean_response(self, text: str) -> str:
|
282 |
+
"""Clean response for quality output"""
|
283 |
+
if "### Response:" in text:
|
284 |
+
response = text.split("### Response:")[-1].strip()
|
285 |
+
else:
|
286 |
+
response = text.strip()
|
287 |
+
|
288 |
+
if not response:
|
289 |
+
return text
|
290 |
+
|
291 |
+
# Quality cleaning
|
292 |
+
response = re.sub(r"'{2,}", "", response)
|
293 |
+
response = re.sub(r'"{2,}', "", response)
|
294 |
+
response = re.sub(r"\.{2,}", ".", response)
|
295 |
+
response = re.sub(r",{2,}", ",", response)
|
296 |
+
response = re.sub(r"\s+", " ", response)
|
297 |
+
|
298 |
+
# Remove artifacts
|
299 |
+
response = re.sub(r"\$+", "", response)
|
300 |
+
response = re.sub(r"#+", "", response)
|
301 |
+
response = re.sub(r"@+", "", response)
|
302 |
+
|
303 |
+
response = response.strip()
|
304 |
+
if response and not response.endswith(('.', '!', '?')):
|
305 |
+
response += "."
|
306 |
+
|
307 |
+
return response
|
308 |
+
|
309 |
+
class SpeedGenerator(ARDiffusionGenerator):
|
310 |
+
"""Speed-focused AR-Diffusion generator (from second script)"""
|
311 |
+
|
312 |
+
def filter_logits(self, logits: torch.Tensor, top_k: int = 15, top_p: float = 0.8,
|
313 |
+
temperature: float = 1.0) -> torch.Tensor:
|
314 |
+
"""Fast logits filtering"""
|
315 |
+
logits = logits.clone()
|
316 |
+
|
317 |
+
if temperature != 1.0:
|
318 |
+
logits = logits / temperature
|
319 |
+
|
320 |
+
# Top-k filtering
|
321 |
+
if top_k > 0 and top_k < logits.size(-1):
|
322 |
+
topk_vals, _ = torch.topk(logits, top_k, dim=-1)
|
323 |
+
threshold = topk_vals[-1]
|
324 |
+
logits = torch.where(logits < threshold, torch.full_like(logits, float("-inf")), logits)
|
325 |
+
|
326 |
+
# Top-p filtering
|
327 |
+
if top_p > 0.0 and top_p < 1.0:
|
328 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
329 |
+
probs = torch.softmax(sorted_logits, dim=-1)
|
330 |
+
cum_probs = probs.cumsum(dim=-1)
|
331 |
+
|
332 |
+
mask = cum_probs > top_p
|
333 |
+
mask[0] = False
|
334 |
+
|
335 |
+
scatter_mask = torch.zeros_like(logits, dtype=torch.bool)
|
336 |
+
scatter_mask.scatter_(0, sorted_indices, mask)
|
337 |
+
logits = torch.where(scatter_mask, torch.full_like(logits, float("-inf")), logits)
|
338 |
+
|
339 |
+
return logits
|
340 |
+
|
341 |
+
def generate_start(self, prompt: str, length: int = 6) -> List[int]:
|
342 |
+
"""Generate natural start for speed mode"""
|
343 |
+
tokens = self.tokenizer(prompt, return_tensors="pt").to(self.device)
|
344 |
+
input_ids = tokens['input_ids'][0]
|
345 |
+
|
346 |
+
generated = []
|
347 |
+
current = input_ids.clone()
|
348 |
+
|
349 |
+
with torch.no_grad():
|
350 |
+
for _ in range(length):
|
351 |
+
outputs = self.model(input_ids=current.unsqueeze(0))
|
352 |
+
logits = outputs.logits[0, -1]
|
353 |
+
|
354 |
+
filtered_logits = self.filter_logits(logits, top_k=20, top_p=0.9, temperature=0.8)
|
355 |
+
probs = F.softmax(filtered_logits, dim=-1)
|
356 |
+
next_token = torch.multinomial(probs, 1).item()
|
357 |
+
|
358 |
+
if next_token in [self.tokenizer.eos_token_id, 128001, 13]:
|
359 |
+
break
|
360 |
+
|
361 |
+
generated.append(next_token)
|
362 |
+
current = torch.cat([current, torch.tensor([next_token], device=self.device)])
|
363 |
+
|
364 |
+
return generated
|
365 |
+
|
366 |
+
def create_sequence(self, prompt: str) -> Tuple[str, torch.Tensor]:
|
367 |
+
"""Create sequence optimized for speed"""
|
368 |
+
prompt_tokens = self.tokenizer(prompt, return_tensors="pt")['input_ids'][0]
|
369 |
+
natural_start = self.generate_start(prompt, length=6)
|
370 |
+
|
371 |
+
# Shorter sequences for speed
|
372 |
+
prompt_words = len(prompt.split())
|
373 |
+
if prompt_words > 8:
|
374 |
+
num_masks = random.randint(15, 25)
|
375 |
+
else:
|
376 |
+
num_masks = random.randint(12, 20)
|
377 |
+
|
378 |
+
sequence = (
|
379 |
+
prompt_tokens.tolist() +
|
380 |
+
natural_start +
|
381 |
+
[self.mask_token_id] * num_masks +
|
382 |
+
[13]
|
383 |
+
)
|
384 |
+
|
385 |
+
tensor = torch.tensor(sequence)
|
386 |
+
text = self.tokenizer.decode(tensor, skip_special_tokens=False)
|
387 |
+
return text, tensor
|
388 |
+
|
389 |
+
def generate(self, prompt: str, progress_callback=None) -> Tuple[str, dict]:
|
390 |
+
"""Speed generation with progress updates and speed tracking"""
|
391 |
+
steps = 10
|
392 |
+
temperature = 0.8
|
393 |
+
start_time = time.time()
|
394 |
+
|
395 |
+
if progress_callback:
|
396 |
+
progress_callback(0.1, "Creating sequence...")
|
397 |
+
|
398 |
+
full_prompt = self.create_prompt(prompt)
|
399 |
+
corrupted_text, corrupted_ids = self.create_sequence(full_prompt)
|
400 |
+
|
401 |
+
if progress_callback:
|
402 |
+
progress_callback(0.2, "Starting speed denoising...")
|
403 |
+
|
404 |
+
result, stats = self._denoise_speed(corrupted_ids, steps, temperature, progress_callback)
|
405 |
+
|
406 |
+
# Calculate overall stats
|
407 |
+
total_time = time.time() - start_time
|
408 |
+
response = self._clean_response(result)
|
409 |
+
word_count = len(response.split())
|
410 |
+
|
411 |
+
stats.update({
|
412 |
+
'total_time': total_time,
|
413 |
+
'word_count': word_count,
|
414 |
+
'words_per_second': word_count / total_time if total_time > 0 else 0
|
415 |
+
})
|
416 |
+
|
417 |
+
return response, stats
|
418 |
+
|
419 |
+
def _denoise_speed(self, corrupted_ids: torch.Tensor, steps: int, temperature: float, progress_callback=None) -> Tuple[str, dict]:
|
420 |
+
"""Ultra-fast denoising with progress updates and speed tracking"""
|
421 |
+
current_ids = corrupted_ids.clone()
|
422 |
+
total_replacements = 0
|
423 |
+
start_time = time.time()
|
424 |
+
|
425 |
+
# Use mixed precision for speed on GPU
|
426 |
+
with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=self.device.type == 'cuda'):
|
427 |
+
for step in range(steps):
|
428 |
+
step_start = time.time()
|
429 |
+
|
430 |
+
if progress_callback:
|
431 |
+
progress = 0.2 + (step / steps) * 0.7
|
432 |
+
elapsed = time.time() - start_time
|
433 |
+
tokens_per_sec = total_replacements / elapsed if elapsed > 0 else 0
|
434 |
+
progress_callback(progress, f"Speed step {step+1}/{steps} | {tokens_per_sec:.1f} tok/s")
|
435 |
+
|
436 |
+
mask_pos = (current_ids == self.mask_token_id).nonzero(as_tuple=True)[0]
|
437 |
+
|
438 |
+
if len(mask_pos) == 0:
|
439 |
+
break
|
440 |
+
|
441 |
+
with torch.no_grad():
|
442 |
+
outputs = self.model(input_ids=current_ids.unsqueeze(0).to(self.device))
|
443 |
+
logits = outputs.logits[0]
|
444 |
+
|
445 |
+
current_temp = temperature * (0.9 + 0.2 * (step / steps))
|
446 |
+
|
447 |
+
# Aggressive replacement for speed
|
448 |
+
max_replace = min(8, len(mask_pos))
|
449 |
+
positions = sorted(mask_pos.tolist())[:max_replace]
|
450 |
+
|
451 |
+
step_replacements = 0
|
452 |
+
for pos in positions:
|
453 |
+
if pos < len(logits):
|
454 |
+
token_logits = logits[pos].clone()
|
455 |
+
|
456 |
+
# Light anti-repetition
|
457 |
+
recent_start = max(0, pos - 3)
|
458 |
+
recent_tokens = set(current_ids[recent_start:pos].tolist())
|
459 |
+
for token in recent_tokens:
|
460 |
+
if token < len(token_logits):
|
461 |
+
token_logits[token] -= 3.0
|
462 |
+
|
463 |
+
# Fast filtering
|
464 |
+
filtered_logits = self.filter_logits(
|
465 |
+
token_logits, top_k=12, top_p=0.85, temperature=current_temp
|
466 |
+
)
|
467 |
+
|
468 |
+
probs = F.softmax(filtered_logits, dim=-1)
|
469 |
+
probs = torch.clamp(probs, min=1e-8, max=1.0)
|
470 |
+
new_token = torch.multinomial(probs, 1).item()
|
471 |
+
|
472 |
+
# Quick filtering
|
473 |
+
if new_token in [self.mask_token_id, 128001, 128000]:
|
474 |
+
top_vals, top_indices = torch.topk(filtered_logits, 3)
|
475 |
+
new_token = top_indices[1].item()
|
476 |
+
|
477 |
+
current_ids[pos] = new_token
|
478 |
+
step_replacements += 1
|
479 |
+
total_replacements += 1
|
480 |
+
|
481 |
+
if progress_callback:
|
482 |
+
elapsed = time.time() - start_time
|
483 |
+
final_speed = total_replacements / elapsed if elapsed > 0 else 0
|
484 |
+
progress_callback(0.95, f"Finalizing... | Final speed: {final_speed:.1f} tok/s")
|
485 |
+
|
486 |
+
# Calculate final statistics
|
487 |
+
total_time = time.time() - start_time
|
488 |
+
stats = {
|
489 |
+
'mode': 'Speed',
|
490 |
+
'steps': steps,
|
491 |
+
'tokens_replaced': total_replacements,
|
492 |
+
'generation_time': total_time,
|
493 |
+
'tokens_per_second': total_replacements / total_time if total_time > 0 else 0
|
494 |
+
}
|
495 |
+
|
496 |
+
result = self.tokenizer.decode(current_ids, skip_special_tokens=True)
|
497 |
+
return result, stats
|
498 |
+
|
499 |
+
def _clean_response(self, text: str) -> str:
|
500 |
+
"""Clean response for speed output"""
|
501 |
+
if "### Response:" in text:
|
502 |
+
response = text.split("### Response:")[-1].strip()
|
503 |
+
else:
|
504 |
+
response = text.strip()
|
505 |
+
|
506 |
+
if not response:
|
507 |
+
return text
|
508 |
+
|
509 |
+
# Minimal cleaning for speed
|
510 |
+
response = re.sub(r"'{3,}", "", response)
|
511 |
+
response = re.sub(r'"{3,}', "", response)
|
512 |
+
response = re.sub(r"\.{3,}", ".", response)
|
513 |
+
response = re.sub(r",{3,}", ",", response)
|
514 |
+
response = re.sub(r"\s+", " ", response)
|
515 |
+
|
516 |
+
response = response.strip()
|
517 |
+
if response and not response.endswith(('.', '!', '?')):
|
518 |
+
response += "."
|
519 |
+
|
520 |
+
return response
|
521 |
+
|
522 |
+
@spaces.GPU
|
523 |
+
def load_model():
|
524 |
+
"""Load model with Zero GPU optimization using @spaces.GPU"""
|
525 |
+
global tokenizer, model, device
|
526 |
+
|
527 |
+
if tokenizer is not None and model is not None:
|
528 |
+
return tokenizer, model, device
|
529 |
+
|
530 |
+
model_path = "rootxhacker/llama-3B-diffusion-exp-fixed"
|
531 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
532 |
+
|
533 |
+
print(f"Loading model on {device}...")
|
534 |
+
|
535 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
536 |
+
if tokenizer.pad_token is None:
|
537 |
+
tokenizer.pad_token = tokenizer.eos_token
|
538 |
+
|
539 |
+
model = AutoModelForCausalLM.from_pretrained(
|
540 |
+
model_path,
|
541 |
+
torch_dtype=torch.float16 if device.type == "cuda" else torch.float32,
|
542 |
+
device_map="auto" if device.type == "cuda" else None,
|
543 |
+
trust_remote_code=True,
|
544 |
+
low_cpu_mem_usage=True
|
545 |
+
)
|
546 |
+
|
547 |
+
return tokenizer, model, device
|
548 |
+
|
549 |
+
def cleanup_memory():
|
550 |
+
"""Clean up GPU memory"""
|
551 |
+
if torch.cuda.is_available():
|
552 |
+
torch.cuda.empty_cache()
|
553 |
+
gc.collect()
|
554 |
+
|
555 |
+
@spaces.GPU
|
556 |
+
def chat_function(message, history, mode, progress=gr.Progress()):
|
557 |
+
"""Main chat function with @spaces.GPU decorator, progress tracking, and speed display"""
|
558 |
+
if not message.strip():
|
559 |
+
return history, "", ""
|
560 |
+
|
561 |
+
try:
|
562 |
+
# Load model (this will run on GPU when GPU is allocated)
|
563 |
+
progress(0.05, description="Loading model on GPU...")
|
564 |
+
tok, mod, dev = load_model()
|
565 |
+
|
566 |
+
# Create appropriate generator
|
567 |
+
if mode == "Quality (Slower, Better)":
|
568 |
+
generator = QualityGenerator(tok, mod, dev)
|
569 |
+
progress(0.1, description="Initializing quality mode...")
|
570 |
+
else:
|
571 |
+
generator = SpeedGenerator(tok, mod, dev)
|
572 |
+
progress(0.1, description="Initializing speed mode...")
|
573 |
+
|
574 |
+
# Generate response with progress callback
|
575 |
+
def progress_callback(pct, desc):
|
576 |
+
progress(pct, description=desc)
|
577 |
+
|
578 |
+
response, stats = generator.generate(message, progress_callback)
|
579 |
+
|
580 |
+
progress(1.0, description="Complete!")
|
581 |
+
|
582 |
+
# Create performance info
|
583 |
+
perf_info = f"""**⚡ Performance Stats:**
|
584 |
+
- **Mode:** {stats['mode']}
|
585 |
+
- **Generation Time:** {stats['generation_time']:.2f}s
|
586 |
+
- **Tokens Replaced:** {stats['tokens_replaced']}
|
587 |
+
- **Speed:** {stats['tokens_per_second']:.1f} tokens/sec
|
588 |
+
- **Words Generated:** {stats['word_count']} words
|
589 |
+
- **Words/Second:** {stats['words_per_second']:.1f}
|
590 |
+
- **Steps:** {stats['steps']}"""
|
591 |
+
|
592 |
+
# Update history
|
593 |
+
history.append([message, response])
|
594 |
+
|
595 |
+
# Cleanup memory for Zero GPU efficiency
|
596 |
+
cleanup_memory()
|
597 |
+
|
598 |
+
return history, "", perf_info
|
599 |
+
|
600 |
+
except Exception as e:
|
601 |
+
error_msg = f"Error: {str(e)}"
|
602 |
+
history.append([message, error_msg])
|
603 |
+
cleanup_memory()
|
604 |
+
return history, "", f"**❌ Error occurred during generation**"
|
605 |
+
|
606 |
+
def clear_chat():
|
607 |
+
"""Clear chat history and cleanup memory"""
|
608 |
+
cleanup_memory()
|
609 |
+
return [], ""
|
610 |
+
|
611 |
+
# Create Gradio interface
|
612 |
+
def create_interface():
|
613 |
+
with gr.Blocks(
|
614 |
+
title="AR-Diffusion Chat - Experimental Model",
|
615 |
+
theme=gr.themes.Soft(),
|
616 |
+
css="""
|
617 |
+
.warning-box {
|
618 |
+
background-color: #fff3cd;
|
619 |
+
border: 1px solid #ffeaa7;
|
620 |
+
border-radius: 5px;
|
621 |
+
padding: 10px;
|
622 |
+
margin: 10px 0;
|
623 |
+
}
|
624 |
+
"""
|
625 |
+
) as interface:
|
626 |
+
|
627 |
+
gr.HTML("""
|
628 |
+
<div style="text-align: center; margin-bottom: 20px;">
|
629 |
+
<h1>🧪 AR-Diffusion Chat Interface</h1>
|
630 |
+
<p><strong>⚠️ EXPERIMENTAL MODEL ⚠️</strong></p>
|
631 |
+
<p>This is an experimental AR-Diffusion model. Results may vary and the model is still under development.</p>
|
632 |
+
<p><em>🔥 Powered by Zero GPU with @spaces.GPU</em></p>
|
633 |
+
</div>
|
634 |
+
""")
|
635 |
+
|
636 |
+
with gr.Row():
|
637 |
+
with gr.Column(scale=3):
|
638 |
+
chatbot = gr.Chatbot(
|
639 |
+
[],
|
640 |
+
elem_id="chatbot",
|
641 |
+
bubble_full_width=False,
|
642 |
+
height=500,
|
643 |
+
show_label=False
|
644 |
+
)
|
645 |
+
|
646 |
+
with gr.Row():
|
647 |
+
msg = gr.Textbox(
|
648 |
+
placeholder="Type your message here...",
|
649 |
+
show_label=False,
|
650 |
+
scale=9
|
651 |
+
)
|
652 |
+
send_btn = gr.Button("Send", scale=1, variant="primary")
|
653 |
+
|
654 |
+
with gr.Row():
|
655 |
+
clear_btn = gr.Button("Clear Chat", variant="secondary")
|
656 |
+
|
657 |
+
with gr.Column(scale=1):
|
658 |
+
gr.HTML("""
|
659 |
+
<div class="warning-box">
|
660 |
+
<h3>⚙️ Mode Selection</h3>
|
661 |
+
<p><strong>Quality Mode:</strong> Slower but more coherent responses (~40 steps)</p>
|
662 |
+
<p><strong>Speed Mode:</strong> Faster responses with decent quality (~10 steps)</p>
|
663 |
+
<p><em>🔥 GPU acceleration via @spaces.GPU</em></p>
|
664 |
+
</div>
|
665 |
+
""")
|
666 |
+
|
667 |
+
mode = gr.Radio(
|
668 |
+
choices=["Quality (Slower, Better)", "Speed (Faster)"],
|
669 |
+
value="Quality (Slower, Better)",
|
670 |
+
label="Generation Mode"
|
671 |
+
)
|
672 |
+
|
673 |
+
# Performance display
|
674 |
+
perf_display = gr.Markdown(
|
675 |
+
"**⚡ Performance Stats:** *Generate a message to see stats*",
|
676 |
+
elem_id="performance"
|
677 |
+
)
|
678 |
+
|
679 |
+
gr.HTML("""
|
680 |
+
<div class="warning-box">
|
681 |
+
<h3>ℹ️ About AR-Diffusion</h3>
|
682 |
+
<p>This experimental model uses autoregressive diffusion for text generation, creating responses by iteratively denoising masked tokens.</p>
|
683 |
+
<br>
|
684 |
+
<p><strong>Note:</strong> This model is experimental and may produce unexpected results.</p>
|
685 |
+
</div>
|
686 |
+
""")
|
687 |
+
|
688 |
+
# Event handlers
|
689 |
+
def submit_message(message, history, mode):
|
690 |
+
return chat_function(message, history, mode)
|
691 |
+
|
692 |
+
send_btn.click(
|
693 |
+
submit_message,
|
694 |
+
inputs=[msg, chatbot, mode],
|
695 |
+
outputs=[chatbot, msg, perf_display]
|
696 |
+
)
|
697 |
+
|
698 |
+
msg.submit(
|
699 |
+
submit_message,
|
700 |
+
inputs=[msg, chatbot, mode],
|
701 |
+
outputs=[chatbot, msg, perf_display]
|
702 |
+
)
|
703 |
+
|
704 |
+
clear_btn.click(
|
705 |
+
clear_chat,
|
706 |
+
outputs=[chatbot, perf_display]
|
707 |
+
)
|
708 |
+
|
709 |
+
return interface
|
710 |
+
|
711 |
+
# Launch interface
|
712 |
+
if __name__ == "__main__":
|
713 |
+
demo = create_interface()
|
714 |
+
demo.queue(max_size=20) # Important for Zero GPU
|
715 |
+
demo.launch(
|
716 |
+
share=False,
|
717 |
+
server_name="0.0.0.0",
|
718 |
+
server_port=7860,
|
719 |
+
show_error=True
|
720 |
+
)
|