File size: 22,256 Bytes
080889d
 
 
f7f48e6
080889d
f7f48e6
efcf977
 
f7f48e6
080889d
 
 
 
 
 
 
 
efcf977
 
 
 
 
080889d
 
f7f48e6
 
 
 
080889d
f7f48e6
080889d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f48e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50cf1fb
f7f48e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efcf977
 
 
 
 
f7f48e6
 
 
efcf977
f7f48e6
efcf977
f7f48e6
efcf977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
080889d
 
 
 
 
 
 
 
 
 
 
 
 
 
efcf977
080889d
 
 
 
 
 
 
 
 
efcf977
080889d
 
 
 
 
 
 
 
efcf977
080889d
 
 
 
 
 
efcf977
080889d
 
 
 
efcf977
080889d
 
 
 
efcf977
080889d
 
 
 
 
efcf977
080889d
 
 
 
 
 
 
 
 
 
efcf977
080889d
efcf977
080889d
 
 
efcf977
080889d
 
 
 
 
efcf977
080889d
 
 
efcf977
080889d
 
 
efcf977
080889d
 
 
efcf977
080889d
 
 
 
 
 
 
 
 
 
efcf977
080889d
 
 
 
efcf977
080889d
 
 
 
 
 
 
 
 
 
 
 
efcf977
080889d
 
 
 
efcf977
080889d
 
 
efcf977
080889d
 
 
 
 
efcf977
080889d
 
 
 
 
 
 
 
 
f7f48e6
080889d
efcf977
080889d
 
 
efcf977
f7f48e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
080889d
 
 
 
 
 
 
 
 
efcf977
080889d
 
 
efcf977
080889d
 
 
 
 
efcf977
 
 
 
 
 
 
 
 
 
 
 
 
 
080889d
 
 
 
 
 
 
 
efcf977
080889d
 
 
 
efcf977
080889d
 
 
 
 
efcf977
080889d
 
efcf977
080889d
 
 
 
efcf977
080889d
 
 
 
efcf977
080889d
 
 
 
 
 
efcf977
080889d
 
 
 
efcf977
080889d
 
efcf977
080889d
 
 
efcf977
f7f48e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50cf1fb
f7f48e6
 
 
 
 
 
 
 
 
 
080889d
 
 
efcf977
080889d
efcf977
080889d
 
 
 
efcf977
080889d
 
 
f7f48e6
efcf977
 
 
080889d
 
 
 
 
 
 
 
efcf977
080889d
efcf977
080889d
f7f48e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
080889d
efcf977
080889d
efcf977
080889d
efcf977
080889d
 
 
 
 
efcf977
080889d
 
 
 
 
efcf977
080889d
 
 
efcf977
080889d
efcf977
080889d
 
 
 
efcf977
080889d
 
 
efcf977
 
 
080889d
 
 
 
 
 
 
 
efcf977
080889d
efcf977
080889d
 
 
efcf977
080889d
efcf977
080889d
efcf977
080889d
 
 
 
 
efcf977
080889d
 
 
 
 
efcf977
080889d
 
 
 
 
 
 
 
 
 
 
 
 
 
efcf977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
080889d
 
 
efcf977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
080889d
 
 
efcf977
 
 
 
 
 
 
 
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import torch
import torch.nn.functional as F
import asyncio
from datetime import datetime
from typing import List, Dict

# Initialize FastAPI app
app = FastAPI(title="LLM Inference Server")

# Determine device (CPU for free tier)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")

# Request queues
chat_queue = asyncio.Queue()
summarize_queue = asyncio.Queue()
queue_stats = {"chat": 0, "summarize": 0}

# Load models
print("Loading Qwen model for chat...")
chat_model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2.5-0.5B-Instruct",
    torch_dtype=torch.float32 if device == "cpu" else torch.float16,
    device_map=device
)
chat_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")

print("Loading summarization model...")
summarizer = pipeline(
    "summarization",
    model="Falconsai/text_summarization",
    device=device
)

print("Models loaded successfully!")

# Request models
class ChatRequest(BaseModel):
    message: str

class SummarizeRequest(BaseModel):
    text: str

def generate_with_token_probs(model, tokenizer, messages: List[Dict], max_new_tokens: int = 512):
    """
    Generate text and capture top-5 token predictions with probabilities for each step.
    """
    # Apply chat template
    text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    inputs = tokenizer(text, return_tensors="pt").to(model.device)

    # Generate with scores
    outputs = model.generate(
        **inputs,
        max_new_tokens=max_new_tokens,
        temperature=0.7,
        do_sample=True,
        output_scores=True,
        return_dict_in_generate=True,
        pad_token_id=tokenizer.eos_token_id
    )

    # Extract generated tokens (excluding input)
    generated_tokens = outputs.sequences[0][inputs.input_ids.shape[1]:]

    # Process scores to get top-5 predictions for each token
    token_data = []
    for idx, score in enumerate(outputs.scores):
        # Apply softmax to get probabilities
        probs = F.softmax(score[0], dim=-1)

        # Get top 5 predictions
        top5_probs, top5_indices = torch.topk(probs, k=5)

        # Decode tokens
        top5_tokens = [tokenizer.decode([token_id]) for token_id in top5_indices]
        top5_probs_list = [float(prob) * 100 for prob in top5_probs]  # Convert to percentage

        # Build alternatives list
        alternatives = []
        for token, prob in zip(top5_tokens, top5_probs_list):
            alternatives.append({
                "token": token,
                "probability": round(prob, 10)
            })

        # Get the actual generated token
        actual_token = tokenizer.decode([generated_tokens[idx]])

        token_data.append({
            "token": actual_token,
            "top5": alternatives
        })

    # Build full response text
    full_response = tokenizer.decode(generated_tokens, skip_special_tokens=True)

    return {
        "response": full_response,
        "tokens": token_data
    }

# Queue processor for chat with token probabilities
async def process_chat_queue():
    while True:
        request_data = await chat_queue.get()
        try:
            messages = [{"role": "user", "content": request_data["message"]}]
            result = generate_with_token_probs(
                chat_model,
                chat_tokenizer,
                messages,
                max_new_tokens=512
            )
            request_data["result"] = result
        except Exception as e:
            request_data["result"] = {"error": str(e)}
        finally:
            queue_stats["chat"] = max(0, queue_stats["chat"] - 1)
            chat_queue.task_done()

# Queue processor for summarization
async def process_summarize_queue():
    while True:
        request_data = await summarize_queue.get()
        try:
            summary = summarizer(
                request_data["text"],
                max_length=130,
                min_length=30,
                do_sample=False
            )
            request_data["result"] = {"summary": summary[0]["summary_text"]}
        except Exception as e:
            request_data["result"] = {"error": str(e)}
        finally:
            queue_stats["summarize"] = max(0, queue_stats["summarize"] - 1)
            summarize_queue.task_done()

# Start queue processors on startup
@app.on_event("startup")
async def startup_event():
    asyncio.create_task(process_chat_queue())
    asyncio.create_task(process_summarize_queue())

# Custom HTML UI
@app.get("/", response_class=HTMLResponse)
async def root():
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>LLM Inference Server</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 20px;
            }

            .container {
                background: white;
                border-radius: 20px;
                box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                max-width: 800px;
                width: 100%;
                overflow: hidden;
            }

            .header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 30px;
                text-align: center;
            }

            h1 {
                font-size: 2.5em;
                margin-bottom: 10px;
            }

            .subtitle {
                opacity: 0.9;
                font-size: 1.1em;
            }

            .tabs {
                display: flex;
                background: #f5f5f5;
                border-bottom: 2px solid #e0e0e0;
            }

            .tab {
                flex: 1;
                padding: 20px;
                text-align: center;
                cursor: pointer;
                font-weight: 600;
                transition: all 0.3s;
                background: #f5f5f5;
                border: none;
                font-size: 1.1em;
                color: black;
            }

            .tab:hover {
                background: #e8e8e8;
            }

            .tab.active {
                background: white;
                color: #667eea;
                border-bottom: 3px solid #667eea;
            }

            .content {
                padding: 30px;
            }

            .tab-content {
                display: none;
            }

            .tab-content.active {
                display: block;
            }

            textarea {
                width: 100%;
                padding: 15px;
                border: 2px solid #e0e0e0;
                border-radius: 10px;
                font-size: 1em;
                font-family: inherit;
                resize: vertical;
                transition: border-color 0.3s;
            }

            textarea:focus {
                outline: none;
                border-color: #667eea;
            }

            button {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                padding: 15px 40px;
                font-size: 1.1em;
                border-radius: 10px;
                cursor: pointer;
                margin-top: 20px;
                transition: transform 0.2s, box-shadow 0.2s;
                font-weight: 600;
            }

            button:hover {
                transform: translateY(-2px);
                box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
            }

            button:active {
                transform: translateY(0);
            }

            button:disabled {
                opacity: 0.6;
                cursor: not-allowed;
                transform: none;
            }

            .response {
                margin-top: 20px;
                padding: 20px;
                background: #f9f9f9;
                border-radius: 10px;
                border-left: 4px solid #667eea;
                white-space: pre-wrap;
                word-wrap: break-word;
                display: none;
                line-height: 1.6;
            }

            .response.show {
                display: block;
            }

            /* Token visualization styles */
            .token {
                display: inline;
                position: relative;
                cursor: help;
                padding: 2px 1px;
                transition: background-color 0.2s;
            }

            .token:hover {
                background-color: #fff3cd;
                border-radius: 3px;
            }

            .tooltip {
                visibility: hidden;
                position: absolute;
                bottom: 125%;
                left: 50%;
                transform: translateX(-50%);
                background-color: #333;
                color: white;
                padding: 12px;
                border-radius: 8px;
                font-size: 0.85em;
                white-space: nowrap;
                z-index: 1000;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                min-width: 200px;
            }

            .tooltip::after {
                content: "";
                position: absolute;
                top: 100%;
                left: 50%;
                transform: translateX(-50%);
                border-width: 6px;
                border-style: solid;
                border-color: #333 transparent transparent transparent;
            }

            .token:hover .tooltip {
                visibility: visible;
                opacity: 1;
            }

            .tooltip-item {
                display: flex;
                justify-content: space-between;
                padding: 3px 0;
                border-bottom: 1px solid rgba(255,255,255,0.1);
            }

            .tooltip-item:last-child {
                border-bottom: none;
            }

            .tooltip-rank {
                color: #ffd700;
                font-weight: 600;
                margin-right: 8px;
            }

            .tooltip-token {
                font-family: monospace;
                color: #fff;
                margin-right: 8px;
            }

            .tooltip-prob {
                color: #90ee90;
                font-weight: 500;
            }

            .loading {
                display: inline-block;
                width: 20px;
                height: 20px;
                border: 3px solid rgba(255,255,255,.3);
                border-radius: 50%;
                border-top-color: white;
                animation: spin 1s ease-in-out infinite;
            }

            @keyframes spin {
                to { transform: rotate(360deg); }
            }

            .error {
                color: #d32f2f;
                background: #ffebee;
                border-left-color: #d32f2f;
            }

            .queue-info {
                margin-top: 10px;
                padding: 10px;
                background: #e3f2fd;
                border-radius: 5px;
                font-size: 0.9em;
                color: #1976d2;
                display: none;
            }

            .queue-info.show {
                display: block;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>๐Ÿค– LLM Inference Server</h1>
                <p class="subtitle">Powered by Qwen & Falconsai</p>
            </div>

            <div class="tabs">
                <button class="tab active" onclick="switchTab('chat')">๐Ÿ’ฌ Chat</button>
                <button class="tab" onclick="switchTab('summarize')">๐Ÿ“ Summarize</button>
            </div>

            <div class="content">
                <div id="chat" class="tab-content active">
                    <h2 style="margin-bottom: 15px;">Chat with Qwen</h2>
                    <textarea id="chatInput" rows="4" placeholder="Type your message here..."></textarea>
                    <button onclick="sendChat()">Send Message</button>
                    <div id="chatQueue" class="queue-info"></div>
                    <div id="chatResponse" class="response"></div>
                </div>

                <div id="summarize" class="tab-content">
                    <h2 style="margin-bottom: 15px;">Summarize Text</h2>
                    <textarea id="summarizeInput" rows="8" placeholder="Paste the text you want to summarize..."></textarea>
                    <button onclick="sendSummarize()">Generate Summary</button>
                    <div id="summarizeQueue" class="queue-info"></div>
                    <div id="summarizeResponse" class="response"></div>
                </div>
            </div>
        </div>

        <script>
            function switchTab(tabName) {
                // Hide all tab contents
                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.remove('active');
                });

                // Remove active class from all tabs
                document.querySelectorAll('.tab').forEach(tab => {
                    tab.classList.remove('active');
                });

                // Show selected tab content
                document.getElementById(tabName).classList.add('active');

                // Add active class to clicked tab
                event.target.classList.add('active');
            }

            function createTokenTooltip(tokenData, index) {
                const tokenSpan = document.createElement('span');
                tokenSpan.className = 'token';
                tokenSpan.textContent = tokenData.token;

                const tooltip = document.createElement('div');
                tooltip.className = 'tooltip';

                // Create tooltip content
                let tooltipHTML = '';
                tokenData.top5.forEach((item, rank) => {
                    const rankLabel = rank === 0 ? '1st (chosen)' :
                                     rank === 1 ? '2nd' :
                                     rank === 2 ? '3rd' :
                                     rank === 3 ? '4th' : '5th';
                    tooltipHTML += `
                        <div class="tooltip-item">
                            <span class="tooltip-rank">${rankLabel}:</span>
                            <span class="tooltip-token">"${item.token}"</span>
                            <span class="tooltip-prob">${item.probability.toFixed(10)}%</span>
                        </div>
                    `;
                });

                tooltip.innerHTML = tooltipHTML;
                tokenSpan.appendChild(tooltip);

                return tokenSpan;
            }

            async function sendChat() {
                const input = document.getElementById('chatInput');
                const responseDiv = document.getElementById('chatResponse');
                const queueDiv = document.getElementById('chatQueue');
                const button = event.target;

                if (!input.value.trim()) {
                    alert('Please enter a message');
                    return;
                }

                button.disabled = true;
                button.innerHTML = '<span class="loading"></span> Processing...';
                responseDiv.classList.remove('show', 'error');
                responseDiv.innerHTML = '';
                queueDiv.classList.add('show');
                queueDiv.textContent = 'Adding to queue...';

                try {
                    const response = await fetch('/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ message: input.value })
                    });

                    const data = await response.json();

                    if (response.ok) {
                        // Clear previous content
                        responseDiv.innerHTML = '';

                        // Check if we have token data
                        if (data.tokens && data.tokens.length > 0) {
                            // Create interactive token display
                            data.tokens.forEach((tokenData, index) => {
                                const tokenElement = createTokenTooltip(tokenData, index);
                                responseDiv.appendChild(tokenElement);
                            });
                        } else {
                            // Fallback to plain text
                            responseDiv.textContent = data.response;
                        }

                        responseDiv.classList.remove('error');
                        queueDiv.classList.remove('show');
                    } else {
                        responseDiv.textContent = 'Error: ' + (data.detail || data.error || 'Unknown error');
                        responseDiv.classList.add('error');
                        queueDiv.classList.remove('show');
                    }
                    responseDiv.classList.add('show');
                } catch (error) {
                    responseDiv.textContent = 'Error: ' + error.message;
                    responseDiv.classList.add('error', 'show');
                    queueDiv.classList.remove('show');
                } finally {
                    button.disabled = false;
                    button.textContent = 'Send Message';
                }
            }

            async function sendSummarize() {
                const input = document.getElementById('summarizeInput');
                const responseDiv = document.getElementById('summarizeResponse');
                const queueDiv = document.getElementById('summarizeQueue');
                const button = event.target;

                if (!input.value.trim()) {
                    alert('Please enter text to summarize');
                    return;
                }

                button.disabled = true;
                button.innerHTML = '<span class="loading"></span> Processing...';
                responseDiv.classList.remove('show', 'error');
                queueDiv.classList.add('show');
                queueDiv.textContent = 'Adding to queue...';

                try {
                    const response = await fetch('/summarize', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ text: input.value })
                    });

                    const data = await response.json();

                    if (response.ok) {
                        responseDiv.textContent = data.summary;
                        responseDiv.classList.remove('error');
                        queueDiv.classList.remove('show');
                    } else {
                        responseDiv.textContent = 'Error: ' + (data.detail || data.error || 'Unknown error');
                        responseDiv.classList.add('error');
                        queueDiv.classList.remove('show');
                    }
                    responseDiv.classList.add('show');
                } catch (error) {
                    responseDiv.textContent = 'Error: ' + error.message;
                    responseDiv.classList.add('error', 'show');
                    queueDiv.classList.remove('show');
                } finally {
                    button.disabled = false;
                    button.textContent = 'Generate Summary';
                }
            }

            // Allow Enter key to submit (with Shift+Enter for new line)
            document.getElementById('chatInput').addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendChat();
                }
            });
        </script>
    </body>
    </html>
    """

@app.post("/chat")
async def chat(request: ChatRequest):
    queue_stats["chat"] += 1
    request_data = {"message": request.message, "result": None}
    await chat_queue.put(request_data)

    # Wait for result with timeout
    timeout = 120  # 2 minutes
    start_time = datetime.now()
    while request_data["result"] is None:
        await asyncio.sleep(0.5)
        if (datetime.now() - start_time).total_seconds() > timeout:
            return JSONResponse(content={"error": "Request timeout"}, status_code=504)

    result = request_data["result"]
    if "error" in result:
        return JSONResponse(content=result, status_code=500)
    return JSONResponse(content=result)

@app.post("/summarize")
async def summarize(request: SummarizeRequest):
    queue_stats["summarize"] += 1
    request_data = {"text": request.text, "result": None}
    await summarize_queue.put(request_data)

    # Wait for result with timeout
    timeout = 120  # 2 minutes
    start_time = datetime.now()
    while request_data["result"] is None:
        await asyncio.sleep(0.5)
        if (datetime.now() - start_time).total_seconds() > timeout:
            return JSONResponse(content={"error": "Request timeout"}, status_code=504)

    result = request_data["result"]
    if "error" in result:
        return JSONResponse(content=result, status_code=500)
    return JSONResponse(content=result)

@app.get("/health")
async def health():
    return {"status": "healthy", "device": device, "queue": queue_stats}

@app.get("/queue")
async def get_queue_status():
    return {
        "chat_queue": queue_stats["chat"],
        "summarize_queue": queue_stats["summarize"]
    }