diff --git a/src/diffusers/modular_pipelines/modular_pipeline.py b/src/diffusers/modular_pipelines/modular_pipeline.py index dfa700af4765..f0d38c7d7565 100644 --- a/src/diffusers/modular_pipelines/modular_pipeline.py +++ b/src/diffusers/modular_pipelines/modular_pipeline.py @@ -863,6 +863,7 @@ def __call__(self, pipeline, state: PipelineState) -> tuple["ModularPipeline", P logger.info(f"Running block: {block.__class__.__name__}") return block(pipeline, state) except Exception as e: + _add_component_load_error_notes(pipeline, block, e) error_msg = ( f"\nError in block: {block.__class__.__name__}\n" f"Error details: {str(e)}\n" @@ -1223,6 +1224,7 @@ def __call__(self, pipeline, state: PipelineState) -> tuple["ModularPipeline", P try: pipeline, state = block(pipeline, state) except Exception as e: + _add_component_load_error_notes(pipeline, block, e) error_msg = ( f"\nError in block: ({block_name}, {block.__class__.__name__})\n" f"Error details: {str(e)}\n" @@ -1593,6 +1595,7 @@ def loop_step(self, components, state: PipelineState, **kwargs): try: components, state = block(components, state, **kwargs) except Exception as e: + _add_component_load_error_notes(components, block, e) error_msg = ( f"\nError in block: ({block_name}, {block.__class__.__name__})\n" f"Error details: {str(e)}\n" @@ -1697,6 +1700,21 @@ def set_progress_bar_config(self, **kwargs): # 1. look into the serialization of modular_model_index.json, make sure the items are properly ordered like model_index.json (currently a mess) # 2. do we need ConfigSpec? the are basically just key/val kwargs # 3. imnprove docstring and potentially add validator for methods where we accept kwargs to be passed to from_pretrained/save_pretrained/load_components() +def _add_component_load_error_notes(pipeline, block, error): + if not isinstance(pipeline, ModularPipeline) or not pipeline._component_load_errors or block.sub_blocks: + return + + failed_none_access = isinstance(error, AttributeError) and error.obj is None and error.name is not None + failed_none_operation = isinstance(error, TypeError) and str(error).startswith("'NoneType' object is not ") + if not (failed_none_access or failed_none_operation): + return + + for spec in block.expected_components: + load_error = pipeline._component_load_errors.get(spec.name) + if load_error and getattr(pipeline, spec.name, None) is None: + error.add_note(f"Possibly related component load failure for '{spec.name}': {load_error}") + + class ModularPipeline(ConfigMixin, PushToHubMixin): """ Base class for all Modular pipelines. @@ -1824,6 +1842,7 @@ def __init__( self._components_manager = components_manager self._collection = collection self._component_specs = {spec.name: deepcopy(spec) for spec in self._blocks.expected_components} + self._component_load_errors: dict[str, str] = {} self._config_specs = {spec.name: deepcopy(spec) for spec in self._blocks.expected_configs} # update component_specs and config_specs based on modular_model_index.json @@ -2226,6 +2245,7 @@ def register_components(self, **kwargs): if module is not None: # actual library and class name of the module library, class_name = _fetch_class_library_tuple(module) # e.g. ("diffusers", "UNet2DConditionModel") + self._component_load_errors.pop(name, None) else: # if module is None, e.g. self.register_components(unet=None) during __init__ # we do not update the spec, @@ -2563,8 +2583,10 @@ def load_components(self, names: list[str] | str | None = None, workflow: str | try: components_to_register[name] = spec.load(**component_load_kwargs) - except Exception: + except Exception as error: tb = traceback.format_exc() + if getattr(self, name, None) is None: + self._component_load_errors[name] = f"{type(error).__name__}: {error}" if trust_remote_code_stripped and "trust_remote_code" in tb: warning_msg = ( f"Failed to load component `{name}` from external repository " @@ -2583,7 +2605,7 @@ def load_components(self, names: list[str] | str | None = None, workflow: str | f"Failed to create component {name}:\n" f"- Component spec: {spec}\n" f"- load() called with kwargs: {component_load_kwargs}\n" - "If this component is not required for your workflow you can safely ignore this message.\n\n" + "You can ignore this warning if your workflow does not use this component.\n\n" "Traceback:\n" f"{tb}" ) @@ -3028,7 +3050,8 @@ def __call__(self, state: PipelineState = None, output: str | list[str] = None, with torch.no_grad(): try: _, state = self._blocks(self, state) - except Exception: + except Exception as e: + _add_component_load_error_notes(self, self._blocks, e) error_msg = f"Error in block: ({self._blocks.__class__.__name__}):\n" logger.error(error_msg) raise diff --git a/tests/modular_pipelines/test_modular_pipeline_loading.py b/tests/modular_pipelines/test_modular_pipeline_loading.py index 4871eab4e67d..16dcda8115ec 100644 --- a/tests/modular_pipelines/test_modular_pipeline_loading.py +++ b/tests/modular_pipelines/test_modular_pipeline_loading.py @@ -21,7 +21,8 @@ import torch from huggingface_hub import snapshot_download -from diffusers import AutoModel, ControlNetModel, ModularPipeline, UNet2DConditionModel +from diffusers import AutoModel, ControlNetModel, DDIMScheduler, ModularPipeline, UNet2DConditionModel +from diffusers.modular_pipelines import InputParam, ModularPipelineBlocks, SequentialPipelineBlocks from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec @@ -122,6 +123,81 @@ def test_load_components_skips_invalid_pretrained_path(self): assert not hasattr(pipe, "test_component") or pipe.test_component is None +class SchedulerLoadBlock(ModularPipelineBlocks): + def __init__(self, scheduler_path): + super().__init__() + self.scheduler_path = scheduler_path + + @property + def expected_components(self): + return [ComponentSpec("scheduler", DDIMScheduler, pretrained_model_name_or_path=self.scheduler_path)] + + @property + def inputs(self): + return [InputParam("use_scheduler", type_hint=bool, default=True)] + + def __call__(self, components, state): + if self.get_block_state(state).use_scheduler: + state.set("num_train_timesteps", components.scheduler.config.num_train_timesteps) + else: + state.set("num_train_timesteps", 0) + return components, state + + +class TestComponentLoadErrors: + @pytest.mark.parametrize("sequential", [False, True]) + @pytest.mark.parametrize("recover", ["load", "register", "update"]) + def test_failed_component_load_is_reported(self, tmp_path, sequential, recover): + block = SchedulerLoadBlock(str(tmp_path)) + if sequential: + block = SequentialPipelineBlocks.from_blocks_dict({"scheduler_step": block}) + pipeline = block.init_pipeline() + pipeline.load_components() + + assert pipeline.scheduler is None + assert pipeline(use_scheduler=False, output="num_train_timesteps") == 0 + with pytest.raises(AttributeError, match="NoneType") as exc_info: + pipeline() + assert exc_info.value.name == "config" + assert any( + "Possibly related component load failure for 'scheduler'" in note and "scheduler_config.json" in note + for note in exc_info.value.__notes__ + ) + + scheduler = DDIMScheduler(num_train_timesteps=7) + if recover == "load": + scheduler.save_pretrained(tmp_path) + pipeline.load_components() + elif recover == "register": + pipeline.register_components(scheduler=scheduler) + else: + pipeline.update_components(scheduler=scheduler) + assert pipeline(output="num_train_timesteps") == 7 + + pipeline.unload_components("scheduler") + with pytest.raises(AttributeError, match="NoneType") as exc_info: + pipeline() + assert not getattr(exc_info.value, "__notes__", []) + + def test_missing_input_error_is_not_replaced(self, tmp_path): + class ImageBlock(SchedulerLoadBlock): + @property + def inputs(self): + return [InputParam("image", type_hint=torch.Tensor)] + + def __call__(self, components, state): + state.set("shape", self.get_block_state(state).image.shape) + return components, state + + pipeline = ImageBlock(str(tmp_path)).init_pipeline() + pipeline.load_components() + + with pytest.raises(AttributeError, match="NoneType") as exc_info: + pipeline(image=None) + assert exc_info.value.name == "shape" + assert exc_info.value.__cause__ is None + + class TestCustomModelSavePretrained: @pytest.mark.parametrize("overwrite_modular_index", [True, False]) def test_save_pretrained_updates_index_for_local_model(self, tmp_path, overwrite_modular_index):