Repository: Lightning-AI/pytorch-lightning
File: src/lightning/pytorch/cli.py (Python)

Code before:
        """Parses command line arguments and stores it in ``self.config``."""
        if args is not None and len(sys.argv) > 1:
            rank_zero_warn(
                "LightningCLI's args parameter is intended to run from within Python like if it were from the command "
                "line. To prevent mistakes it is not recommended to provide both args and command line arguments, got: "
                f"sys.argv[1:]={sys.argv[1:]}, args={args}."
            )
        if isinstance(args, (dict, Namespace)):
            self.config = parser.parse_object(args)
        else:
            self.config = parser.parse_args(args)

    def _parse_ckpt_path(self) -> None:
        """If a checkpoint path is given, parse the hyperparameters from the checkpoint and update the config."""
        if not self.config.get("subcommand"):
            return
        ckpt_path = self.config[self.config.subcommand].get("ckpt_path")
        if ckpt_path and Path(ckpt_path).is_file():
            ckpt = torch.load(ckpt_path, weights_only=True, map_location="cpu")
            hparams = ckpt.get("hyper_parameters", {})
            hparams.pop("_instantiator", None)
            if hparams:
                hparams = {self.config.subcommand: {"model": hparams}}
                self.config = self.parser.parse_object(hparams, self.config)

    def _dump_config(self) -> None:
        if hasattr(self, "config_dump"):
            return
        self.config_dump = yaml.safe_load(
            self.parser.dump(self.config, skip_link_targets=False, skip_none=False, format="yaml")
        )
        if "subcommand" in self.config:
            self.config_dump = self.config_dump[self.config.subcommand]

    def _add_instantiators(self) -> None:
        self.parser.add_instantiator(
            _InstantiatorFn(cli=self, key="model"),
            _get_module_type(self._model_class),
            subclasses=self.subclass_mode_model,
        )
        self.parser.add_instantiator(
            _InstantiatorFn(cli=self, key="data"),
            _get_module_type(self._datamodule_class),
            subclasses=self.subclass_mode_data,
        )

    def before_instantiate_classes(self) -> None:
        """Implement to run some code before instantiating the classes."""

    def instantiate_classes(self) -> None:
        """Instantiates the classes and sets their attributes."""

Review comment (bug):
I think I will change this a bit. If someone provides a path to a checkpoint that corresponds to a different model, the error would be confusing. Better if the error starts with something like "parsing of hyperparameters found in ckpt_path failed".

Code after:
        """Parses command line arguments and stores it in ``self.config``."""
        if args is not None and len(sys.argv) > 1:
            rank_zero_warn(
                "LightningCLI's args parameter is intended to run from within Python like if it were from the command "
                "line. To prevent mistakes it is not recommended to provide both args and command line arguments, got: "
                f"sys.argv[1:]={sys.argv[1:]}, args={args}."
            )
        if isinstance(args, (dict, Namespace)):
            self.config = parser.parse_object(args)
        else:
            self.config = parser.parse_args(args)

    def _parse_ckpt_path(self) -> None:
        """If a checkpoint path is given, parse the hyperparameters from the checkpoint and update the config."""
        if not self.config.get("subcommand"):
            return
        ckpt_path = self.config[self.config.subcommand].get("ckpt_path")
        if ckpt_path and Path(ckpt_path).is_file():
            ckpt = torch.load(ckpt_path, weights_only=True, map_location="cpu")
            hparams = ckpt.get("hyper_parameters", {})
            hparams.pop("_instantiator", None)
            if not hparams:
                return
            hparams = {self.config.subcommand: {"model": hparams}}
            try:
                self.config = self.parser.parse_object(hparams, self.config)
            except SystemExit:
                sys.stderr.write("Parsing of ckpt_path hyperparameters failed!\n")
                raise

    def _dump_config(self) -> None:
        if hasattr(self, "config_dump"):
            return
        self.config_dump = yaml.safe_load(
            self.parser.dump(self.config, skip_link_targets=False, skip_none=False, format="yaml")
        )
        if "subcommand" in self.config:
            self.config_dump = self.config_dump[self.config.subcommand]

    def _add_instantiators(self) -> None:
        self.parser.add_instantiator(
            _InstantiatorFn(cli=self, key="model"),
            _get_module_type(self._model_class),
            subclasses=self.subclass_mode_model,
        )
        self.parser.add_instantiator(
            _InstantiatorFn(cli=self, key="data"),
            _get_module_type(self._datamodule_class),
            subclasses=self.subclass_mode_data,
        )