-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathserver.py
More file actions
1678 lines (1379 loc) · 63.8 KB
/
Copy pathserver.py
File metadata and controls
1678 lines (1379 loc) · 63.8 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
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import contextlib
import copy
import inspect
import json
import logging
import multiprocessing as mp
import os
import pickle
import secrets
import socket
import sys
import threading
import time
import uuid
import warnings
from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Callable, Iterable, Mapping, Sequence
from contextlib import asynccontextmanager
from queue import Queue
from typing import TYPE_CHECKING, Any, Literal, Optional, Union
import uvicorn
import uvicorn.server
from fastapi import Depends, FastAPI, HTTPException, Request, Response, status
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.security import APIKeyHeader, OAuth2PasswordBearer
from starlette.formparsers import MultiPartParser
from starlette.middleware.gzip import GZipMiddleware
from litserve import LitAPI
from litserve.callbacks.base import Callback, CallbackRunner, EventTypes
from litserve.connector import _Connector
from litserve.loggers import Logger, _LoggerConnector
from litserve.loops import LitLoop, inference_worker
from litserve.middlewares import MaxSizeMiddleware, RequestCountMiddleware
from litserve.python_client import client_template
from litserve.specs.base import LitSpec
from litserve.transport.base import MessageTransport
from litserve.transport.factory import TransportConfig, create_transport_from_config
from litserve.utils import (
LitAPIStatus,
LoopResponseType,
ResponseBufferItem,
WorkerSetupStatus,
add_ssl_context_from_env,
call_after_stream,
configure_logging,
is_package_installed,
)
_MCP_AVAILABLE = is_package_installed("mcp")
if TYPE_CHECKING:
from litserve.mcp import ToolEndpointType
mp.allow_connection_pickling()
logger = logging.getLogger(__name__)
# if defined, it will require clients to auth with X-API-Key in the header
LIT_SERVER_API_KEY = os.environ.get("LIT_SERVER_API_KEY")
SHUTDOWN_API_KEY = os.environ.get("LIT_SHUTDOWN_API_KEY")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# FastAPI writes form files to disk over 1MB by default, which prevents serialization by multiprocessing
MultiPartParser.max_file_size = sys.maxsize
# renamed in PR: https://github.com/encode/starlette/pull/2780
MultiPartParser.spool_max_size = sys.maxsize
def no_auth():
pass
def api_key_auth(x_api_key: str = Depends(APIKeyHeader(name="X-API-Key"))):
if x_api_key != LIT_SERVER_API_KEY:
raise HTTPException(
status_code=401, detail="Invalid API Key. Check that you are passing a correct 'X-API-Key' in your header."
)
async def _mixed_response_to_buffer(
transport: MessageTransport,
response_buffer: dict[str, ResponseBufferItem],
consumer_id: int = 0,
):
"""Handle both regular and streaming responses.
Detect streaming responses by checking if the response is for streaming.
"""
while True:
try:
result = await transport.areceive(consumer_id)
if result is None:
continue
uid, (*response, response_type, worker_id) = result
response_item = response_buffer.get(uid)
if response_item is None:
continue
if response[1] == LitAPIStatus.START:
response_item.worker_id = int(worker_id)
continue
if response_type == LoopResponseType.STREAMING:
response_item.response_queue.append(response)
response_item.event.set()
else:
response_item.response = response
response_item.event.set()
except asyncio.CancelledError:
logger.debug("Response queue to buffer task was cancelled")
break
except Exception as e:
logger.error(f"Error in response_queue_to_buffer: {e}")
break
async def response_queue_to_buffer(
transport: MessageTransport,
response_buffer: dict[str, ResponseBufferItem],
consumer_id: int,
litapi_connector: "_LitAPIConnector",
):
mixed_streaming = (
len(litapi_connector.lit_apis) > 1
and litapi_connector.any_stream()
and not all(api.stream for api in litapi_connector)
)
if mixed_streaming:
return await _mixed_response_to_buffer(transport, response_buffer, consumer_id)
stream = litapi_connector.any_stream()
if stream:
while True:
try:
result = await transport.areceive(consumer_id)
if result is None:
continue
uid, (*response, response_type, worker_id) = result
response_item = response_buffer.get(uid)
if response_item is None:
continue
if response[1] == LitAPIStatus.START:
response_item.worker_id = int(worker_id)
continue
response_item.response_queue.append(response)
response_item.event.set()
except asyncio.CancelledError:
logger.debug("Response queue to buffer task was cancelled")
break
except Exception as e:
logger.error(f"Error in response_queue_to_buffer: {e}")
break
else:
while True:
try:
result = await transport.areceive(consumer_id)
if result is None:
continue
uid, (*response, response_type, worker_id) = result
response_item = response_buffer.get(uid)
if response_item is None:
continue
if response[1] == LitAPIStatus.START:
response_item.worker_id = int(worker_id)
continue
response_item.response = response
response_item.event.set()
except asyncio.CancelledError:
logger.debug("Response queue to buffer task was cancelled")
break
except Exception as e:
logger.error(f"Error in response_queue_to_buffer: {e}")
break
def _migration_warning(feature_name):
warnings.warn(
f"The {feature_name} parameter is being deprecated in `LitServer` "
"and will be removed in version v0.3.0.\n\n"
"Please update your code to pass these arguments to `LitAPI` instead.\n\n"
"Old usage:\n"
f" server = LitServer(api, {feature_name}=...)\n\n"
"New usage:\n"
f" api = LitAPI({feature_name}=...)\n"
" server = LitServer(api, ...)",
DeprecationWarning,
stacklevel=3,
)
class _LitAPIConnector:
"""A helper class to manage one or more `LitAPI` instances.
This class provides utilities for performing setup tasks, managing request
and batch timeouts, and interacting with `LitAPI` instances in a unified way.
It ensures that all `LitAPI` instances are properly initialized and configured
before use.
Attributes:
lit_apis (list[LitAPI]): A list of `LitAPI` instances managed by this connector.
Methods:
pre_setup(): Calls the `pre_setup` method on all managed `LitAPI` instances.
set_request_timeout(timeout): Sets the request timeout for all `LitAPI` instances
and validates that batch timeouts are within acceptable limits.
__iter__(): Allows iteration over the managed `LitAPI` instances.
any_stream(): Checks if any of the `LitAPI` instances have streaming enabled.
set_logger_queue(queue): Sets a logger queue for all `LitAPI` instances.
"""
def __init__(self, lit_apis: Union[LitAPI, Iterable[LitAPI]]):
if isinstance(lit_apis, LitAPI):
self.lit_apis = [lit_apis]
elif isinstance(lit_apis, Iterable):
self.lit_apis = list(lit_apis)
if not self.lit_apis: # Check if the iterable is empty
raise ValueError("lit_apis must not be an empty iterable")
self._detect_path_collision()
else:
raise ValueError(f"lit_apis must be a LitAPI or an iterable of LitAPI, but got {type(lit_apis)}")
def _detect_path_collision(self):
paths = {"/health": "LitServe healthcheck", "/info": "LitServe info"}
for lit_api in self.lit_apis:
if lit_api.api_path in paths:
raise ValueError(f"api_path {lit_api.api_path} is already in use by {paths[lit_api.api_path]}")
paths[lit_api.api_path] = lit_api
def pre_setup(self):
for lit_api in self.lit_apis:
lit_api.pre_setup()
# Ideally LitAPI should not know about LitLoop
# LitLoop can keep litapi as a class variable
lit_api.loop.pre_setup(lit_api)
def set_request_timeout(self, timeout: float):
for lit_api in self.lit_apis:
lit_api.request_timeout = timeout
for lit_api in self.lit_apis:
if lit_api.batch_timeout > timeout and timeout not in (False, -1):
raise ValueError("batch_timeout must be less than request_timeout")
def __iter__(self):
return iter(self.lit_apis)
def any_stream(self):
return any(lit_api.stream for lit_api in self.lit_apis)
def set_logger_queue(self, queue: Queue):
for lit_api in self.lit_apis:
lit_api.set_logger_queue(queue)
def get_mcp_tools(self) -> list["ToolEndpointType"]:
mcp_tools = []
for lit_api in self.lit_apis:
if lit_api.mcp:
mcp_tools.append(lit_api.mcp.as_tool())
return mcp_tools
class BaseRequestHandler(ABC):
def __init__(self, lit_api: LitAPI, server: "LitServer"):
self.lit_api = lit_api
self.server = server
async def _prepare_request(self, request, request_type) -> dict:
"""Common request preparation logic."""
# FastAPI parses JSON body to dict when endpoint uses dict type annotation
if isinstance(request, dict):
return request
if request_type == Request:
content_type = request.headers.get("Content-Type", "")
if content_type == "application/x-www-form-urlencoded" or content_type.startswith("multipart/form-data"):
return await request.form()
return await request.json()
return request
async def _submit_request(self, payload: dict) -> tuple[str, asyncio.Event]:
"""Submit request to worker queue."""
request_queue = self.server._get_request_queue(self.lit_api.api_path)
response_queue_id = self.server.app.response_queue_id
uid = str(uuid.uuid4())
# Trigger callback
self.server._callback_runner.trigger_event(
EventTypes.ON_REQUEST.value,
active_requests=self.server.active_requests,
litserver=self.server,
)
request_queue.put((response_queue_id, uid, time.monotonic(), payload))
logger.debug(f"Submitted request uid={uid}")
return uid, response_queue_id
@abstractmethod
async def handle_request(self, request, request_type) -> Response:
pass
class RegularRequestHandler(BaseRequestHandler):
async def handle_request(self, request, request_type) -> Response:
try:
logger.debug(f"Handling request: {request}")
# Prepare request
payload = await self._prepare_request(request, request_type)
# Submit to worker
uid, _ = await self._submit_request(payload)
# Wait for response
event = asyncio.Event()
self.server.response_buffer[uid] = ResponseBufferItem(event)
await event.wait()
# Process response
response_buffer_item = self.server.response_buffer.pop(uid)
response, status = response_buffer_item.response
if status == LitAPIStatus.ERROR:
self._handle_error_response(response)
# Trigger callback
self.server._callback_runner.trigger_event(EventTypes.ON_RESPONSE.value, litserver=self.server)
return response
except HTTPException as e:
raise e from None
except Exception as e:
logger.error(f"Unhandled exception: {e}", exc_info=True)
raise HTTPException(status_code=500, detail="Internal server error") from e
@staticmethod
def _handle_error_response(response):
"""Raise HTTPException as is and rest as 500 after logging the error."""
try:
if isinstance(response, bytes):
response = pickle.loads(response)
raise HTTPException(status_code=response.status_code, detail=response.detail)
except Exception as e:
logger.debug(f"couldn't unpickle error response {e}")
if isinstance(response, HTTPException):
raise response
if isinstance(response, Exception):
logger.error(f"Error while handling request: {response}")
raise HTTPException(status_code=500, detail="Internal server error")
class StreamingRequestHandler(BaseRequestHandler):
async def handle_request(self, request, request_type) -> StreamingResponse:
try:
# Prepare request
payload = await self._prepare_request(request, request_type)
# Submit to worker
uid, _ = await self._submit_request(payload)
# Set up streaming response
event = asyncio.Event()
response_queue = deque()
self.server.response_buffer[uid] = ResponseBufferItem(event=event, response_queue=response_queue)
# Create streaming response
response_generator = call_after_stream(
self.server.data_streamer(response_queue, data_available=event),
self.server._callback_runner.trigger_event,
EventTypes.ON_RESPONSE.value,
litserver=self.server,
)
async def stream_with_cleanup():
try:
async for item in response_generator:
yield item
finally:
self.server.response_buffer.pop(uid, None)
return StreamingResponse(stream_with_cleanup())
except Exception as e:
logger.exception(f"Error handling streaming request: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
class _Server(uvicorn.server.Server):
def run(self, worker_id: int, sockets: Union[list[socket.socket], None] = None) -> None:
os.environ["LITSERVE_WORKER_ID"] = str(worker_id)
return super().run(sockets)
class LitServer:
"""Initialize a LitServer for high-performance AI model serving.
LitServer transforms AI models into production-ready APIs with automatic scaling,
batching, streaming, and multi-GPU support.
Quick Start:
```python
import litserve as ls
# Define inference pipeline
class MyAPI(ls.LitAPI):
def setup(self, device):
self.model = load_model() # model loading logic
def predict(self, x):
return self.model(x)
# Create and run server
server = ls.LitServer(MyAPI())
server.run(port=8000)
```
Args:
lit_api:
The core component - one or more LitAPI instances defining model logic.
- Single API: `MyAPI()` for serving one model
- Multiple APIs: `[API1(), API2()]` for multi-model serving
Each LitAPI must implement:
- `setup(device)`: Initialize the model
- `predict(x)`: Run inference
- Optional: `decode_request()`, `encode_response()` for custom I/O
Hardware Configuration:
accelerator:
Hardware type for inference. Defaults to "auto".
- "auto": Automatically detects best available (CUDA > MPS > CPU)
- "cpu": Force CPU usage
- "cuda": Use NVIDIA GPUs
- "mps": Use Apple Metal Performance Shaders
devices:
Number of devices to use. Defaults to "auto".
- "auto": Use all available devices
- int: Use specific number (e.g., 2 for 2 GPUs)
workers_per_device:
Worker processes per device for parallel inference. Defaults to 1.
- Higher values = better throughput but more memory usage
- Good starting point: 1-4 depending on model size
- For CPU, set to the number of cores available on the machine (e.g., 8 for 8-core CPU)
- Monitor GPU memory when increasing
Performance & Scaling:
timeout:
Request timeout in seconds. Defaults to 30.
- Set to False or -1 to disable timeouts
- Increase for slow models (e.g., 300 for large LLMs)
- Decrease for fast models (e.g., 5 for lightweight models)
fast_queue:
Enable ZeroMQ for high-throughput scenarios (>100 RPS). Defaults to False.
- Use when serving hundreds of requests per second
- Not supported on Windows
track_requests:
Track active requests across all API servers for monitoring and load management. Defaults to False.
When enabled, tracks the total number of active requests in the queue across all API servers
and makes this count available via callbacks using the `on_request` hook. Essential for
monitoring concurrent request load and implementing custom load management logic.
- Recommended for production deployments
- Access count via callbacks or `server.active_requests` property
- Useful for monitoring and handling concurrent requests effectively
API Configuration:
healthcheck_path:
Health check endpoint for load balancers. Defaults to "/health".
- Returns 200 when all workers are ready
- Critical for Kubernetes/Docker deployments
info_path:
Server information endpoint. Defaults to "/info".
- Shows model metadata, device info, server config
- Useful for debugging and monitoring
disable_openapi_url:
If True, disables the OpenAPI schema endpoint ("/openapi.json").
- Useful for production environments where exposing API schemas is not desired.
- Defaults to False (the OpenAPI schema is enabled).
shutdown_path:
Graceful shutdown endpoint. Defaults to "/shutdown".
enable_shutdown_api:
Enable remote shutdown capability. Defaults to False.
- Requires authentication token (set LIT_SHUTDOWN_API_KEY env var)
- Useful for automated deployment pipelines
restart_workers:
Enable this option to automatically restart
workers if a critical error occurs. Defaults to False.
- When enabled, the worker loop will exit using `os._exit(1)`,
allowing the main process to recreate the worker.
Content & Middleware:
max_payload_size:
Maximum request size. Defaults to "100MB".
- String format: "10MB", "1GB"
- Integer format: bytes (1048576 for 1MB)
- Increase for large images/videos
middlewares:
HTTP middleware for cross-cutting concerns. Defaults to None.
Example:
```python
from starlette.middleware.cors import CORSMiddleware
server = LitServer(
api,
middlewares=[
(CORSMiddleware, {"allow_origins": ["*"]}),
# Add more middleware as needed
]
)
```
model_metadata:
Metadata about the model displayed at info endpoint. Defaults to None.
Example:
```python
metadata = {
"model_name": "bert-base-uncased",
"version": "1.0.0",
"description": "Text classification model"
}
```
Monitoring & Debugging:
callbacks:
Event handlers for server lifecycle. Defaults to None.
- Built-in callbacks for logging, metrics, custom logic
- Triggers on request start/end, server start/stop
loggers:
Custom loggers for metrics and events. Defaults to None.
- Integrate with monitoring stack
- Track performance metrics, error rates
Advanced Configuration:
max_batch_size, batch_timeout, spec, stream, api_path, loop:
**Deprecated**: Configure these in LitAPI implementation instead.
Migration example:
```python
# Old way (deprecated)
server = LitServer(api, max_batch_size=8, stream=True)
# New way (recommended)
api = MyAPI(max_batch_size=8, stream=True)
server = LitServer(api)
```
Examples:
Basic Usage:
```python
import litserve as ls
class SimpleAPI(ls.LitAPI):
def setup(self, device):
self.model = lambda x: x * 2 # model here
def predict(self, x):
return self.model(x)
server = ls.LitServer(SimpleAPI())
server.run()
```
Production Setup:
```python
server = ls.LitServer(
MyAPI(max_batch_size=8),
accelerator="cuda",
devices=2,
workers_per_device=4,
fast_queue=True,
track_requests=True,
max_payload_size="50MB",
timeout=60
)
server.run(port=8000, num_api_servers=4)
```
Multi-Model Serving:
```python
# Serve multiple models on different endpoints
text_api = TextClassifierAPI(api_path="/classify")
image_api = ImageClassifierAPI(api_path="/vision")
server = ls.LitServer([text_api, image_api])
server.run()
```
Streaming Response:
```python
class StreamingAPI(ls.LitAPI):
def setup(self, device):
self.model = load_llm()
def predict(self, prompt):
for token in self.model.generate(prompt):
yield {"token": token}
server = ls.LitServer(StreamingAPI(stream=True))
```
Per-route using dict
```python
server = ls.LitServer(
[sentiment_api, generate_api],
accelerator="cuda",
devices=[0, 1],
workers_per_device={
"/sentiment": 2, # 2 workers per GPU for sentiment
"/generate": 3, # 3 workers per GPU for generation
},
)
```
Per-api position
```python
server = ls.LitServer(
[sentiment_api, generate_api],
accelerator="cuda",
devices=[0, 1],
workers_per_device=[2, 3], # sentiment then generate (same order as API list)
)
```
Deployment:
Self-hosted:
```bash
python server.py # Run locally
```
Lightning AI Cloud:
```bash
lightning deploy server.py --cloud # One-click deploy
```
See Also:
- LitAPI: Base class for defining model logic
- LitSpec: API specifications (OpenAI compatibility)
- Documentation: https://lightning.ai/docs/litserve
"""
def __init__(
self,
lit_api: Union[LitAPI, list[LitAPI]],
accelerator: Literal["cpu", "cuda", "mps", "auto"] = "auto",
devices: Union[int, Literal["auto"]] = "auto",
workers_per_device: int = 1,
timeout: Union[float, bool] = 30,
healthcheck_path: str = "/health",
info_path: str = "/info",
shutdown_path: str = "/shutdown",
enable_shutdown_api: bool = False,
model_metadata: Optional[dict] = None,
spec: Optional[LitSpec] = None,
max_payload_size=None,
track_requests: bool = False,
callbacks: Optional[Union[list[Callback], Callback]] = None,
middlewares: Optional[list[Union[Callable, tuple[Callable, dict]]]] = None,
loggers: Optional[Union[Logger, list[Logger]]] = None,
fast_queue: bool = False,
disable_openapi_url: bool = False,
# All the following arguments are deprecated and will be removed in v0.3.0
max_batch_size: Optional[int] = None,
batch_timeout: float = 0.0,
stream: bool = False,
api_path: Optional[str] = None,
loop: Optional[Union[str, LitLoop]] = None,
restart_workers: bool = False,
):
if max_batch_size is not None:
warnings.warn(
"'max_batch_size' and 'batch_timeout' are being deprecated in `LitServer` "
"and will be removed in version v0.3.0.\n\n"
"Please update your code to pass these arguments to `LitAPI` instead.\n\n"
"Old usage:\n"
" server = LitServer(api, max_batch_size=N, batch_timeout=T, ...)\n\n"
"New usage:\n"
" api = LitAPI(max_batch_size=N, batch_timeout=T, ...)\n"
" server = LitServer(api, ...)",
DeprecationWarning,
stacklevel=2,
)
lit_api.max_batch_size = max_batch_size
lit_api.batch_timeout = batch_timeout
if middlewares is None:
middlewares = []
if not isinstance(middlewares, list):
_msg = (
"middlewares must be a list of tuples"
" where each tuple contains a middleware and its arguments. For example:\n"
"server = ls.LitServer(ls.test_examples.SimpleLitAPI(), "
'middlewares=[(RequestIdMiddleware, {"length": 5})])'
)
raise ValueError(_msg)
# Handle 0.3.0 migration
if api_path is not None:
_migration_warning("api_path")
lit_api.api_path = api_path
if stream is True:
_migration_warning("stream")
lit_api.stream = stream
if isinstance(loop, LitLoop):
_migration_warning("loop")
lit_api.loop = loop
if isinstance(spec, LitSpec):
_migration_warning("spec")
lit_api.spec = spec
lit_api.stream = spec.stream
# pre setup
self.litapi_connector = _LitAPIConnector(lit_api)
self.litapi_connector.pre_setup()
if api_path and not api_path.startswith("/"):
raise ValueError(
"api_path must start with '/'. "
"Please provide a valid api path like '/predict', '/classify', or '/v1/predict'"
)
if not healthcheck_path.startswith("/"):
raise ValueError(
"healthcheck_path must start with '/'. "
"Please provide a valid api path like '/health', '/healthcheck', or '/v1/health'"
)
if not info_path.startswith("/"):
raise ValueError(
"info_path must start with '/'. Please provide a valid api path like '/info', '/details', or '/v1/info'"
)
if enable_shutdown_api and not shutdown_path.startswith("/"):
raise ValueError("shutdown_path must start with '/'. Please provide a valid api path like '/shutdown'")
global SHUTDOWN_API_KEY
if enable_shutdown_api and not SHUTDOWN_API_KEY:
SHUTDOWN_API_KEY = secrets.token_urlsafe(32)
logger.warning(
"LitServe's Shutdown API is enabled, but the `LIT_SHUTDOWN_API_KEY` environment variable is missing."
f"Generated shutdown API key: {SHUTDOWN_API_KEY}"
)
if enable_shutdown_api:
curl_command = (
"curl -X 'POST' 'http://localhost:8000/shutdown' "
"-H 'accept: application/json' "
f"-H 'Authorization: Bearer {SHUTDOWN_API_KEY}' "
"-d ''"
)
logger.info(f"To shutdown the server, run command: \n{curl_command}\n")
try:
json.dumps(model_metadata)
except (TypeError, ValueError):
raise ValueError("model_metadata must be JSON serializable.")
if sys.platform == "win32" and fast_queue:
warnings.warn("ZMQ is not supported on Windows with LitServe. Disabling ZMQ.")
fast_queue = False
self.healthcheck_path = healthcheck_path
self.info_path = info_path
self._shutdown_path = shutdown_path
self.track_requests = track_requests
self.timeout = timeout
self.litapi_connector.set_request_timeout(timeout)
self.app = FastAPI(lifespan=self.lifespan, openapi_url="" if disable_openapi_url else "/openapi.json")
self._disable_openapi_url = disable_openapi_url
self.app.response_queue_id = None
self.response_buffer: dict[str, ResponseBufferItem] = {}
# gzip does not play nicely with streaming, see https://github.com/tiangolo/fastapi/discussions/8448
if not self.litapi_connector.any_stream():
middlewares.append((GZipMiddleware, {"minimum_size": 1000}))
if max_payload_size is not None:
middlewares.append((MaxSizeMiddleware, {"max_size": max_payload_size}))
self.active_counters: list[mp.Value] = []
self.middlewares = middlewares
self._logger_connector = _LoggerConnector(self, loggers)
self.logger_queue = None
self.lit_api = lit_api
self.enable_shutdown_api = enable_shutdown_api
self.workers_per_device = workers_per_device
self._workers_per_device_by_api_path = self._resolve_workers_per_device_config(workers_per_device)
self.max_payload_size = max_payload_size
self.model_metadata = model_metadata
self._connector = _Connector(accelerator=accelerator, devices=devices)
self._callback_runner = CallbackRunner(callbacks)
self.use_zmq = fast_queue
self.transport_config = None
self.litapi_request_queues = {}
self._shutdown_event: Optional[mp.Event] = None
self.uvicorn_graceful_timeout = 30
self.restart_workers = restart_workers or False
self.monitor_internal = 2
self.mcp_server = None
self._monitor_workers = True
accelerator = self._connector.accelerator
devices = self._connector.devices
if accelerator == "cpu":
self.devices = [accelerator]
elif accelerator in ["cuda", "mps"]:
device_list = devices
if isinstance(devices, int):
device_list = range(devices)
self.devices = [self.device_identifiers(accelerator, device) for device in device_list]
self.transport_config = TransportConfig(transport_config="zmq" if self.use_zmq else "mp")
self.register_endpoints()
# register middleware
self._register_middleware()
def _inference_workers_config_for_api(self, api_path: str):
wpd = self._workers_per_device_by_api_path[api_path]
return self.devices * wpd
def launch_inference_worker(self, lit_api: LitAPI):
specs = [lit_api.spec] if lit_api.spec else []
for spec in specs:
# Objects of Server class are referenced (not copied)
logging.debug(f"shallow copy for Server is created for for spec {spec}")
server_copy = copy.copy(self)
del server_copy.app, server_copy.transport_config, server_copy.litapi_connector
spec.setup(server_copy)
process_list = []
endpoint = lit_api.api_path.split("/")[-1]
inference_workers_config = self._inference_workers_config_for_api(lit_api.api_path)
for worker_id, device in enumerate(inference_workers_config):
if len(device) == 1:
device = device[0]
self.workers_setup_status[f"{endpoint}_{worker_id}"] = WorkerSetupStatus.STARTING
ctx = mp.get_context("spawn")
process = ctx.Process(
target=inference_worker,
args=(
lit_api,
device,
worker_id,
self._get_request_queue(lit_api.api_path),
self._transport,
self.workers_setup_status,
self._callback_runner,
self.restart_workers,
),
name="inference-worker",
)
process.start()
process_list.append(process)
return process_list
def launch_single_inference_worker(self, lit_api: LitAPI, worker_id: int):
specs = [lit_api.spec] if lit_api.spec else []
for spec in specs:
# Objects of Server class are referenced (not copied)
logging.debug(f"shallow copy for Server is created for for spec {spec}")
server_copy = copy.copy(self)
del server_copy.app, server_copy.transport_config, server_copy.litapi_connector
spec.setup(server_copy)
inference_workers_config = self._inference_workers_config_for_api(lit_api.api_path)
device = inference_workers_config[worker_id]
endpoint = lit_api.api_path.split("/")[-1]
if len(device) == 1:
device = device[0]
self.workers_setup_status[f"{endpoint}_{worker_id}"] = WorkerSetupStatus.STARTING
ctx = mp.get_context("spawn")
process = ctx.Process(
target=inference_worker,
args=(
lit_api,
device,
worker_id,
self._get_request_queue(lit_api.api_path),
self._transport,
self.workers_setup_status,
self._callback_runner,
self.restart_workers,
),
name="inference-worker",
)
process.start()
return process
@asynccontextmanager
async def lifespan(self, app: FastAPI):
loop = asyncio.get_running_loop()
if not hasattr(self, "_transport") or not self._transport:
raise RuntimeError(
"Response queues have not been initialized. "
"Please make sure to call the 'launch_inference_workers' method of "
"the LitServer class to initialize the response queues."
)
transport = self._transport
future = response_queue_to_buffer(
transport,
self.response_buffer,
app.response_queue_id,
self.litapi_connector,
)
task = loop.create_task(future, name=f"response_queue_to_buffer-{app.response_queue_id}")
task.add_done_callback(
lambda _: logger.debug(f"Response queue to buffer task terminated for consumer_id {app.response_queue_id}")
)
try:
if _MCP_AVAILABLE:
async with self.mcp_server.lifespan(app):
yield
else:
yield
finally:
self._callback_runner.trigger_event(EventTypes.ON_SERVER_END.value, litserver=self)
# Cancel the task
task.cancel()
with contextlib.suppress(asyncio.CancelledError, asyncio.TimeoutError, Exception):
await asyncio.wait_for(task, timeout=1.0)
def device_identifiers(self, accelerator, device):
if isinstance(device, Sequence):
return [f"{accelerator}:{el}" for el in device]
return [f"{accelerator}:{device}"]
@staticmethod
async def data_streamer(q: deque, data_available: asyncio.Event, send_status: bool = False):
while True: