🛠️ 技術框架與設計模式
🐍 Python 3.10+
核心開發語言,支援類型提示和現代 Python 特性
🔥 PyTorch 2.7
深度學習框架,提供 GPU 加速和模型推理支援
🤗 Diffusers
HuggingFace 的擴散模型庫,支援多種 Stable Diffusion 變體
⚡ FastAPI
高性能異步 Web 框架,提供 REST API 和 WebSocket 支援
⚛️ React
前端框架,構建互動式 UI 和節點編輯器
🗄️ SQLite/PostgreSQL
資料庫系統,儲存工作流、圖像元數據和用戶資料
核心設計模式
🎯 Service Locator Pattern - 依賴注入服務管理
InvokeAI 使用 Service Locator Pattern 管理複雜的服務依賴關係。InvocationServices 類作為中央服務定位器,提供所有服務的統一訪問接口,避免了服務之間的直接耦合。
主要優勢:
集中管理所有服務依賴
簡化服務之間的交互
便於測試和模擬
支援運行時服務替換
🔧 服務定位器實作
class InvocationServices :
"""Services that can be used by invocations"""
def __init__ (self ,
board_images: "BoardImagesServiceABC" ,
boards: "BoardServiceABC" ,
configuration: "InvokeAIAppConfig" ,
events: "EventServiceBase" ,
images: "ImageServiceABC" ,
model_manager: "ModelManagerServiceBase" ,
session_queue: "SessionQueueBase" ,
):
self .board_images = board_images
self .boards = boards
self .configuration = configuration
self .events = events
self .images = images
self .model_manager = model_manager
self .session_queue = session_queue
這個服務定位器模式讓每個 Invocation 都能輕鬆訪問所需的服務,而無需知道服務的具體實現細節。
Service Locator Pattern 類別圖
+
−
⌂
InvocationServices
+ board_images
+ model_manager
+ session_queue
BaseInvocation
+ invoke(context)
«interface»
ImageServiceABC
+ create_image()
«interface»
ModelManagerServiceBase
+ load_model()
«interface»
SessionQueueBase
+ enqueue()
ImageServiceDefault
+ create_image()
ModelManagerDefault
+ load_model()
SessionQueueSQLite
+ enqueue()
UML 關係圖例:
實線 + 空心三角形 = 繼承關係 (Inheritance)
實線 = 關聯關係 (Association)
實線 + 空心菱形 = 聚合關係 (Aggregation)
實線 + 實心菱形 = 組合關係 (Composition)
虛線 + 箭頭 = 依賴關係 (Dependency)
虛線 + 空心三角形 = 實現關係 (Realization)
類別顏色編碼:
Service Locator (藍色) - 服務定位器
Interface (紅色) - 服務介面
Service (綠色) - 具體服務實作
※ 根據 UML 標準,class diagram 共有以上 6 種關係線類型
🔄 Graph-based Workflow Pattern - 節點化工作流引擎
InvokeAI 創新性地使用有向無環圖(DAG)來表示和執行複雜的圖像生成工作流。每個節點代表一個特定的操作(Invocation),邊則表示數據流向。
主要優勢:
視覺化的工作流設計
靈活的節點組合
自動依賴解析
支援並行執行
🔧 工作流圖實作
class Edge (BaseModel):
source: EdgeConnection = Field(description="The connection for the edge's from node and field" )
destination: EdgeConnection = Field(description="The connection for the edge's to node and field" )
class Graph (BaseModel):
id: str = Field(description="The id of this graph" )
nodes: dict[str, BaseInvocation] = Field(description="The nodes in this graph" )
edges: list[Edge] = Field(description="The edges in this graph" )
def execute (self , context: InvocationContext) -> Iterator[BaseInvocationOutput]:
g = nx.DiGraph()
g.add_edges_from([(e.source.node_id, e.destination.node_id) for e in self .edges])
for node_id in nx.topological_sort(g):
node = self .nodes[node_id]
output = node.invoke(context)
yield output
Graph-based Workflow Pattern 類別圖
+
−
⌂
Graph
+ id: str
+ nodes: dict[str, BaseInvocation]
+ edges: list[Edge]
+ execute(context)
BaseInvocation
+ id: str
+ type: str
+ invoke(context)
Edge
+ source: EdgeConnection
+ destination: EdgeConnection
GraphExecutor
+ topological_sort()
+ validate_graph()
+ run_node()
EdgeConnection
+ node_id: str
+ field: str
UML 關係圖例:
實線 + 實心菱形 = 組合關係 (Composition)
虛線 + 箭頭 = 依賴關係 (Dependency)
虛線 + 空心三角形 = 實現關係 (Realization)
實線 + 空心三角形 = 繼承關係 (Inheritance)
實線 = 關聯關係 (Association)
實線 + 空心菱形 = 聚合關係 (Aggregation)
※ 根據 UML 標準,class diagram 共有以上 6 種關係線類型
💾 Model Cache Pattern - 智能模型快取管理
InvokeAI 實現了一個雙層快取系統,智能管理模型在 GPU/CPU 記憶體之間的移動,最大化硬體使用效率。這個模式特別適合處理大型 AI 模型的記憶體限制問題。
主要優勢:
自動記憶體管理
智能模型調度
減少載入時間
支援多模型並行
🔧 模型快取實作
class ModelCache :
"""A cache for managing models in memory.
The cache is based on two levels of model storage:
- execution_device: The device where models are executed (typically "cuda", "mps", or "cpu").
- storage_device: The device where models are offloaded when not in active use (typically "cpu").
"""
def __init__ (self , max_cache_size: int, execution_device: torch.device):
self ._max_cache_size = max_cache_size
self ._execution_device = execution_device
self ._storage_device = torch.device("cpu" )
self ._cache_records: Dict[str, CacheRecord] = {}
self ._lock = threading.Lock()
@synchronized
def get_model (self , model_key: str) -> CacheRecord:
if model_key in self ._cache_records:
self ._move_to_execution_device(model_key)
return self ._cache_records[model_key]
self ._make_room_for_model(model_size)
loaded_model = self ._load_model_from_disk(model_key)
self ._cache_records[model_key] = CacheRecord(loaded_model)
return self ._cache_records[model_key]
Model Cache Pattern 類別圖
+
−
⌂
ModelCache
- _cache_records: Dict
- _max_cache_size: int
- _lock: Lock
+ get_model(key)
+ _make_room_for_model()
CacheRecord
+ cache_key: str
+ total_bytes: int
+ current_device: Device
+ cached_model: Model
LoadedModelWithoutConfig
- _cache_record: CacheRecord
- _cache: ModelCache
+ model_on_device()
+ __enter__()
ModelLoader
+ load_from_disk()
+ get_model_size()
+ validate_model()
UML 關係圖例:
實線 + 空心三角形 = 繼承關係 (Inheritance)
實線 = 關聯關係 (Association)
實線 + 空心菱形 = 聚合關係 (Aggregation)
實線 + 實心菱形 = 組合關係 (Composition)
虛線 + 箭頭 = 依賴關係 (Dependency)
虛線 + 空心三角形 = 實現關係 (Realization)
Model Cache Pattern 說明:
此圖展示 ModelCache 如何管理模型載入、快取記錄和記憶體調度的關係
※ 根據 UML 標準,class diagram 共有以上 6 種關係線類型
🔌 Extension System Pattern - 插件式擴展架構
InvokeAI 使用擴展系統模式來處理各種模型增強功能(如 ControlNet、LoRA、IP-Adapter)。這種設計讓系統能夠靈活地添加新功能而不影響核心邏輯。
主要優勢:
模組化設計
易於擴展新功能
解耦核心與擴展
支援動態載入
🔧 擴展系統實作
class ExtensionsManager :
def __init__ (self , is_canceled: Callable[[], bool]):
self ._is_canceled = is_canceled
self ._extensions: List[ExtensionBase] = []
self ._ordered_callbacks: Dict[ExtensionCallbackType, List[CallbackFunctionWithMetadata]] = {}
def add_extension (self , extension: ExtensionBase):
"""Register an extension and its callbacks."""
self ._extensions.append(extension)
for callback_type in ExtensionCallbackType:
if hasattr(extension, callback_type.value):
callback_fn = getattr(extension, callback_type.value)
self ._register_callback(callback_type, callback_fn, extension.priority)
def run_callback (self , callback_type: ExtensionCallbackType, ctx: DenoiseContext):
"""Execute all registered callbacks for a given type."""
for callback in self ._ordered_callbacks.get(callback_type, []):
if self ._is_canceled():
break
callback.function(ctx)
Extension System Pattern 類別圖
+
−
⌂
ExtensionsManager
- _extensions: List[ExtensionBase]
- _callbacks: Dict
+ add_extension()
+ run_callback()
«abstract»
ExtensionBase
+ priority: int
+ setup(context)
ControlNetExt
+ pre_denoise()
+ post_denoise()
LoRAExt
+ patch_model()
+ unpatch_model()
T2IAdapterExt
+ setup_adapter()
+ cleanup_adapter()
FreeUExt
+ modify_unet()
+ restore_unet()
InpaintExt
+ apply_mask()
+ blend_latents()
«enum»
ExtensionCallbackType
PRE_DENOISE
POST_DENOISE
UML 關係圖例:
實線 + 空心三角形 = 繼承關係 (Inheritance)
實線 = 關聯關係 (Association)
實線 + 空心菱形 = 聚合關係 (Aggregation)
實線 + 實心菱形 = 組合關係 (Composition)
虛線 + 箭頭 = 依賴關係 (Dependency)
虛線 + 空心三角形 = 實現關係 (Realization)
Extension System Pattern 說明:
此圖展示 ExtensionsManager 如何管理各種擴展的生命週期和回調執行
※ 根據 UML 標準,class diagram 共有以上 6 種關係線類型
🔄 Adapter Pattern - 多模型統一介面
InvokeAI 使用 Adapter Pattern 來統一不同 AI 模型(SD1.5、SD2.0、SDXL、FLUX)的介面,讓系統能夠無縫支援多種模型架構。
主要優勢:
統一的模型操作介面
簡化模型切換邏輯
易於添加新模型支援
隔離模型特定實現
🔧 模型適配器實作
class StableDiffusionBackend (ABC):
"""Abstract base class for all diffusion model backends."""
@abstractmethod
def denoise (self ,
context: DenoiseContext,
latents: torch.Tensor,
timesteps: List[int],
noise: torch.Tensor) -> torch.Tensor:
"""Run the denoising process."""
pass
class StableDiffusion15Backend (StableDiffusionBackend):
def denoise (self , context, latents, timesteps, noise):
for t in timesteps:
latents = self .unet(latents, t, context.conditioning)
return latents
class SDXLBackend (StableDiffusionBackend):
def denoise (self , context, latents, timesteps, noise):
add_time_ids = self ._get_add_time_ids(context)
for t in timesteps:
latents = self .unet(latents, t, context.conditioning, add_time_ids)
return latents
class FluxBackend (StableDiffusionBackend):
def denoise (self , context, latents, timesteps, noise):
packed_latents = self ._pack_latents(latents)
for t in timesteps:
packed_latents = self .transformer(packed_latents, t, context)
return self ._unpack_latents(packed_latents)
Model Adapter Pattern 類別圖
+
−
⌂
DiffusionPipeline
+ backend: StableDiffusionBackend
+ run(prompt, params)
+ generate_image()
«interface»
StableDiffusionBackend
+ denoise(context, latents)
+ encode_prompt(prompt)
SD15Backend
+ denoise()
- _apply_cfg()
SDXLBackend
+ denoise()
- _get_add_time_ids()
FluxBackend
+ denoise()
- _pack_latents()
SD3Backend
+ denoise()
- _apply_sd3_cfg()
UNet2DConditionModel
+ forward()
SDXLUNet
+ forward()
FluxTransformer
+ forward()
UML 關係圖例:
實線 + 空心三角形 = 繼承關係 (Inheritance)
實線 = 關聯關係 (Association)
實線 + 空心菱形 = 聚合關係 (Aggregation)
實線 + 實心菱形 = 組合關係 (Composition)
虛線 + 箭頭 = 依賴關係 (Dependency)
虛線 + 空心三角形 = 實現關係 (Realization)
Adapter Pattern 說明:
此圖展示 DiffusionPipeline 如何透過統一介面操作不同的模型 Backend
※ 根據 UML 標準,class diagram 共有以上 6 種關係線類型