The issue you're encountering stems from the way shared state is managed between the main process (where FastAPI runs) and the child processes you've spawned using multiprocessing. Specifically, the Manager-created shared variables are not being correctly shared or updated across processes, leading to inconsistencies like the one you're observing.
Root Cause Analysis
-
Initialization of Shared Variables Inside __main__:
- Problem: Shared variables (
Manager().Value, Manager().Queue(), etc.) are initialized inside the __main__ block. However, FastAPI endpoints are defined at the module level and attempt to access these variables. When the module is imported (which happens when Uvicorn runs the FastAPI app), these shared variables are not yet initialized, leading to None or default states in the endpoints.
- Impact: The child processes and the FastAPI endpoints are not referencing the same shared objects, causing discrepancies in shared state updates.
-
Process Isolation:
- Problem: Each child process might be initializing its own
Manager, leading to separate instances of shared variables that aren't synchronized with the main process.
- Impact: Updates made in one process (e.g., setting
task_ImageInterpretationProcess_started.value = True in the FastAPI endpoint) aren't reflected in the child processes because they're referencing different instances of the shared variables.
-
Platform-Specific Behavior:
- Windows vs. Unix-like Systems: On Windows, the
multiprocessing module starts new processes without inheriting the state from the parent process, unlike Unix-like systems where fork is used. This means that without proper initialization, child processes on Windows won't have access to shared variables unless explicitly passed.
Solution
To ensure that all parts of your application correctly share and update the state, follow these steps:
-
Initialize Manager and Shared Variables at the Module Level:
- Move the initialization of the
Manager and all shared variables outside the __main__ block. This ensures that both the FastAPI app and the child processes reference the same shared objects.
-
Ensure Proper Synchronization:
- Use synchronization primitives (like
Lock, Event, etc.) if necessary to prevent race conditions when multiple processes access or modify shared variables.
-
Prevent Recursive Process Creation (Especially on Windows):
- On Windows, ensure that the code that spawns new processes is protected under the
if __name__ == "__main__": guard to prevent recursive spawning when child processes import the main module.
-
Example Refactored Code:
Here's a refactored version of your code that addresses these issues:
from fastapi import FastAPI, Request
import uuid
import requests
import asyncio
import uvicorn
from multiprocessing import Process, Manager, Value
import multiprocessing
import threading
import time
app = FastAPI()
# Initialize Manager and shared variables at the module level
manager = Manager()
# Shared states
ImageInterpretation = manager.Value('b', False)
TranscriptProcessor = manager.Value('b', False)
GenerateLLMResponse = manager.Value('b', False)
Wispper = manager.Value('b', False)
task_GenerateResponseProcess_started = manager.Value('b', False)
task_ImageInterpretationProcess_started = manager.Value('b', False)
# Queues
input_queue_1 = manager.Queue()
input_queue_2 = manager.Queue()
input_queue_3 = manager.Queue()
input_queue_4 = manager.Queue()
output_queue_1 = manager.Queue()
output_queue_2 = manager.Queue()
output_queue_3 = manager.Queue()
output_queue_4 = manager.Queue()
request_queues_1 = manager.dict()
request_queues_2 = manager.dict()
request_queues_3 = manager.dict()
request_queues_4 = manager.dict()
class TranscriptProcessorProcess:
def __init__(self, input_queue, output_queue, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper):
self.input_queue = input_queue
self.output_queue = output_queue
self.ImageInterpretation = ImageInterpretation
self.TranscriptProcessor = TranscriptProcessor
self.GenerateLLMResponse = GenerateLLMResponse
self.Wispper = Wispper
async def get_transcript_youtube(self):
from server_modules.youtube_transcript import get_transcript_from_message
while True:
request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
response = await get_transcript_from_message(message_content)
await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))
def _run(self):
asyncio.run(self.get_transcript_youtube())
class ImageInterpretationProcess:
def __init__(self, input_queue, output_queue, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_ImageInterpretationProcess_started):
self.input_queue = input_queue
self.output_queue = output_queue
self.ImageInterpretation = ImageInterpretation
self.TranscriptProcessor = TranscriptProcessor
self.GenerateLLMResponse = GenerateLLMResponse
self.Wispper = Wispper
self.task_ImageInterpretationProcess_started = task_ImageInterpretationProcess_started
async def Qwen_interpretation(self):
from server_modules.image_interpretation import Qwen_2_VL
while True:
await asyncio.sleep(1) # Prevent CPU overload
# Read shared values
generate_llm_response_value = self.GenerateLLMResponse.value
wispper_value = self.Wispper.value
task_image_interpretation_process_started_value = self.task_ImageInterpretationProcess_started.value
print("-------")
print(f"GenerateLLMResponse: {generate_llm_response_value}")
print(f"Wispper: {wispper_value}")
print(f"task_ImageInterpretationProcess_started: {task_image_interpretation_process_started_value}")
print("-------")
if not generate_llm_response_value and not wispper_value and task_image_interpretation_process_started_value:
print("Condition met for Image Interpretation")
print("Image Interpretation started")
requests.post("http://127.0.0.1:5000/v1/internal/model/unload")
print("Model unloaded for Image Interpretation")
request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
print("Request ID and message content retrieved")
Qwen_2_VL.model_to_gpu()
print("Model moved to GPU for Image Interpretation")
response = await Qwen_2_VL.process_img(message_content)
print("Image processed")
Qwen_2_VL.model_to_cpu()
print("Model moved to CPU")
await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))
print("Response added to output queue")
self.ImageInterpretation.value = False
print("Image Interpretation completed")
data = {"model_name": "c4ai-command-r-08-2024-IQ4_XS.gguf", "args": {}, "settings": {}}
requests.post("http://127.0.0.1:5000/v1/internal/model/load", json=data)
print("Model loaded for next task")
def _run(self):
asyncio.run(self.Qwen_interpretation())
class GenerateResponseProcess:
def __init__(self, input_queue, output_queue, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_GenerateResponseProcess_started):
self.input_queue = input_queue
self.output_queue = output_queue
self.ImageInterpretation = ImageInterpretation
self.TranscriptProcessor = TranscriptProcessor
self.GenerateLLMResponse = GenerateLLMResponse
self.Wispper = Wispper
self.task_GenerateResponseProcess_started = task_GenerateResponseProcess_started
async def Get_LLM_Response(self):
from server_modules.text_web_ui import local_answer
while True:
if not self.ImageInterpretation.value and not self.Wispper.value and self.task_GenerateResponseProcess_started.value:
self.GenerateLLMResponse.value = True
request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
response = await local_answer(message_content)
await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))
self.GenerateLLMResponse.value = False
def _run(self):
asyncio.run(self.Get_LLM_Response())
# Function to process requests
def process_request(request, input_queue, output_queue, request_queues):
request_id = str(uuid.uuid4())
response_queue = manager.Queue() # Use the module-level manager
request_queues[request_id] = response_queue
input_queue.put((request_id, request))
# Wait for the response
response = response_queue.get()
del request_queues[request_id] # Clean up
return {"response": response}
# Function to handle responses
def handle_responses(output_queue, request_queues):
while True:
request_id, response = output_queue.get()
if request_id in request_queues:
request_queues[request_id].put(response)
# Define FastAPI endpoints
@app.post("/get_youtube_transcript")
async def process_request_endpoint_1(request: Request):
data = await request.json()
return process_request(data, input_queue_1, output_queue_1, request_queues_1)
@app.post("/image_interpretation")
async def process_request_endpoint_2(request: Request):
global task_ImageInterpretationProcess_started
print("Received data for image interpretation")
data = await request.json()
# Update the shared state
print(f"Before update: {task_ImageInterpretationProcess_started.value}")
task_ImageInterpretationProcess_started.value = True
print(f"After update: {task_ImageInterpretationProcess_started.value}")
return process_request(data, input_queue_2, output_queue_2, request_queues_2)
@app.post("/generate_LLM_response")
async def process_request_endpoint_3(request: Request):
global task_GenerateResponseProcess_started
task_GenerateResponseProcess_started.value = True
data = await request.json()
return process_request(data, input_queue_3, output_queue_3, request_queues_3)
@app.post("/get_youtube_transcript_4")
async def process_request_endpoint_4(request: Request):
data = await request.json()
return process_request(data, input_queue_4, output_queue_4, request_queues_4)
if __name__ == "__main__":
multiprocessing.freeze_support()
# Create and start processes
processes = []
TPP = Process(target=TranscriptProcessorProcess(
input_queue_1, output_queue_1, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper
)._run)
IIP = Process(target=ImageInterpretationProcess(
input_queue_2, output_queue_2, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_ImageInterpretationProcess_started
)._run)
GRP = Process(target=GenerateResponseProcess(
input_queue_3, output_queue_3, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_GenerateResponseProcess_started
)._run)
processes.extend([TPP, IIP, GRP])
for p in processes:
p.start()
# Start threads to handle responses
threading.Thread(target=handle_responses, args=(output_queue_1, request_queues_1), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_2, request_queues_2), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_3, request_queues_3), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_4, request_queues_4), daemon=True).start()
# Run the FastAPI app
uvicorn.run(app, host="127.0.0.1", port=5100)
# Wait for all processes to finish
for p in processes:
p.join()
Key Changes and Explanations
-
Module-Level Initialization:
- The
Manager and all shared variables (ImageInterpretation, TranscriptProcessor, etc.) are initialized at the top level of the module, ensuring that both the FastAPI app and child processes reference the same shared objects.
-
Consistent Use of Shared Variables:
- All references to shared variables within classes and functions now use the module-level instances, ensuring synchronization across processes.
-
Proper Function Definitions:
- Ensured that methods like
model_to_gpu and model_to_cpu in ImageInterpretationProcess are correctly called (e.g., Qwen_2_VL.model_to_gpu() instead of Qwen_2_VL.model_to_gpu).
-
Process Creation within __main__:
- All process creation and starting are encapsulated within the
if __name__ == "__main__": block to prevent unintended behavior, especially on Windows.
-
Thread Safety:
- Using
daemon=True for response handling threads ensures they don't prevent the program from exiting if the main thread terminates.
-
Enhanced Logging:
- Added more descriptive print statements to better trace the flow of data and state changes.
Additional Recommendations
-
Error Handling: Implement try-except blocks around critical sections, especially where inter-process communication occurs, to handle unexpected errors gracefully.
-
Graceful Shutdown: Ensure that child processes are terminated gracefully when the FastAPI app shuts down. You might consider handling signals or using FastAPI's lifespan events.
-
Performance Considerations: Regularly evaluate the performance impact of using Manager for shared state, as it can introduce overhead. Depending on the use case, other synchronization mechanisms or architectures (like message queues) might be more efficient.
-
Testing: Before deploying, thoroughly test the application in both development and production environments to ensure that shared state behaves as expected across different operating systems.
Conclusion
By initializing shared variables at the module level and ensuring that both the FastAPI app and child processes reference the same Manager-created objects, you ensure consistent and synchronized state across your application. This should resolve the issue where the ImageInterpretationProcess wasn't recognizing the updated task_ImageInterpretationProcess_started value.