service.py 19.2 KB
Newer Older
gaclove's avatar
gaclove committed
1
2
import asyncio
import threading
PengGao's avatar
PengGao committed
3
4
5
6
7
8
9
10
11
12
13
import time
import uuid
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse

import httpx
import torch.multiprocessing as mp
from loguru import logger

from ..infer import init_runner
PengGao's avatar
PengGao committed
14
from ..utils.set_config import set_config
gaclove's avatar
gaclove committed
15
from .config import server_config
PengGao's avatar
PengGao committed
16
from .distributed_utils import create_distributed_worker
gaclove's avatar
gaclove committed
17
from .image_utils import is_base64_image, save_base64_image
PengGao's avatar
PengGao committed
18
from .schema import TaskRequest, TaskResponse
PengGao's avatar
PengGao committed
19
20
21
22
23
24
25
26
27
28
29

mp.set_start_method("spawn", force=True)


class FileService:
    def __init__(self, cache_dir: Path):
        self.cache_dir = cache_dir
        self.input_image_dir = cache_dir / "inputs" / "imgs"
        self.input_audio_dir = cache_dir / "inputs" / "audios"
        self.output_video_dir = cache_dir / "outputs"

gaclove's avatar
gaclove committed
30
31
32
33
34
35
36
        self._http_client = None
        self._client_lock = asyncio.Lock()

        self.max_retries = 3
        self.retry_delay = 1.0
        self.max_retry_delay = 10.0

PengGao's avatar
PengGao committed
37
38
39
40
41
42
43
        for directory in [
            self.input_image_dir,
            self.output_video_dir,
            self.input_audio_dir,
        ]:
            directory.mkdir(parents=True, exist_ok=True)

gaclove's avatar
gaclove committed
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
    async def _get_http_client(self) -> httpx.AsyncClient:
        """Get or create a persistent HTTP client with connection pooling."""
        async with self._client_lock:
            if self._http_client is None or self._http_client.is_closed:
                timeout = httpx.Timeout(
                    connect=10.0,
                    read=30.0,
                    write=10.0,
                    pool=5.0,
                )
                limits = httpx.Limits(max_keepalive_connections=5, max_connections=10, keepalive_expiry=30.0)
                self._http_client = httpx.AsyncClient(verify=False, timeout=timeout, limits=limits, follow_redirects=True)
            return self._http_client

    async def _download_with_retry(self, url: str, max_retries: Optional[int] = None) -> httpx.Response:
        """Download with exponential backoff retry logic."""
        if max_retries is None:
            max_retries = self.max_retries

        last_exception = None

        retry_delay = self.retry_delay

        for attempt in range(max_retries):
            try:
                client = await self._get_http_client()
                response = await client.get(url)

                if response.status_code == 200:
                    return response
                elif response.status_code >= 500:
                    logger.warning(f"Server error {response.status_code} for {url}, attempt {attempt + 1}/{max_retries}")
                    last_exception = httpx.HTTPStatusError(f"Server returned {response.status_code}", request=response.request, response=response)
                else:
                    raise httpx.HTTPStatusError(f"Client error {response.status_code}", request=response.request, response=response)

            except (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) as e:
                logger.warning(f"Connection error for {url}, attempt {attempt + 1}/{max_retries}: {str(e)}")
                last_exception = e
            except httpx.HTTPStatusError as e:
                if e.response and e.response.status_code < 500:
                    raise
                last_exception = e
            except Exception as e:
                logger.error(f"Unexpected error downloading {url}: {str(e)}")
                last_exception = e

            if attempt < max_retries - 1:
                await asyncio.sleep(retry_delay)
                retry_delay = min(retry_delay * 2, self.max_retry_delay)

        error_msg = f"All {max_retries} connection attempts failed for {url}"
        if last_exception:
            error_msg += f": {str(last_exception)}"
        raise httpx.ConnectError(error_msg)

PengGao's avatar
PengGao committed
100
    async def download_image(self, image_url: str) -> Path:
gaclove's avatar
gaclove committed
101
        """Download image with retry logic and proper error handling."""
PengGao's avatar
PengGao committed
102
        try:
gaclove's avatar
gaclove committed
103
104
105
            parsed_url = urlparse(image_url)
            if not parsed_url.scheme or not parsed_url.netloc:
                raise ValueError(f"Invalid URL format: {image_url}")
PengGao's avatar
PengGao committed
106

gaclove's avatar
gaclove committed
107
            response = await self._download_with_retry(image_url)
PengGao's avatar
PengGao committed
108

gaclove's avatar
gaclove committed
109
            image_name = Path(parsed_url.path).name
PengGao's avatar
PengGao committed
110
            if not image_name:
gaclove's avatar
gaclove committed
111
                image_name = f"{uuid.uuid4()}.jpg"
PengGao's avatar
PengGao committed
112
113
114
115
116
117
118

            image_path = self.input_image_dir / image_name
            image_path.parent.mkdir(parents=True, exist_ok=True)

            with open(image_path, "wb") as f:
                f.write(response.content)

gaclove's avatar
gaclove committed
119
            logger.info(f"Successfully downloaded image from {image_url} to {image_path}")
PengGao's avatar
PengGao committed
120
            return image_path
gaclove's avatar
gaclove committed
121
122
123
124
125
126
127
128
129
130
131

        except httpx.ConnectError as e:
            logger.error(f"Connection error downloading image from {image_url}: {str(e)}")
            raise ValueError(f"Failed to connect to {image_url}: {str(e)}")
        except httpx.TimeoutException as e:
            logger.error(f"Timeout downloading image from {image_url}: {str(e)}")
            raise ValueError(f"Download timeout for {image_url}: {str(e)}")
        except httpx.HTTPStatusError as e:
            logger.error(f"HTTP error downloading image from {image_url}: {str(e)}")
            raise ValueError(f"HTTP error for {image_url}: {str(e)}")
        except ValueError as e:
PengGao's avatar
PengGao committed
132
            raise
gaclove's avatar
gaclove committed
133
134
135
        except Exception as e:
            logger.error(f"Unexpected error downloading image from {image_url}: {str(e)}")
            raise ValueError(f"Failed to download image from {image_url}: {str(e)}")
PengGao's avatar
PengGao committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    def save_uploaded_file(self, file_content: bytes, filename: str) -> Path:
        file_extension = Path(filename).suffix
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = self.input_image_dir / unique_filename

        with open(file_path, "wb") as f:
            f.write(file_content)

        return file_path

    def get_output_path(self, save_video_path: str) -> Path:
        video_path = Path(save_video_path)
        if not video_path.is_absolute():
            return self.output_video_dir / save_video_path
        return video_path

gaclove's avatar
gaclove committed
153
154
155
156
157
158
159
    async def cleanup(self):
        """Cleanup resources including HTTP client."""
        async with self._client_lock:
            if self._http_client and not self._http_client.is_closed:
                await self._http_client.aclose()
                self._http_client = None

PengGao's avatar
PengGao committed
160

gaclove's avatar
gaclove committed
161
def _distributed_inference_worker(rank, world_size, master_addr, master_port, args, shared_data, task_event, result_event):
PengGao's avatar
PengGao committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    task_data = None
    worker = None

    try:
        logger.info(f"Process {rank}/{world_size - 1} initializing distributed inference service...")

        worker = create_distributed_worker(rank, world_size, master_addr, master_port)
        if not worker.init():
            raise RuntimeError(f"Rank {rank} distributed environment initialization failed")

        config = set_config(args)
        logger.info(f"Rank {rank} config: {config}")

        runner = init_runner(config)
        logger.info(f"Process {rank}/{world_size - 1} distributed inference service initialization completed")

        while True:
gaclove's avatar
gaclove committed
179
180
            task_event.wait(timeout=1.0)

PengGao's avatar
PengGao committed
181
            if rank == 0:
gaclove's avatar
gaclove committed
182
183
184
185
186
187
188
                if shared_data.get("stop", False):
                    logger.info(f"Process {rank} received stop signal, exiting inference service")
                    worker.dist_manager.broadcast_task_data(None)
                    break

                task_data = shared_data.get("current_task")
                if task_data:
PengGao's avatar
PengGao committed
189
                    worker.dist_manager.broadcast_task_data(task_data)
gaclove's avatar
gaclove committed
190
                else:
PengGao's avatar
PengGao committed
191
192
193
                    continue
            else:
                task_data = worker.dist_manager.broadcast_task_data()
gaclove's avatar
gaclove committed
194
                if task_data is None:
PengGao's avatar
PengGao committed
195
196
197
198
199
200
201
202
                    logger.info(f"Process {rank} received stop signal, exiting inference service")
                    break

            if task_data is not None:
                logger.info(f"Process {rank} received inference task: {task_data['task_id']}")

                try:
                    runner.set_inputs(task_data)  # type: ignore
203
                    runner.run_pipeline()
PengGao's avatar
PengGao committed
204

gaclove's avatar
gaclove committed
205
206
207
208
209
210
211
212
213
214
215
216
217
                    worker.dist_manager.barrier()

                    if rank == 0:
                        # Only rank 0 updates the result
                        shared_data["result"] = {
                            "task_id": task_data["task_id"],
                            "status": "success",
                            "save_video_path": task_data.get("video_path", task_data["save_video_path"]),  # Return original path for API
                            "message": "Inference completed",
                        }
                        result_event.set()
                        logger.info(f"Task {task_data['task_id']} success")

PengGao's avatar
PengGao committed
218
219
220
                except Exception as e:
                    logger.error(f"Process {rank} error occurred while processing task: {str(e)}")

gaclove's avatar
gaclove committed
221
222
223
224
225
226
227
228
229
230
231
232
                    worker.dist_manager.barrier()

                    if rank == 0:
                        # Only rank 0 updates the result
                        shared_data["result"] = {
                            "task_id": task_data.get("task_id", "unknown"),
                            "status": "failed",
                            "error": str(e),
                            "message": f"Inference failed: {str(e)}",
                        }
                        result_event.set()
                        logger.info(f"Task {task_data.get('task_id', 'unknown')} failed")
PengGao's avatar
PengGao committed
233
234
235
236

    except KeyboardInterrupt:
        logger.info(f"Process {rank} received KeyboardInterrupt, gracefully exiting")
    except Exception as e:
gaclove's avatar
gaclove committed
237
        logger.exception(f"Distributed inference service process {rank} startup failed: {str(e)}")
PengGao's avatar
PengGao committed
238
        if rank == 0:
gaclove's avatar
gaclove committed
239
            shared_data["result"] = {
PengGao's avatar
PengGao committed
240
241
242
243
244
                "task_id": "startup",
                "status": "startup_failed",
                "error": str(e),
                "message": f"Inference service startup failed: {str(e)}",
            }
gaclove's avatar
gaclove committed
245
            result_event.set()
PengGao's avatar
PengGao committed
246
247
248
249
    finally:
        try:
            if worker:
                worker.cleanup()
gaclove's avatar
gaclove committed
250
251
        except Exception as e:
            logger.debug(f"Error cleaning up worker for rank {rank}: {e}")
PengGao's avatar
PengGao committed
252
253
254
255


class DistributedInferenceService:
    def __init__(self):
gaclove's avatar
gaclove committed
256
257
258
259
        self.manager = None
        self.shared_data = None
        self.task_event = None
        self.result_event = None
PengGao's avatar
PengGao committed
260
261
262
263
        self.processes = []
        self.is_running = False

    def start_distributed_inference(self, args) -> bool:
264
265
266
267
268
269
        if hasattr(args, "lora_path") and args.lora_path:
            args.lora_configs = [{"path": args.lora_path, "strength": getattr(args, "lora_strength", 1.0)}]
            delattr(args, "lora_path")
            if hasattr(args, "lora_strength"):
                delattr(args, "lora_strength")

270
        self.args = args
PengGao's avatar
PengGao committed
271
272
273
274
275
276
277
278
279
280
        if self.is_running:
            logger.warning("Distributed inference service is already running")
            return True

        nproc_per_node = args.nproc_per_node
        if nproc_per_node <= 0:
            logger.error("nproc_per_node must be greater than 0")
            return False

        try:
gaclove's avatar
gaclove committed
281
282
            master_addr = server_config.master_addr
            master_port = server_config.find_free_master_port()
PengGao's avatar
PengGao committed
283
284
            logger.info(f"Distributed inference service Master Addr: {master_addr}, Master Port: {master_port}")

gaclove's avatar
gaclove committed
285
286
287
288
289
290
291
292
293
294
            # Create shared data structures
            self.manager = mp.Manager()
            self.shared_data = self.manager.dict()
            self.task_event = self.manager.Event()
            self.result_event = self.manager.Event()

            # Initialize shared data
            self.shared_data["current_task"] = None
            self.shared_data["result"] = None
            self.shared_data["stop"] = False
PengGao's avatar
PengGao committed
295
296
297
298
299
300
301
302
303
304

            for rank in range(nproc_per_node):
                p = mp.Process(
                    target=_distributed_inference_worker,
                    args=(
                        rank,
                        nproc_per_node,
                        master_addr,
                        master_port,
                        args,
gaclove's avatar
gaclove committed
305
306
307
                        self.shared_data,
                        self.task_event,
                        self.result_event,
PengGao's avatar
PengGao committed
308
                    ),
gaclove's avatar
gaclove committed
309
                    daemon=False,  # Changed to False for proper cleanup
PengGao's avatar
PengGao committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
                )
                p.start()
                self.processes.append(p)

            self.is_running = True
            logger.info(f"Distributed inference service started successfully with {nproc_per_node} processes")
            return True

        except Exception as e:
            logger.exception(f"Error occurred while starting distributed inference service: {str(e)}")
            self.stop_distributed_inference()
            return False

    def stop_distributed_inference(self):
gaclove's avatar
gaclove committed
324
325
326
        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

PengGao's avatar
PengGao committed
327
328
329
330
331
332
        if not self.is_running:
            return

        try:
            logger.info(f"Stopping {len(self.processes)} distributed inference service processes...")

gaclove's avatar
gaclove committed
333
334
335
            if self.shared_data is not None:
                self.shared_data["stop"] = True
                self.task_event.set()
PengGao's avatar
PengGao committed
336
337
338
339
340
341
342
343

            for p in self.processes:
                try:
                    p.join(timeout=10)
                    if p.is_alive():
                        logger.warning(f"Process {p.pid} did not end within the specified time, forcing termination...")
                        p.terminate()
                        p.join(timeout=5)
gaclove's avatar
gaclove committed
344
345
                except Exception as e:
                    logger.warning(f"Error terminating process {p.pid}: {e}")
PengGao's avatar
PengGao committed
346
347
348
349
350
351
352
353

            logger.info("All distributed inference service processes have stopped")

        except Exception as e:
            logger.error(f"Error occurred while stopping distributed inference service: {str(e)}")
        finally:
            # Clean up resources
            self.processes = []
gaclove's avatar
gaclove committed
354
355
356
357
            self.manager = None
            self.shared_data = None
            self.task_event = None
            self.result_event = None
PengGao's avatar
PengGao committed
358
359
360
            self.is_running = False

    def submit_task(self, task_data: dict) -> bool:
gaclove's avatar
gaclove committed
361
362
363
364
        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

        if not self.is_running or not self.shared_data:
PengGao's avatar
PengGao committed
365
366
367
368
            logger.error("Distributed inference service is not started")
            return False

        try:
gaclove's avatar
gaclove committed
369
370
371
372
373
374
            self.result_event.clear()
            self.shared_data["result"] = None

            self.shared_data["current_task"] = task_data
            self.task_event.set()  # Signal workers

PengGao's avatar
PengGao committed
375
376
377
378
379
            return True
        except Exception as e:
            logger.error(f"Failed to submit task: {str(e)}")
            return False

gaclove's avatar
gaclove committed
380
381
382
383
384
385
386
    def wait_for_result(self, task_id: str, timeout: Optional[int] = None) -> Optional[dict]:
        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

        if timeout is None:
            timeout = server_config.task_timeout
        if not self.is_running or not self.shared_data:
PengGao's avatar
PengGao committed
387
388
            return None

gaclove's avatar
gaclove committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        if self.result_event.wait(timeout=timeout):
            result = self.shared_data.get("result")
            if result and result.get("task_id") == task_id:
                self.shared_data["current_task"] = None
                self.task_event.clear()
                return result

        return None

    def wait_for_result_with_stop(self, task_id: str, stop_event: threading.Event, timeout: Optional[int] = None) -> Optional[dict]:
        if timeout is None:
            timeout = server_config.task_timeout

        if not self.is_running or not self.shared_data:
            return None

        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

PengGao's avatar
PengGao committed
408
409
410
        start_time = time.time()

        while time.time() - start_time < timeout:
gaclove's avatar
gaclove committed
411
412
413
414
415
416
417
418
419
420
421
            if stop_event.is_set():
                logger.info(f"Task {task_id} stop event triggered during wait")
                self.shared_data["current_task"] = None
                self.task_event.clear()
                return None

            if self.result_event.wait(timeout=0.5):
                result = self.shared_data.get("result")
                if result and result.get("task_id") == task_id:
                    self.shared_data["current_task"] = None
                    self.task_event.clear()
PengGao's avatar
PengGao committed
422
423
424
425
                    return result

        return None

426
427
428
429
    def server_metadata(self):
        assert hasattr(self, "args"), "Distributed inference service has not been started. Call start_distributed_inference() first."
        return {"nproc_per_node": self.args.nproc_per_node, "model_cls": self.args.model_cls, "model_path": self.args.model_path}

PengGao's avatar
PengGao committed
430
431
432
433
434
435

class VideoGenerationService:
    def __init__(self, file_service: FileService, inference_service: DistributedInferenceService):
        self.file_service = file_service
        self.inference_service = inference_service

gaclove's avatar
gaclove committed
436
    async def generate_video_with_stop_event(self, message: TaskRequest, stop_event) -> Optional[TaskResponse]:
PengGao's avatar
PengGao committed
437
        try:
438
439
            task_data = {field: getattr(message, field) for field in message.model_fields_set if field != "task_id"}
            task_data["task_id"] = message.task_id
PengGao's avatar
PengGao committed
440

gaclove's avatar
gaclove committed
441
442
443
444
445
446
447
448
449
450
451
452
453
            if stop_event.is_set():
                logger.info(f"Task {message.task_id} cancelled before processing")
                return None

            if "image_path" in message.model_fields_set and message.image_path:
                if message.image_path.startswith("http"):
                    image_path = await self.file_service.download_image(message.image_path)
                    task_data["image_path"] = str(image_path)
                elif is_base64_image(message.image_path):
                    image_path = save_base64_image(message.image_path, str(self.file_service.input_image_dir))
                    task_data["image_path"] = str(image_path)
                else:
                    task_data["image_path"] = message.image_path
PengGao's avatar
PengGao committed
454

gaclove's avatar
gaclove committed
455
456
457
            actual_save_path = self.file_service.get_output_path(message.save_video_path)
            task_data["save_video_path"] = str(actual_save_path)
            task_data["video_path"] = message.save_video_path
PengGao's avatar
PengGao committed
458
459
460
461

            if not self.inference_service.submit_task(task_data):
                raise RuntimeError("Distributed inference service is not started")

gaclove's avatar
gaclove committed
462
            result = self.inference_service.wait_for_result_with_stop(message.task_id, stop_event, timeout=300)
PengGao's avatar
PengGao committed
463
464

            if result is None:
gaclove's avatar
gaclove committed
465
466
467
                if stop_event.is_set():
                    logger.info(f"Task {message.task_id} cancelled during processing")
                    return None
PengGao's avatar
PengGao committed
468
469
470
471
472
473
                raise RuntimeError("Task processing timeout")

            if result.get("status") == "success":
                return TaskResponse(
                    task_id=message.task_id,
                    task_status="completed",
gaclove's avatar
gaclove committed
474
                    save_video_path=message.save_video_path,  # Return original path
PengGao's avatar
PengGao committed
475
476
477
478
479
480
481
482
                )
            else:
                error_msg = result.get("error", "Inference failed")
                raise RuntimeError(error_msg)

        except Exception as e:
            logger.error(f"Task {message.task_id} processing failed: {str(e)}")
            raise