-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduction_server.py
More file actions
514 lines (403 loc) · 15.7 KB
/
production_server.py
File metadata and controls
514 lines (403 loc) · 15.7 KB
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
#!/usr/bin/env python3
"""
Production TTS Server with Micro-Batching
High-concurrency, low-latency TTS server implementing:
- Token-level micro-batching across sessions
- Pre-allocated KV cache for N concurrent sessions
- Streaming audio with TTFB optimization
- Fair scheduling with priority for new sessions
Target: 16-32 concurrent sessions on RTX 4090 with <150ms TTFB
"""
import os
import sys
import time
import asyncio
import logging
import argparse
import struct
from pathlib import Path
from typing import Optional, AsyncGenerator
from contextlib import asynccontextmanager
import numpy as np
import yaml
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel, Field
# Add src to path
sys.path.insert(0, str(Path(__file__).parent))
from src.scheduler import (
BatchInferenceEngine,
SchedulerConfig,
SessionConfig,
TTSSession,
)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# ============================================================================
# Configuration
# ============================================================================
def load_config(path: str) -> dict:
"""Load configuration from YAML file."""
with open(path, 'r') as f:
return yaml.safe_load(f)
# ============================================================================
# Mock engines for development (replace with real engines in production)
# ============================================================================
class MockLLMEngine:
"""Mock LLM engine for development/testing."""
def __init__(self):
from transformers import AutoTokenizer
try:
self.tokenizer = AutoTokenizer.from_pretrained(
"meta-llama/Llama-3.2-3B-Instruct",
trust_remote_code=True,
)
except Exception as e:
logger.warning(f"Could not load tokenizer: {e}")
self.tokenizer = None
def format_prompt(self, text: str, voice: str = "tara") -> str:
"""Format the TTS prompt."""
return f"<|audio|>{voice}: {text}<|eoa|>"
async def generate_tokens(self, prompt: str, max_tokens: int = 100):
"""Generate tokens (mock)."""
for i in range(max_tokens):
# Simulate audio tokens
token = 128266 + (i % 4096)
yield token
await asyncio.sleep(0.005) # ~200 tok/s simulation
class MockSNACDecoder:
"""Mock SNAC decoder for development/testing."""
AUDIO_TOKEN_OFFSET = 128266
TOKENS_PER_FRAME = 7
SAMPLE_RATE = 24000
def decode(self, tokens: list) -> np.ndarray:
"""Decode tokens to audio (mock - generates silence with click)."""
if not tokens:
return np.array([], dtype=np.float32)
# ~10.67ms per token frame
samples_per_frame = int(0.01067 * self.SAMPLE_RATE)
total_samples = (len(tokens) // self.TOKENS_PER_FRAME) * samples_per_frame
if total_samples == 0:
return np.array([], dtype=np.float32)
# Generate low-amplitude white noise as placeholder
audio = np.random.randn(total_samples).astype(np.float32) * 0.01
return audio
# ============================================================================
# API Models
# ============================================================================
class TTSRequest(BaseModel):
"""TTS request body."""
text: str = Field(..., min_length=1, max_length=10000)
voice: str = Field(default="tara")
response_format: str = Field(default="wav")
speed: float = Field(default=1.0, ge=0.5, le=2.0)
# Advanced options
temperature: float = Field(default=0.6, ge=0.0, le=1.5)
top_p: float = Field(default=0.95, ge=0.0, le=1.0)
max_tokens: int = Field(default=4096, ge=1, le=8192)
class HealthResponse(BaseModel):
"""Health check response."""
status: str
gpu_available: bool
engine_stats: dict
class StatsResponse(BaseModel):
"""Server statistics response."""
scheduler: dict
kv_cache: dict
total_batches: int
total_tokens: int
total_audio_chunks: int
# ============================================================================
# Audio Utilities
# ============================================================================
def create_wav_header(sample_rate: int = 24000, bits_per_sample: int = 16) -> bytes:
"""Create WAV header for streaming (unknown length)."""
return struct.pack(
'<4sI4s4sIHHIIHH4sI',
b'RIFF',
0xFFFFFFFF, # Placeholder for unknown length
b'WAVE',
b'fmt ',
16, # Subchunk1Size
1, # AudioFormat (PCM)
1, # NumChannels
sample_rate,
sample_rate * bits_per_sample // 8, # ByteRate
bits_per_sample // 8, # BlockAlign
bits_per_sample,
b'data',
0xFFFFFFFF, # Placeholder for unknown length
)
# ============================================================================
# Global state
# ============================================================================
engine: Optional[BatchInferenceEngine] = None
# ============================================================================
# FastAPI Application
# ============================================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan handler."""
global engine
logger.info("Starting production TTS server...")
# Load configuration
config_path = os.environ.get("CONFIG_PATH", "config/model_config.yaml")
try:
config = load_config(config_path)
except Exception as e:
logger.warning(f"Could not load config: {e}, using defaults")
config = {}
# Create scheduler config
server_config = config.get("server", {})
scheduler_config = SchedulerConfig(
max_concurrent_sessions=server_config.get("max_concurrent_sessions", 32),
max_batch_size=server_config.get("max_batch_size", 16),
ttfb_priority_tokens=server_config.get("ttfb_priority_tokens", 20),
flush_first_n_tokens=7, # SNAC needs 7 tokens for first frame
flush_every_n_tokens=14, # ~160ms audio chunks
max_new_tokens_per_call=4096,
kv_cache_slots=32,
max_context_len=4096,
)
# Initialize engines (mock for development)
logger.info("Initializing engines...")
llm = MockLLMEngine()
snac = MockSNACDecoder()
# Create batch inference engine
engine = BatchInferenceEngine(
llm_engine=llm,
snac_decoder=snac,
config=scheduler_config,
)
# Start the engine
await engine.start()
logger.info("Production TTS server ready")
logger.info(f" Max concurrent sessions: {scheduler_config.max_concurrent_sessions}")
logger.info(f" Max batch size: {scheduler_config.max_batch_size}")
yield
# Shutdown
logger.info("Shutting down...")
if engine:
await engine.stop()
app = FastAPI(
title="Orpheus TTS Production Server",
description="High-concurrency, low-latency TTS with micro-batching",
version="2.0.0",
lifespan=lifespan,
)
# ============================================================================
# Endpoints
# ============================================================================
@app.get("/health", response_model=HealthResponse)
async def health():
"""Health check endpoint."""
import torch
stats = engine.get_stats() if engine else {}
return HealthResponse(
status="healthy" if engine else "starting",
gpu_available=torch.cuda.is_available(),
engine_stats=stats,
)
@app.get("/v1/stats", response_model=StatsResponse)
async def get_stats():
"""Get detailed server statistics."""
if not engine:
raise HTTPException(status_code=503, detail="Engine not ready")
stats = engine.get_stats()
return StatsResponse(**stats)
@app.get("/v1/voices")
async def list_voices():
"""List available voices."""
return {
"voices": [
{"id": "tara", "name": "Tara", "description": "Default female voice"},
{"id": "leah", "name": "Leah", "description": "Female voice"},
{"id": "jess", "name": "Jess", "description": "Female voice"},
{"id": "leo", "name": "Leo", "description": "Male voice"},
{"id": "dan", "name": "Dan", "description": "Male voice"},
{"id": "mia", "name": "Mia", "description": "Female voice"},
{"id": "zac", "name": "Zac", "description": "Male voice"},
{"id": "zoe", "name": "Zoe", "description": "Female voice"},
]
}
async def stream_audio(session: TTSSession) -> AsyncGenerator[bytes, None]:
"""Stream audio from a session."""
# Send WAV header first
yield create_wav_header()
bytes_sent = 0
start_time = time.perf_counter()
try:
while True:
try:
# Wait for audio chunk with timeout
chunk = await asyncio.wait_for(
session.audio_queue.get(),
timeout=30.0
)
if chunk is None:
# End of stream
break
bytes_sent += len(chunk)
yield chunk
except asyncio.TimeoutError:
logger.warning(f"Session {session.session_id[:8]} timed out")
break
finally:
elapsed = time.perf_counter() - start_time
logger.info(
f"Session {session.session_id[:8]} streamed "
f"{bytes_sent/1024:.1f}KB in {elapsed:.2f}s"
)
@app.post("/v1/audio/speech")
async def create_speech(request: TTSRequest):
"""
Generate speech from text with streaming response.
Compatible with OpenAI TTS API.
"""
if not engine:
raise HTTPException(status_code=503, detail="Engine not ready")
try:
# Create session config
session_config = SessionConfig(
temperature=request.temperature,
top_p=request.top_p,
max_new_tokens=request.max_tokens,
)
# Submit request
session = await engine.submit_request(
text=request.text,
voice=request.voice,
config=session_config,
)
# Return streaming response
return StreamingResponse(
stream_audio(session),
media_type="audio/wav",
headers={
"X-Session-ID": session.session_id,
"Transfer-Encoding": "chunked",
}
)
except RuntimeError as e:
raise HTTPException(status_code=429, detail=str(e))
except Exception as e:
logger.error(f"Speech generation error: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.websocket("/v1/audio/stream")
async def websocket_stream(websocket: WebSocket):
"""
WebSocket endpoint for real-time streaming TTS.
Protocol:
- Client sends: {"text": "...", "voice": "...", ...}
- Server sends: binary audio chunks
- Server sends: {"done": true, "metrics": {...}} when complete
"""
await websocket.accept()
try:
while True:
# Receive request
data = await websocket.receive_json()
text = data.get("text", "")
voice = data.get("voice", "tara")
if not text:
await websocket.send_json({"error": "No text provided"})
continue
try:
# Submit request
session = await engine.submit_request(text=text, voice=voice)
# Stream audio chunks
while True:
try:
chunk = await asyncio.wait_for(
session.audio_queue.get(),
timeout=30.0
)
if chunk is None:
# Send completion message
metrics = session.get_metrics()
await websocket.send_json({
"done": True,
"metrics": metrics
})
break
# Send binary audio
await websocket.send_bytes(chunk)
except asyncio.TimeoutError:
await websocket.send_json({"error": "Timeout"})
break
except RuntimeError as e:
await websocket.send_json({"error": str(e)})
except WebSocketDisconnect:
logger.info("WebSocket client disconnected")
except Exception as e:
logger.error(f"WebSocket error: {e}")
# ============================================================================
# gRPC-style endpoint for backend-to-backend
# ============================================================================
@app.post("/v1/audio/generate")
async def generate_audio(request: TTSRequest):
"""
Generate complete audio (non-streaming).
For batch processing or backend-to-backend calls.
"""
if not engine:
raise HTTPException(status_code=503, detail="Engine not ready")
try:
session = await engine.submit_request(
text=request.text,
voice=request.voice,
)
# Collect all audio
chunks = []
while True:
try:
chunk = await asyncio.wait_for(
session.audio_queue.get(),
timeout=60.0
)
if chunk is None:
break
chunks.append(chunk)
except asyncio.TimeoutError:
break
# Combine and return
audio_data = b''.join(chunks)
wav_header = create_wav_header()
return StreamingResponse(
iter([wav_header + audio_data]),
media_type="audio/wav",
headers={
"X-Session-ID": session.session_id,
"X-TTFB-Ms": str(int(session.get_ttfb_ms())),
"X-Total-Tokens": str(session.total_tokens),
}
)
except RuntimeError as e:
raise HTTPException(status_code=429, detail=str(e))
# ============================================================================
# Main
# ============================================================================
def main():
parser = argparse.ArgumentParser(description="Production TTS Server")
parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
parser.add_argument("--config", default="config/model_config.yaml", help="Config file")
parser.add_argument("--workers", type=int, default=1, help="Number of workers")
parser.add_argument("--reload", action="store_true", help="Enable auto-reload")
args = parser.parse_args()
# Set config path
os.environ["CONFIG_PATH"] = args.config
import uvicorn
uvicorn.run(
"production_server:app",
host=args.host,
port=args.port,
workers=args.workers,
reload=args.reload,
log_level="info",
)
if __name__ == "__main__":
main()