File size: 14,448 Bytes
3d635c7
 
24088e0
 
 
3d635c7
bc44dae
24088e0
bc44dae
24088e0
 
 
 
 
 
 
bc44dae
3d635c7
24088e0
bc44dae
24088e0
3d635c7
24088e0
 
 
 
 
 
 
 
 
 
 
 
3d635c7
 
 
24088e0
 
3d635c7
24088e0
 
 
 
 
3d635c7
 
 
 
24088e0
 
3d635c7
 
 
 
24088e0
 
 
 
 
 
 
 
 
 
 
 
 
 
3d635c7
 
 
 
24088e0
 
3d635c7
24088e0
 
 
 
 
3d635c7
 
 
 
24088e0
 
3d635c7
bc44dae
 
3d635c7
 
24088e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc44dae
 
 
24088e0
 
3e4c841
24088e0
 
 
 
 
 
 
 
 
 
 
 
3e4c841
24088e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d635c7
 
 
 
 
 
 
 
24088e0
3d635c7
 
24088e0
 
 
 
 
 
 
 
 
 
 
 
3d635c7
 
 
24088e0
 
 
 
 
3d635c7
24088e0
 
3d635c7
 
 
 
 
24088e0
 
3d635c7
 
24088e0
 
 
 
3d635c7
 
24088e0
3d635c7
24088e0
 
 
3d635c7
 
24088e0
 
 
 
 
3d635c7
24088e0
3d635c7
24088e0
3d635c7
24088e0
 
 
 
 
 
 
3d635c7
 
 
 
24088e0
 
 
 
3d635c7
24088e0
3d635c7
24088e0
 
 
 
 
3d635c7
24088e0
3d635c7
24088e0
3d635c7
 
24088e0
 
3d635c7
 
24088e0
 
 
3d635c7
24088e0
 
 
3d635c7
 
 
 
 
bc44dae
24088e0
3d635c7
24088e0
3d635c7
 
 
 
 
24088e0
 
bc44dae
24088e0
 
bc44dae
24088e0
 
bc44dae
24088e0
 
 
 
 
3e4c841
24088e0
 
bc44dae
24088e0
3d635c7
3e4c841
24088e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d635c7
 
24088e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc44dae
3d635c7
 
24088e0
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import os
import uvicorn
import asyncio
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import torch
from typing import Optional, Dict
import time
import logging

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Inisialisasi FastAPI
app = FastAPI(title="LyonPoy AI Chat - Optimized")

# Optimized model configuration - prioritize smaller, faster models
MODELS = {
    "distil-gpt-2": {
        "name": "DistilGPT-2",
        "model_path": "Lyon28/Distil_GPT-2",
        "task": "text-generation",
        "priority": 1  # Highest priority - smallest model
    },
    "gpt-2-tinny": {
        "name": "GPT-2 Tinny",
        "model_path": "Lyon28/GPT-2-Tinny", 
        "task": "text-generation",
        "priority": 2
    },
    "tinny-llama": {
        "name": "Tinny Llama",
        "model_path": "Lyon28/Tinny-Llama",
        "task": "text-generation",
        "priority": 3
    },
    "gpt-2": {
        "name": "GPT-2",
        "model_path": "Lyon28/GPT-2",
        "task": "text-generation",
        "priority": 4
    },
    "bert-tinny": {
        "name": "BERT Tinny",
        "model_path": "Lyon28/Bert-Tinny",
        "task": "text-classification",
        "priority": 5
    },
    "albert-base-v2": {
        "name": "ALBERT Base V2",
        "model_path": "Lyon28/Albert-Base-V2",
        "task": "text-classification",
        "priority": 6
    },
    "distilbert-base-uncased": {
        "name": "DistilBERT",
        "model_path": "Lyon28/Distilbert-Base-Uncased",
        "task": "text-classification",
        "priority": 7
    },
    "electra-small": {
        "name": "ELECTRA Small",
        "model_path": "Lyon28/Electra-Small",
        "task": "text-classification",
        "priority": 8
    },
    "t5-small": {
        "name": "T5 Small",
        "model_path": "Lyon28/T5-Small",
        "task": "text2text-generation",
        "priority": 9
    },
    "pythia": {
        "name": "Pythia",
        "model_path": "Lyon28/Pythia",
        "task": "text-generation",
        "priority": 10
    },
    "gpt-neo": {
        "name": "GPT-Neo",
        "model_path": "Lyon28/GPT-Neo",
        "task": "text-generation",
        "priority": 11  # Largest model - lowest priority
    }
}

class ChatRequest(BaseModel):
    message: str
    model: Optional[str] = "distil-gpt-2"  # Default to fastest model

# Global state
app.state.pipelines = {}
app.state.loading_models = set()
app.state.executor = ThreadPoolExecutor(max_workers=2)

# Optimized model loading
async def load_model_async(model_id: str):
    """Load model in background thread"""
    if model_id in app.state.loading_models:
        return False
    
    app.state.loading_models.add(model_id)
    
    try:
        model_config = MODELS[model_id]
        logger.info(f"πŸ”„ Loading {model_config['name']}...")
        
        # Load in thread to avoid blocking
        loop = asyncio.get_event_loop()
        
        def load_model():
            device = 0 if torch.cuda.is_available() else -1
            dtype = torch.float16 if torch.cuda.is_available() else torch.float32
            
            return pipeline(
                task=model_config["task"],
                model=model_config["model_path"],
                device=device,
                torch_dtype=dtype,
                use_fast=True,
                trust_remote_code=True,
                low_cpu_mem_usage=True,
                # Optimization for faster inference
                pad_token_id=50256 if "gpt" in model_id else None
            )
        
        pipeline_obj = await loop.run_in_executor(app.state.executor, load_model)
        app.state.pipelines[model_id] = pipeline_obj
        logger.info(f"βœ… {model_config['name']} loaded successfully")
        return True
        
    except Exception as e:
        logger.error(f"❌ Failed to load {model_id}: {e}")
        return False
    finally:
        app.state.loading_models.discard(model_id)

@app.on_event("startup")
async def load_models():
    """Load high-priority models on startup"""
    os.environ['HF_HOME'] = './cache/huggingface'  # Persistent cache
    os.makedirs(os.environ['HF_HOME'], exist_ok=True)
    
    # Pre-load top 3 fastest models
    priority_models = sorted(MODELS.keys(), key=lambda x: MODELS[x]['priority'])[:3]
    
    tasks = []
    for model_id in priority_models:
        task = asyncio.create_task(load_model_async(model_id))
        tasks.append(task)
    
    # Load models concurrently
    await asyncio.gather(*tasks, return_exceptions=True)
    logger.info("πŸš€ LyonPoy AI Chat Ready!")

# Optimized inference
async def run_inference(model_id: str, message: str):
    """Run inference in background thread"""
    if model_id not in app.state.pipelines:
        # Try to load model if not available
        success = await load_model_async(model_id)
        if not success:
            raise HTTPException(status_code=503, detail=f"Model {model_id} unavailable")
    
    pipe = app.state.pipelines[model_id]
    model_config = MODELS[model_id]
    
    loop = asyncio.get_event_loop()
    
    def inference():
        start_time = time.time()
        
        try:
            if model_config["task"] == "text-generation":
                # Optimized generation parameters
                result = pipe(
                    message,
                    max_new_tokens=min(50, 150 - len(message.split())),  # Shorter responses
                    temperature=0.7,
                    do_sample=True,
                    top_p=0.9,
                    top_k=50,
                    repetition_penalty=1.1,
                    pad_token_id=pipe.tokenizer.eos_token_id if hasattr(pipe.tokenizer, 'eos_token_id') else 50256
                )[0]['generated_text']
                
                # Clean output
                if result.startswith(message):
                    result = result[len(message):].strip()
                
                # Limit response length
                if len(result) > 200:
                    result = result[:200] + "..."
                    
            elif model_config["task"] == "text-classification":
                output = pipe(message)[0]
                result = f"Analisis: {output['label']} (Keyakinan: {output['score']:.2f})"
                
            elif model_config["task"] == "text2text-generation":
                result = pipe(message, max_length=100, num_beams=2)[0]['generated_text']
            
            inference_time = time.time() - start_time
            logger.info(f"⚑ Inference time: {inference_time:.2f}s for {model_config['name']}")
            
            return result
            
        except Exception as e:
            logger.error(f"Inference error: {e}")
            raise e
    
    return await loop.run_in_executor(app.state.executor, inference)

# Frontend route - simplified HTML
@app.get("/", response_class=HTMLResponse)
async def get_frontend():
    html_content = '''
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LyonPoy AI Chat - Fast Mode</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: system-ui; background: #f5f5f5; padding: 20px; }
        .container { max-width: 600px; margin: 0 auto; background: white; border-radius: 10px; overflow: hidden; }
        .header { background: #007bff; color: white; padding: 15px; }
        .chat { height: 400px; overflow-y: auto; padding: 15px; background: #fafafa; }
        .message { margin: 10px 0; padding: 8px 12px; border-radius: 8px; }
        .user { background: #007bff; color: white; margin-left: 20%; }
        .bot { background: white; border: 1px solid #ddd; margin-right: 20%; }
        .input-area { padding: 15px; display: flex; gap: 10px; }
        input { flex: 1; padding: 10px; border: 1px solid #ddd; border-radius: 5px; }
        button { padding: 10px 15px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; }
        select { padding: 5px; margin-left: 10px; }
        .loading { color: #666; font-style: italic; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>πŸš€ LyonPoy AI - Fast Mode</h1>
            <select id="model">
                <option value="distil-gpt-2">DistilGPT-2 (Fastest)</option>
                <option value="gpt-2-tinny">GPT-2 Tinny</option>
                <option value="tinny-llama">Tinny Llama</option>
                <option value="gpt-2">GPT-2</option>
                <option value="bert-tinny">BERT Tinny</option>
                <option value="albert-base-v2">ALBERT Base V2</option>
                <option value="distilbert-base-uncased">DistilBERT</option>
                <option value="electra-small">ELECTRA Small</option>
                <option value="t5-small">T5 Small</option>
                <option value="pythia">Pythia</option>
                <option value="gpt-neo">GPT-Neo (Slowest)</option>
            </select>
        </div>
        <div class="chat" id="chat"></div>
        <div class="input-area">
            <input type="text" id="message" placeholder="Ketik pesan..." maxlength="200">
            <button onclick="sendMessage()">Kirim</button>
        </div>
    </div>
    
    <script>
        const chat = document.getElementById('chat');
        const messageInput = document.getElementById('message');
        const modelSelect = document.getElementById('model');
        
        function addMessage(content, isUser = false) {
            const div = document.createElement('div');
            div.className = `message ${isUser ? 'user' : 'bot'}`;
            div.textContent = content;
            chat.appendChild(div);
            chat.scrollTop = chat.scrollHeight;
        }
        
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) return;
            
            addMessage(message, true);
            messageInput.value = '';
            addMessage('⏳ Thinking...', false);
            
            const startTime = Date.now();
            
            try {
                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        message: message, 
                        model: modelSelect.value 
                    })
                });
                
                const data = await response.json();
                const responseTime = ((Date.now() - startTime) / 1000).toFixed(1);
                
                // Remove loading message
                chat.removeChild(chat.lastElementChild);
                
                if (data.status === 'success') {
                    addMessage(`${data.response} (${responseTime}s)`, false);
                } else {
                    addMessage('❌ Error occurred', false);
                }
            } catch (error) {
                chat.removeChild(chat.lastElementChild);
                addMessage('❌ Connection error', false);
            }
        }
        
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
        
        // Show welcome message
        addMessage('πŸ‘‹ Halo! Pilih model dan mulai chat. Model DistilGPT-2 paling cepat!', false);
    </script>
</body>
</html>
    '''
    return HTMLResponse(content=html_content)

# Optimized chat endpoint
@app.post("/chat")
async def chat(request: ChatRequest, background_tasks: BackgroundTasks):
    try:
        model_id = request.model.lower()
        if model_id not in MODELS:
            raise HTTPException(status_code=400, detail="Model tidak tersedia")
        
        # Limit message length for faster processing
        message = request.message[:200]  # Max 200 chars
        
        # Run inference
        result = await run_inference(model_id, message)
        
        # Load next priority model in background
        background_tasks.add_task(preload_next_model, model_id)
        
        return {
            "response": result,
            "model": MODELS[model_id]["name"],
            "status": "success"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Chat error: {e}")
        raise HTTPException(status_code=500, detail="Terjadi kesalahan")

async def preload_next_model(current_model: str):
    """Preload next model in background"""
    try:
        # Find next unloaded model by priority
        loaded_models = set(app.state.pipelines.keys())
        all_models = sorted(MODELS.keys(), key=lambda x: MODELS[x]['priority'])
        
        for model_id in all_models:
            if model_id not in loaded_models and model_id not in app.state.loading_models:
                await load_model_async(model_id)
                break
    except Exception as e:
        logger.error(f"Background loading error: {e}")

# Health check with model status
@app.get("/health")
async def health():
    loaded_models = list(app.state.pipelines.keys())
    return {
        "status": "healthy",
        "gpu": torch.cuda.is_available(),
        "loaded_models": loaded_models,
        "loading_models": list(app.state.loading_models)
    }

# Model status endpoint
@app.get("/models")
async def get_models():
    models_status = {}
    for model_id, config in MODELS.items():
        models_status[model_id] = {
            "name": config["name"],
            "loaded": model_id in app.state.pipelines,
            "loading": model_id in app.state.loading_models,
            "priority": config["priority"]
        }
    return models_status

# Cleanup on shutdown
@app.on_event("shutdown")
async def cleanup():
    app.state.executor.shutdown(wait=True)

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))
    uvicorn.run(
        app, 
        host="0.0.0.0", 
        port=port,
        log_level="info",
        access_log=False  # Disable access log for better performance
    )