diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 672ad87f05..90ce425b14 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -29,7 +29,7 @@ repos: exclude: ^source/3rdparty - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.4.1 + rev: v0.4.2 hooks: - id: ruff args: ["--fix"] diff --git a/backend/read_env.py b/backend/read_env.py index c97c854a13..14935dcc0f 100644 --- a/backend/read_env.py +++ b/backend/read_env.py @@ -63,7 +63,7 @@ def get_argument_from_env() -> Tuple[str, list, list, dict, str]: if hipcc_flags is not None: os.environ["HIPFLAGS"] = os.environ.get("HIPFLAGS", "") + " " + hipcc_flags else: - raise RuntimeError("Unsupported DP_VARIANT option: %s" % dp_variant) + raise RuntimeError(f"Unsupported DP_VARIANT option: {dp_variant}") if os.environ.get("DP_BUILD_TESTING", "0") == "1": cmake_args.append("-DBUILD_TESTING:BOOL=TRUE") diff --git a/data/raw/copy_raw.py b/data/raw/copy_raw.py index 69ccdf5c63..2a4078df4d 100755 --- a/data/raw/copy_raw.py +++ b/data/raw/copy_raw.py @@ -85,7 +85,7 @@ def _main(): ) args = parser.parse_args() - print("# copy the system by %s copies" % args.ncopies) # noqa: T201 + print(f"# copy the system by {args.ncopies} copies") # noqa: T201 assert np.all( np.array(args.ncopies, dtype=int) >= np.array([1, 1, 1], dtype=int) ), "number of copies should be larger than or equal to 1" diff --git a/deepmd/dpmodel/descriptor/make_base_descriptor.py b/deepmd/dpmodel/descriptor/make_base_descriptor.py index 940bd0cd27..a984c96f33 100644 --- a/deepmd/dpmodel/descriptor/make_base_descriptor.py +++ b/deepmd/dpmodel/descriptor/make_base_descriptor.py @@ -135,7 +135,7 @@ def deserialize(cls, data: dict) -> "BD": """ if cls is BD: return BD.get_class_by_type(data["type"]).deserialize(data) - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") @classmethod @abstractmethod diff --git a/deepmd/dpmodel/fitting/make_base_fitting.py b/deepmd/dpmodel/fitting/make_base_fitting.py index c7341798c3..72dc83c29e 100644 --- a/deepmd/dpmodel/fitting/make_base_fitting.py +++ b/deepmd/dpmodel/fitting/make_base_fitting.py @@ -88,7 +88,7 @@ def deserialize(cls, data: dict) -> "BF": """ if cls is BF: return BF.get_class_by_type(data["type"]).deserialize(data) - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") setattr(BF, fwd_method_name, BF.fwd) delattr(BF, "fwd") diff --git a/deepmd/dpmodel/model/base_model.py b/deepmd/dpmodel/model/base_model.py index de69afcf6c..b416e57fb8 100644 --- a/deepmd/dpmodel/model/base_model.py +++ b/deepmd/dpmodel/model/base_model.py @@ -126,7 +126,7 @@ def deserialize(cls, data: dict) -> "BaseBaseModel": if model_type == "standard": model_type = data.get("fitting", {}).get("type", "ener") return cls.get_class_by_type(model_type).deserialize(data) - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") model_def_script: str diff --git a/deepmd/entrypoints/doc.py b/deepmd/entrypoints/doc.py index e55e84f9d3..2f0d57e645 100644 --- a/deepmd/entrypoints/doc.py +++ b/deepmd/entrypoints/doc.py @@ -16,5 +16,5 @@ def doc_train_input(*, out_type: str = "rst", **kwargs): elif out_type == "json": doc_str = gen_json() else: - raise RuntimeError("Unsupported out type %s" % out_type) + raise RuntimeError(f"Unsupported out type {out_type}") print(doc_str) # noqa: T201 diff --git a/deepmd/entrypoints/neighbor_stat.py b/deepmd/entrypoints/neighbor_stat.py index a68a3fd3bb..ef02561ba3 100644 --- a/deepmd/entrypoints/neighbor_stat.py +++ b/deepmd/entrypoints/neighbor_stat.py @@ -91,6 +91,6 @@ def neighbor_stat( data.get_batch() nei = NeighborStat(data.get_ntypes(), rcut, mixed_type=mixed_type) min_nbor_dist, max_nbor_size = nei.get_stat(data) - log.info("min_nbor_dist: %f" % min_nbor_dist) - log.info("max_nbor_size: %s" % str(max_nbor_size)) + log.info(f"min_nbor_dist: {min_nbor_dist:f}") + log.info(f"max_nbor_size: {max_nbor_size!s}") return min_nbor_dist, max_nbor_size diff --git a/deepmd/entrypoints/test.py b/deepmd/entrypoints/test.py index 1540a5a1b9..5f0225c0cd 100644 --- a/deepmd/entrypoints/test.py +++ b/deepmd/entrypoints/test.py @@ -460,14 +460,14 @@ def test_ener( save_txt_file( detail_path.with_suffix(".e.out"), pe, - header="%s: data_e pred_e" % system, + header=f"{system}: data_e pred_e", append=append_detail, ) pe_atom = pe / natoms save_txt_file( detail_path.with_suffix(".e_peratom.out"), pe_atom, - header="%s: data_e pred_e" % system, + header=f"{system}: data_e pred_e", append=append_detail, ) if not out_put_spin: @@ -481,7 +481,7 @@ def test_ener( save_txt_file( detail_path.with_suffix(".f.out"), pf, - header="%s: data_fx data_fy data_fz pred_fx pred_fy pred_fz" % system, + header=f"{system}: data_fx data_fy data_fz pred_fx pred_fy pred_fz", append=append_detail, ) else: @@ -496,14 +496,13 @@ def test_ener( save_txt_file( detail_path.with_suffix(".fr.out"), pf_real, - header="%s: data_fx data_fy data_fz pred_fx pred_fy pred_fz" % system, + header=f"{system}: data_fx data_fy data_fz pred_fx pred_fy pred_fz", append=append_detail, ) save_txt_file( detail_path.with_suffix(".fm.out"), pf_mag, - header="%s: data_fmx data_fmy data_fmz pred_fmx pred_fmy pred_fmz" - % system, + header=f"{system}: data_fmx data_fmy data_fmz pred_fmx pred_fmy pred_fmz", append=append_detail, ) pv = np.concatenate( diff --git a/deepmd/env.py b/deepmd/env.py index 8215de39ac..139e95b824 100644 --- a/deepmd/env.py +++ b/deepmd/env.py @@ -46,9 +46,9 @@ global_float_prec = "float" else: raise RuntimeError( - "Unsupported float precision option: %s. Supported: high," + f"Unsupported float precision option: {dp_float_prec}. Supported: high," "low. Please set precision with environmental variable " - "DP_INTERFACE_PREC." % dp_float_prec + "DP_INTERFACE_PREC." ) diff --git a/deepmd/main.py b/deepmd/main.py index b503107c73..9d023221a6 100644 --- a/deepmd/main.py +++ b/deepmd/main.py @@ -650,7 +650,7 @@ def main_parser() -> argparse.ArgumentParser: # --version parser.add_argument( - "--version", action="version", version="DeePMD-kit v%s" % __version__ + "--version", action="version", version=f"DeePMD-kit v{__version__}" ) # * train nvnmd script ****************************************************************** diff --git a/deepmd/pt/optimizer/LKF.py b/deepmd/pt/optimizer/LKF.py index 6196414243..6683d24fe7 100644 --- a/deepmd/pt/optimizer/LKF.py +++ b/deepmd/pt/optimizer/LKF.py @@ -75,7 +75,7 @@ def __init_P(self): P = [] params_packed_index = [] - logging.info("LKF parameter nums: %s" % param_nums) + logging.info(f"LKF parameter nums: {param_nums}") if self.dist_init: block_num = 0 for param_num in param_nums: diff --git a/deepmd/pt/train/training.py b/deepmd/pt/train/training.py index 5ba4b6f336..6934a9d8fe 100644 --- a/deepmd/pt/train/training.py +++ b/deepmd/pt/train/training.py @@ -651,7 +651,7 @@ def warm_up_linear(step, warmup_steps): self.wrapper.parameters(), 0.98, 0.99870, self.opt_param["kf_blocksize"] ) else: - raise ValueError("Not supported optimizer type '%s'" % self.opt_type) + raise ValueError(f"Not supported optimizer type '{self.opt_type}'") # Get model prob for multi-task if self.multi_task: @@ -808,7 +808,7 @@ def fake_model(): learning_rate=pref_lr, ) else: - raise ValueError("Not supported optimizer type '%s'" % self.opt_type) + raise ValueError(f"Not supported optimizer type '{self.opt_type}'") # Log and persist if _step_id % self.disp_freq == 0: @@ -1170,7 +1170,7 @@ def print_on_training(self, fout, step_id, cur_lr, train_results, valid_results) prop_fmt = " %11.2e" for k in sorted(train_results[model_key].keys()): print_str += prop_fmt % (train_results[model_key][k]) - print_str += " %8.1e\n" % cur_lr + print_str += f" {cur_lr:8.1e}\n" fout.write(print_str) fout.flush() diff --git a/deepmd/tf/cluster/local.py b/deepmd/tf/cluster/local.py index 60961a0d65..009a182e55 100644 --- a/deepmd/tf/cluster/local.py +++ b/deepmd/tf/cluster/local.py @@ -45,7 +45,7 @@ def get_gpus(): stdout, stderr = p.communicate() if p.returncode != 0: decoded = stderr.decode("UTF-8") - raise RuntimeError("Failed to detect availbe GPUs due to:\n%s" % decoded) + raise RuntimeError(f"Failed to detect availbe GPUs due to:\n{decoded}") decoded = stdout.decode("UTF-8").strip() num_gpus = int(decoded) return list(range(num_gpus)) if num_gpus > 0 else None diff --git a/deepmd/tf/descriptor/descriptor.py b/deepmd/tf/descriptor/descriptor.py index 6a4ed5f354..fd6f6729e8 100644 --- a/deepmd/tf/descriptor/descriptor.py +++ b/deepmd/tf/descriptor/descriptor.py @@ -247,7 +247,7 @@ def enable_compression( This method is called by others when the descriptor supported compression. """ raise NotImplementedError( - "Descriptor %s doesn't support compression!" % type(self).__name__ + f"Descriptor {type(self).__name__} doesn't support compression!" ) def enable_mixed_precision(self, mixed_prec: Optional[dict] = None) -> None: @@ -263,8 +263,7 @@ def enable_mixed_precision(self, mixed_prec: Optional[dict] = None) -> None: This method is called by others when the descriptor supported compression. """ raise NotImplementedError( - "Descriptor %s doesn't support mixed precision training!" - % type(self).__name__ + f"Descriptor {type(self).__name__} doesn't support mixed precision training!" ) @abstractmethod @@ -315,8 +314,7 @@ def init_variables( This method is called by others when the descriptor supported initialization from the given variables. """ raise NotImplementedError( - "Descriptor %s doesn't support initialization from the given variables!" - % type(self).__name__ + f"Descriptor {type(self).__name__} doesn't support initialization from the given variables!" ) def get_tensor_names(self, suffix: str = "") -> Tuple[str]: @@ -333,7 +331,7 @@ def get_tensor_names(self, suffix: str = "") -> Tuple[str]: Names of tensors """ raise NotImplementedError( - "Descriptor %s doesn't support this property!" % type(self).__name__ + f"Descriptor {type(self).__name__} doesn't support this property!" ) def pass_tensors_from_frz_model( @@ -353,7 +351,7 @@ def pass_tensors_from_frz_model( :meth:`get_tensor_names`. """ raise NotImplementedError( - "Descriptor %s doesn't support this method!" % type(self).__name__ + f"Descriptor {type(self).__name__} doesn't support this method!" ) def build_type_exclude_mask( @@ -498,7 +496,7 @@ def deserialize(cls, data: dict, suffix: str = "") -> "Descriptor": return Descriptor.get_class_by_type( j_get_type(data, cls.__name__) ).deserialize(data, suffix=suffix) - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") def serialize(self, suffix: str = "") -> dict: """Serialize the model. @@ -513,4 +511,4 @@ def serialize(self, suffix: str = "") -> dict: suffix : str, optional Name suffix to identify this descriptor """ - raise NotImplementedError("Not implemented in class %s" % self.__name__) + raise NotImplementedError(f"Not implemented in class {self.__name__}") diff --git a/deepmd/tf/descriptor/loc_frame.py b/deepmd/tf/descriptor/loc_frame.py index ee414fc0bb..963e9bf607 100644 --- a/deepmd/tf/descriptor/loc_frame.py +++ b/deepmd/tf/descriptor/loc_frame.py @@ -427,12 +427,8 @@ def init_variables( suffix : str, optional The suffix of the scope """ - self.davg = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_avg" % suffix - ) - self.dstd = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_std" % suffix - ) + self.davg = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_avg") + self.dstd = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_std") @classmethod def update_sel(cls, global_jdata: dict, local_jdata: dict): diff --git a/deepmd/tf/descriptor/se.py b/deepmd/tf/descriptor/se.py index 5a3c5dd447..a14dc0a5ce 100644 --- a/deepmd/tf/descriptor/se.py +++ b/deepmd/tf/descriptor/se.py @@ -141,12 +141,8 @@ def init_variables( self.embedding_net_variables = get_embedding_net_variables_from_graph_def( graph_def, suffix=suffix ) - self.davg = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_avg" % suffix - ) - self.dstd = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_std" % suffix - ) + self.davg = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_avg") + self.dstd = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_std") @property def precision(self) -> tf.DType: diff --git a/deepmd/tf/descriptor/se_a.py b/deepmd/tf/descriptor/se_a.py index 4f7897e76c..a3c96d3b9f 100644 --- a/deepmd/tf/descriptor/se_a.py +++ b/deepmd/tf/descriptor/se_a.py @@ -554,12 +554,8 @@ def enable_compression( min_nbor_dist, table_extrapolate, table_stride_1, table_stride_2 ) - self.davg = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_avg" % suffix - ) - self.dstd = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_std" % suffix - ) + self.davg = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_avg") + self.dstd = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_std") def enable_mixed_precision(self, mixed_prec: Optional[dict] = None) -> None: """Reveive the mixed precision setting. @@ -1305,14 +1301,14 @@ def init_variables( super().init_variables(graph=graph, graph_def=graph_def, suffix=suffix) try: self.original_sel = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/original_sel" % suffix + graph, f"descrpt_attr{suffix}/original_sel" ) except GraphWithoutTensorError: # original_sel is not restored in old graphs, assume sel never changed before pass # check sel == original sel? try: - sel = get_tensor_by_name_from_graph(graph, "descrpt_attr%s/sel" % suffix) + sel = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/sel") except GraphWithoutTensorError: # sel is not restored in old graphs pass @@ -1387,7 +1383,7 @@ def deserialize(cls, data: dict, suffix: str = ""): The deserialized model """ if cls is not DescrptSeA: - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") data = data.copy() check_version_compatibility(data.pop("@version", 1), 1, 1) data.pop("@class", None) @@ -1422,7 +1418,7 @@ def serialize(self, suffix: str = "") -> dict: """ if type(self) is not DescrptSeA: raise NotImplementedError( - "Not implemented in class %s" % self.__class__.__name__ + f"Not implemented in class {self.__class__.__name__}" ) if self.stripped_type_embedding: raise NotImplementedError( diff --git a/deepmd/tf/descriptor/se_atten.py b/deepmd/tf/descriptor/se_atten.py index 0ba426ee4b..9b13c3944b 100644 --- a/deepmd/tf/descriptor/se_atten.py +++ b/deepmd/tf/descriptor/se_atten.py @@ -492,12 +492,8 @@ def enable_compression( ) self.two_embd = make_data(self, self.final_type_embedding) - self.davg = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_avg" % suffix - ) - self.dstd = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_std" % suffix - ) + self.davg = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_avg") + self.dstd = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_std") def build( self, @@ -1672,7 +1668,7 @@ def deserialize(cls, data: dict, suffix: str = ""): The deserialized model """ if cls is not DescrptSeAtten: - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") data = data.copy() check_version_compatibility(data.pop("@version"), 1, 1) data.pop("@class") @@ -1711,7 +1707,7 @@ def serialize(self, suffix: str = "") -> dict: """ if type(self) not in [DescrptSeAtten, DescrptDPA1Compat]: raise NotImplementedError( - "Not implemented in class %s" % self.__class__.__name__ + f"Not implemented in class {self.__class__.__name__}" ) if self.stripped_type_embedding: raise NotImplementedError( @@ -2075,7 +2071,7 @@ def deserialize(cls, data: dict, suffix: str = ""): The deserialized model """ if cls is not DescrptDPA1Compat: - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") data = data.copy() check_version_compatibility(data.pop("@version"), 1, 1) data.pop("@class") diff --git a/deepmd/tf/descriptor/se_r.py b/deepmd/tf/descriptor/se_r.py index aef40b74bf..64a599716f 100644 --- a/deepmd/tf/descriptor/se_r.py +++ b/deepmd/tf/descriptor/se_r.py @@ -376,12 +376,8 @@ def enable_compression( min_nbor_dist, table_extrapolate, table_stride_1, table_stride_2 ) - self.davg = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_avg" % suffix - ) - self.dstd = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_std" % suffix - ) + self.davg = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_avg") + self.dstd = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_std") def build( self, @@ -737,7 +733,7 @@ def deserialize(cls, data: dict, suffix: str = ""): The deserialized model """ if cls is not DescrptSeR: - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") data = data.copy() check_version_compatibility(data.pop("@version", 1), 1, 1) embedding_net_variables = cls.deserialize_network( @@ -770,7 +766,7 @@ def serialize(self, suffix: str = "") -> dict: """ if type(self) is not DescrptSeR: raise NotImplementedError( - "Not implemented in class %s" % self.__class__.__name__ + f"Not implemented in class {self.__class__.__name__}" ) if self.embedding_net_variables is None: raise RuntimeError("init_variables must be called before serialize") diff --git a/deepmd/tf/descriptor/se_t.py b/deepmd/tf/descriptor/se_t.py index 4f6cda6c9c..77234cb92e 100644 --- a/deepmd/tf/descriptor/se_t.py +++ b/deepmd/tf/descriptor/se_t.py @@ -368,12 +368,8 @@ def enable_compression( min_nbor_dist, table_extrapolate, table_stride_1 * 10, table_stride_2 * 10 ) - self.davg = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_avg" % suffix - ) - self.dstd = get_tensor_by_name_from_graph( - graph, "descrpt_attr%s/t_std" % suffix - ) + self.davg = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_avg") + self.dstd = get_tensor_by_name_from_graph(graph, f"descrpt_attr{suffix}/t_std") def build( self, diff --git a/deepmd/tf/entrypoints/compress.py b/deepmd/tf/entrypoints/compress.py index 1f2bbc93a0..1e50d88b63 100644 --- a/deepmd/tf/entrypoints/compress.py +++ b/deepmd/tf/entrypoints/compress.py @@ -102,11 +102,10 @@ def compress( except GraphWithoutTensorError as e: if training_script is None: raise RuntimeError( - "The input frozen model: %s has no training script or min_nbor_dist information, " + f"The input frozen model: {input} has no training script or min_nbor_dist information, " "which is not supported by the model compression interface. " "Please consider using the --training-script command within the model compression interface to provide the training script of the input frozen model. " "Note that the input training script must contain the correct path to the training data." - % input ) from e elif not os.path.exists(training_script): raise RuntimeError( @@ -164,10 +163,10 @@ def compress( ) except GraphTooLargeError as e: raise RuntimeError( - "The uniform step size of the tabulation's first table is %f, " + f"The uniform step size of the tabulation's first table is {step:f}, " "which is too small. This leads to a very large graph size, " "exceeding protobuf's limitation (2 GB). You should try to " - "increase the step size." % step + "increase the step size." ) from e # reset the graph, otherwise the size limitation will be only 2 GB / 2 = 1 GB @@ -180,10 +179,10 @@ def compress( freeze(checkpoint_folder=checkpoint_folder, output=output, node_names=None) except GraphTooLargeError as e: raise RuntimeError( - "The uniform step size of the tabulation's first table is %f, " + f"The uniform step size of the tabulation's first table is {step:f}, " "which is too small. This leads to a very large graph size, " "exceeding protobuf's limitation (2 GB). You should try to " - "increase the step size." % step + "increase the step size." ) from e diff --git a/deepmd/tf/entrypoints/freeze.py b/deepmd/tf/entrypoints/freeze.py index 3d2a609797..a2b07f2c5e 100755 --- a/deepmd/tf/entrypoints/freeze.py +++ b/deepmd/tf/entrypoints/freeze.py @@ -368,9 +368,9 @@ def freeze_graph( different_set -= set(optional_node) if different_set: log.warning( - "The following nodes are not in the graph: %s. " + f"The following nodes are not in the graph: {different_set}. " "Skip freezeing these nodes. You may be freezing " - "a checkpoint generated by an old version." % different_set + "a checkpoint generated by an old version." ) # use intersection as output list output_node = list(set(output_node) & set(input_node)) diff --git a/deepmd/tf/fit/dos.py b/deepmd/tf/fit/dos.py index 7989752e5a..d967ce03d0 100644 --- a/deepmd/tf/fit/dos.py +++ b/deepmd/tf/fit/dos.py @@ -611,21 +611,21 @@ def init_variables( self.fitting_net_variables.update(shared_variables) if self.numb_fparam > 0: self.fparam_avg = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_fparam_avg" % suffix + graph, f"fitting_attr{suffix}/t_fparam_avg" ) self.fparam_inv_std = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_fparam_istd" % suffix + graph, f"fitting_attr{suffix}/t_fparam_istd" ) if self.numb_aparam > 0: self.aparam_avg = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_aparam_avg" % suffix + graph, f"fitting_attr{suffix}/t_aparam_avg" ) self.aparam_inv_std = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_aparam_istd" % suffix + graph, f"fitting_attr{suffix}/t_aparam_istd" ) try: self.bias_dos = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_bias_dos" % suffix + graph, f"fitting_attr{suffix}/t_bias_dos" ) except GraphWithoutTensorError: # for compatibility, old models has no t_bias_dos diff --git a/deepmd/tf/fit/ener.py b/deepmd/tf/fit/ener.py index d38d0416af..873f7258db 100644 --- a/deepmd/tf/fit/ener.py +++ b/deepmd/tf/fit/ener.py @@ -779,21 +779,21 @@ def init_variables( self.fitting_net_variables.update(shared_variables) if self.numb_fparam > 0: self.fparam_avg = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_fparam_avg" % suffix + graph, f"fitting_attr{suffix}/t_fparam_avg" ) self.fparam_inv_std = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_fparam_istd" % suffix + graph, f"fitting_attr{suffix}/t_fparam_istd" ) if self.numb_aparam > 0: self.aparam_avg = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_aparam_avg" % suffix + graph, f"fitting_attr{suffix}/t_aparam_avg" ) self.aparam_inv_std = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_aparam_istd" % suffix + graph, f"fitting_attr{suffix}/t_aparam_istd" ) try: self.bias_atom_e = get_tensor_by_name_from_graph( - graph, "fitting_attr%s/t_bias_atom_e" % suffix + graph, f"fitting_attr{suffix}/t_bias_atom_e" ) except GraphWithoutTensorError: # for compatibility, old models has no t_bias_atom_e diff --git a/deepmd/tf/fit/fitting.py b/deepmd/tf/fit/fitting.py index 0f73230bc8..d2aebd8f97 100644 --- a/deepmd/tf/fit/fitting.py +++ b/deepmd/tf/fit/fitting.py @@ -63,8 +63,7 @@ def init_variables( This method is called by others when the fitting supported initialization from the given variables. """ raise NotImplementedError( - "Fitting %s doesn't support initialization from the given variables!" - % type(self).__name__ + f"Fitting {type(self).__name__} doesn't support initialization from the given variables!" ) @abstractmethod @@ -107,7 +106,7 @@ def deserialize(cls, data: dict, suffix: str = "") -> "Fitting": return Fitting.get_class_by_type( j_get_type(data, cls.__name__) ).deserialize(data, suffix=suffix) - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") def serialize(self, suffix: str = "") -> dict: """Serialize the fitting. @@ -122,7 +121,7 @@ def serialize(self, suffix: str = "") -> dict: suffix : str, optional Name suffix to identify this fitting """ - raise NotImplementedError("Not implemented in class %s" % self.__name__) + raise NotImplementedError(f"Not implemented in class {self.__name__}") def serialize_network( self, diff --git a/deepmd/tf/model/dos.py b/deepmd/tf/model/dos.py index 2d244f5733..61809eff30 100644 --- a/deepmd/tf/model/dos.py +++ b/deepmd/tf/model/dos.py @@ -229,6 +229,6 @@ def init_variables( self.fitting.init_variables(graph, graph_def, suffix=suffix) tf.constant("compressed_model", name="model_type", dtype=tf.string) else: - raise RuntimeError("Unknown model type %s" % model_type) + raise RuntimeError(f"Unknown model type {model_type}") if self.typeebd is not None: self.typeebd.init_variables(graph, graph_def, suffix=suffix) diff --git a/deepmd/tf/model/ener.py b/deepmd/tf/model/ener.py index 4a0195b334..c8b9b2d6f5 100644 --- a/deepmd/tf/model/ener.py +++ b/deepmd/tf/model/ener.py @@ -376,7 +376,7 @@ def init_variables( self.fitting.init_variables(graph, graph_def, suffix=suffix) tf.constant("compressed_model", name="model_type", dtype=tf.string) else: - raise RuntimeError("Unknown model type %s" % model_type) + raise RuntimeError(f"Unknown model type {model_type}") if ( self.typeebd is not None and self.typeebd.type_embedding_net_variables is None diff --git a/deepmd/tf/model/model.py b/deepmd/tf/model/model.py index fc8f862e3b..2718d53cbe 100644 --- a/deepmd/tf/model/model.py +++ b/deepmd/tf/model/model.py @@ -283,11 +283,11 @@ def build_descrpt( else: tf.constant( self.rcut, - name="descrpt_attr%s/rcut" % suffix, + name=f"descrpt_attr{suffix}/rcut", dtype=GLOBAL_TF_FLOAT_PRECISION, ) tf.constant( - self.ntypes, name="descrpt_attr%s/ntypes" % suffix, dtype=tf.int32 + self.ntypes, name=f"descrpt_attr{suffix}/ntypes", dtype=tf.int32 ) if "global_feed_dict" in input_dict: feed_dict = input_dict["global_feed_dict"] @@ -302,7 +302,7 @@ def build_descrpt( ) return_elements = [ *self.descrpt.get_tensor_names(suffix=suffix), - "o_descriptor%s:0" % suffix, + f"o_descriptor{suffix}:0", ] if frz_model is not None: imported_tensors = self._import_graph_def_from_frz_model( @@ -571,7 +571,7 @@ def deserialize(cls, data: dict, suffix: str = "") -> "Model": data, suffix=suffix, ) - raise NotImplementedError("Not implemented in class %s" % cls.__name__) + raise NotImplementedError(f"Not implemented in class {cls.__name__}") def serialize(self, suffix: str = "") -> dict: """Serialize the model. @@ -586,7 +586,7 @@ def serialize(self, suffix: str = "") -> dict: suffix : str, optional Name suffix to identify this descriptor """ - raise NotImplementedError("Not implemented in class %s" % self.__name__) + raise NotImplementedError(f"Not implemented in class {self.__name__}") @Model.register("standard") diff --git a/deepmd/tf/model/tensor.py b/deepmd/tf/model/tensor.py index ff20b771a7..b2afe0d71f 100644 --- a/deepmd/tf/model/tensor.py +++ b/deepmd/tf/model/tensor.py @@ -234,7 +234,7 @@ def init_variables( self.fitting.init_variables(graph, graph_def, suffix=suffix) tf.constant("compressed_model", name="model_type", dtype=tf.string) else: - raise RuntimeError("Unknown model type %s" % model_type) + raise RuntimeError(f"Unknown model type {model_type}") class WFCModel(TensorModel): diff --git a/deepmd/tf/nvnmd/entrypoints/train.py b/deepmd/tf/nvnmd/entrypoints/train.py index 18c644a7f6..e6ca374977 100644 --- a/deepmd/tf/nvnmd/entrypoints/train.py +++ b/deepmd/tf/nvnmd/entrypoints/train.py @@ -126,7 +126,7 @@ def train_nvnmd( ): # test input if not os.path.exists(INPUT): - log.warning("The input script %s does not exist" % (INPUT)) + log.warning(f"The input script {INPUT} does not exist") # STEP1 PATH_CNN = "nvnmd_cnn" CONFIG_CNN = os.path.join(PATH_CNN, "config.npy") diff --git a/deepmd/tf/nvnmd/entrypoints/wrap.py b/deepmd/tf/nvnmd/entrypoints/wrap.py index f2be8352e2..adaec39f3e 100644 --- a/deepmd/tf/nvnmd/entrypoints/wrap.py +++ b/deepmd/tf/nvnmd/entrypoints/wrap.py @@ -137,7 +137,7 @@ def wrap(self): # DEVELOP_DEBUG if jdata_sys["debug"]: log.info("%s: %d x % d bit" % (k, h, w * 4)) - FioTxt().save("nvnmd/wrap/h%s.txt" % (k), d) + FioTxt().save(f"nvnmd/wrap/h{k}.txt", d) datas[ii] = d # update h & w of nvnmd_cfg nvnmd_cfg.size["NH_DATA"] = nhs diff --git a/deepmd/tf/nvnmd/utils/fio.py b/deepmd/tf/nvnmd/utils/fio.py index 82567e3917..3efd7520dd 100644 --- a/deepmd/tf/nvnmd/utils/fio.py +++ b/deepmd/tf/nvnmd/utils/fio.py @@ -180,7 +180,7 @@ def save(self, file_name: str, data: List[str]): buff.extend(list(bytearray.fromhex(si))[::-1]) # with open(file_name, "wb") as fp: - fp.write(struct.pack("%sB" % len(buff), *buff)) + fp.write(struct.pack(f"{len(buff)}B", *buff)) class FioTxt: diff --git a/deepmd/tf/train/trainer.py b/deepmd/tf/train/trainer.py index 931cf87246..dc9f81957a 100644 --- a/deepmd/tf/train/trainer.py +++ b/deepmd/tf/train/trainer.py @@ -244,7 +244,7 @@ def build(self, data=None, stop_batch=0, origin_type_map=None, suffix=""): ) else: log.info( - "fitting net %s training without frame parameter" % fitting_key + f"fitting net {fitting_key} training without frame parameter" ) if not self.is_compress: @@ -440,8 +440,7 @@ def _build_optimizer(self, fitting_key=None): _TF_VERSION = Version(TF_VERSION) if _TF_VERSION < Version("1.14.0"): raise RuntimeError( - "TensorFlow version %s is not compatible with the mixed precision setting. Please consider upgrading your TF version!" - % TF_VERSION + f"TensorFlow version {TF_VERSION} is not compatible with the mixed precision setting. Please consider upgrading your TF version!" ) elif _TF_VERSION < Version("2.4.0"): optimizer = tf.train.experimental.enable_mixed_precision_graph_rewrite( @@ -505,14 +504,14 @@ def _init_session(self): fp = open(self.disp_file, "w") fp.close() elif self.run_opt.init_mode == "init_from_model": - log.info("initialize from model %s" % self.run_opt.init_model) + log.info(f"initialize from model {self.run_opt.init_model}") run_sess(self.sess, init_op) self.saver.restore(self.sess, self.run_opt.init_model) run_sess(self.sess, self.global_step.assign(0)) fp = open(self.disp_file, "w") fp.close() elif self.run_opt.init_mode == "restart": - log.info("restart from model %s" % self.run_opt.restart) + log.info(f"restart from model {self.run_opt.restart}") run_sess(self.sess, init_op) self.saver.restore(self.sess, self.run_opt.restart) elif self.run_opt.init_mode == "init_from_frz_model": @@ -837,7 +836,7 @@ def save_checkpoint(self, cur_batch: int): # make symlinks from prefix with step to that without step to break nothing # get all checkpoint files symlink_prefix_files(ckpt_prefix, self.save_ckpt) - log.info("saved checkpoint %s" % self.save_ckpt) + log.info(f"saved checkpoint {self.save_ckpt}") def get_feed_dict(self, batch, is_training): feed_dict = {} @@ -963,7 +962,7 @@ def print_on_training( prop_fmt = " %11.2e" for k in train_results.keys(): print_str += prop_fmt % (train_results[k]) - print_str += " %8.1e\n" % cur_lr + print_str += f" {cur_lr:8.1e}\n" log.info( format_training_message_per_task( batch=cur_batch, @@ -995,7 +994,7 @@ def print_on_training( prop_fmt = " %11.2e" for k in train_results[fitting_key].keys(): print_str += prop_fmt % (train_results[fitting_key][k]) - print_str += " %8.1e\n" % cur_lr_dict[fitting_key] + print_str += f" {cur_lr_dict[fitting_key]:8.1e}\n" log.info( format_training_message_per_task( batch=cur_batch, @@ -1090,9 +1089,8 @@ def _init_from_frz_model(self): except GraphWithoutTensorError as e: # throw runtime error if the frozen_model has no model type information... raise RuntimeError( - "The input frozen model: %s has no 'model_type' information, " + f"The input frozen model: {self.run_opt.init_frz_model} has no 'model_type' information, " "which is not supported by the 'dp train init-frz-model' interface. " - % self.run_opt.init_frz_model ) from e else: self.model_type = bytes.decode(t_model_type) @@ -1144,9 +1142,8 @@ def _init_from_pretrained_model( except GraphWithoutTensorError as e: # throw runtime error if the frozen_model has no model type information... raise RuntimeError( - "The input frozen pretrained model: %s has no 'model_type' information, " + f"The input frozen pretrained model: {self.run_opt.finetune} has no 'model_type' information, " "which is not supported by the 'dp train finetune' interface. " - % self.run_opt.finetune ) from e else: self.model_type = bytes.decode(t_model_type) diff --git a/deepmd/tf/utils/convert.py b/deepmd/tf/utils/convert.py index 625f54a9a0..9005fb7d8e 100644 --- a/deepmd/tf/utils/convert.py +++ b/deepmd/tf/utils/convert.py @@ -77,8 +77,7 @@ def convert_to_21(input_model: str, output_model: str, version: Optional[str] = convert_pb_to_pbtxt(input_model, "frozen_model.pbtxt") if version is None: raise ValueError( - "The version of the DP graph %s cannot be detected. Please do the conversion manually." - % (input_model) + f"The version of the DP graph {input_model} cannot be detected. Please do the conversion manually." ) if version in SpecifierSet("<1.0"): convert_dp012_to_dp10("frozen_model.pbtxt") diff --git a/deepmd/tf/utils/finetune.py b/deepmd/tf/utils/finetune.py index 3d11130ba7..4e55b9f5bb 100644 --- a/deepmd/tf/utils/finetune.py +++ b/deepmd/tf/utils/finetune.py @@ -33,10 +33,9 @@ def replace_model_params_with_pretrained_model( t_jdata = get_tensor_by_name(pretrained_model, "train_attr/training_script") except GraphWithoutTensorError as e: raise RuntimeError( - "The input frozen pretrained model: %s has no training script, " + f"The input frozen pretrained model: {input} has no training script, " "which is not supported to perform finetuning. " "Please use the model pretrained with v2.1.5 or higher version of DeePMD-kit." - % input ) from e pretrained_jdata = json.loads(t_jdata) diff --git a/deepmd/tf/utils/multi_init.py b/deepmd/tf/utils/multi_init.py index aafa9461b0..aef4bf4af9 100644 --- a/deepmd/tf/utils/multi_init.py +++ b/deepmd/tf/utils/multi_init.py @@ -33,10 +33,9 @@ def replace_model_params_with_frz_multi_model( t_jdata = get_tensor_by_name(pretrained_model, "train_attr/training_script") except GraphWithoutTensorError as e: raise RuntimeError( - "The input frozen pretrained model: %s has no training script, " + f"The input frozen pretrained model: {input} has no training script, " "which is not supported to perform multi-task training. " "Please use the model pretrained with v2.1.5 or higher version of DeePMD-kit." - % input ) from e pretrained_jdata = json.loads(t_jdata) diff --git a/deepmd/utils/data.py b/deepmd/utils/data.py index d01509d6f5..cd0e414b5f 100644 --- a/deepmd/utils/data.py +++ b/deepmd/utils/data.py @@ -384,7 +384,7 @@ def get_natoms_vec(self, ntypes: int): def avg(self, key): """Return the average value of an item.""" if key not in self.data_dict.keys(): - raise RuntimeError("key %s has not been added" % key) + raise RuntimeError(f"key {key} has not been added") info = self.data_dict[key] ndof = info["ndof"] eners = [] @@ -670,7 +670,7 @@ def _load_data( data = np.repeat(data, repeat).reshape([nframes, -1]) return np.float32(1.0), data elif must: - raise RuntimeError("%s not found!" % path) + raise RuntimeError(f"{path} not found!") else: if atomic and type_sel is not None and not output_natoms_for_type_sel: ndof = ndof_ * natoms_sel diff --git a/deepmd/utils/data_system.py b/deepmd/utils/data_system.py index 640083bc33..693845f8d0 100644 --- a/deepmd/utils/data_system.py +++ b/deepmd/utils/data_system.py @@ -661,7 +661,7 @@ def print_summary( ) log.info("found %d system(s):" % nsystems) log.info( - ("%s " % _format_name_length("system", sys_width)) + ("{} ".format(_format_name_length("system", sys_width))) + ("%6s %6s %6s %9s %3s" % ("natoms", "bch_sz", "n_bch", "prob", "pbc")) ) for ii in range(nsystems): diff --git a/deepmd/utils/neighbor_stat.py b/deepmd/utils/neighbor_stat.py index 34200df007..54a4c16b24 100644 --- a/deepmd/utils/neighbor_stat.py +++ b/deepmd/utils/neighbor_stat.py @@ -67,16 +67,15 @@ def get_stat(self, data: DeepmdDataSystem) -> Tuple[float, np.ndarray]: for mn, dt, jj in self.iterator(data): if np.isinf(dt): log.warning( - "Atoms with no neighbors found in %s. Please make sure it's what you expected." - % jj + f"Atoms with no neighbors found in {jj}. Please make sure it's what you expected." ) if dt < min_nbor_dist: if math.isclose(dt, 0.0, rel_tol=1e-6): # it's unexpected that the distance between two atoms is zero # zero distance will cause nan (#874) raise RuntimeError( - "Some atoms are overlapping in %s. Please check your" - " training data to remove duplicated atoms." % jj + f"Some atoms are overlapping in {jj}. Please check your" + " training data to remove duplicated atoms." ) min_nbor_dist = dt max_nbor_size = np.maximum(mn, max_nbor_size) diff --git a/deepmd/utils/path.py b/deepmd/utils/path.py index 858e31a39d..377953cc35 100644 --- a/deepmd/utils/path.py +++ b/deepmd/utils/path.py @@ -42,7 +42,7 @@ def __new__(cls, path: str, mode: str = "r"): elif os.path.isfile(path.split("#")[0]): # assume h5 if it is not dir return super().__new__(DPH5Path) - raise FileNotFoundError("%s not found" % path) + raise FileNotFoundError(f"{path} not found") return super().__new__(cls) @abstractmethod diff --git a/doc/conf.py b/doc/conf.py index 704ad45479..7eafdb2c37 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -150,7 +150,7 @@ import typing for typing_type in typing.__all__: - numpydoc_xref_aliases[typing_type] = "typing.%s" % typing_type + numpydoc_xref_aliases[typing_type] = f"typing.{typing_type}" rst_epilog = f""" .. |ACTIVATION_FN| replace:: {list_to_doc(ACTIVATION_FN_DICT.keys())} diff --git a/source/install/build_tf.py b/source/install/build_tf.py index d639e2cf51..5e988dd721 100755 --- a/source/install/build_tf.py +++ b/source/install/build_tf.py @@ -192,7 +192,7 @@ def path(self) -> Path: @property def gzip_path(self) -> Path: if self.gzip is None: - raise RuntimeError("gzip is None for %s" % self.path) + raise RuntimeError(f"gzip is None for {self.path}") return PACKAGE_DIR / self.gzip @property @@ -257,10 +257,9 @@ def __call__(self): dd() else: dlog.info( - "Skip installing %s, which has been already installed" - % dd.__class__.__name__ + f"Skip installing {dd.__class__.__name__}, which has been already installed" ) - dlog.info("Start installing %s..." % self.__class__.__name__) + dlog.info(f"Start installing {self.__class__.__name__}...") with tempfile.TemporaryDirectory() as tmpdirname: self._prefix = Path(tmpdirname) self.build() @@ -621,7 +620,7 @@ def dependencies(self) -> Dict[str, Build]: def build(self): tf_res = self.resources["tensorflow"] - src = tf_res.gzip_path / ("tensorflow-%s" % self.version) + src = tf_res.gzip_path / (f"tensorflow-{self.version}") with set_directory(src): # configure -- need bazelisk in PATH call( diff --git a/source/tests/pt/model/test_model.py b/source/tests/pt/model/test_model.py index 71ad64d99d..6eb460e808 100644 --- a/source/tests/pt/model/test_model.py +++ b/source/tests/pt/model/test_model.py @@ -74,7 +74,7 @@ def torch2tf(torch_name, last_layer_id=None): else: ret = "final_layer_type_%d/%s:0" % (element_id, weight_type) else: - raise RuntimeError("Unexpected parameter name: %s" % torch_name) + raise RuntimeError(f"Unexpected parameter name: {torch_name}") return ret diff --git a/source/tests/pt/test_loss.py b/source/tests/pt/test_loss.py index 66460dfef1..dcd59cd56e 100644 --- a/source/tests/pt/test_loss.py +++ b/source/tests/pt/test_loss.py @@ -204,10 +204,10 @@ def fake_model(): for key in ["ener", "force", "virial"]: self.assertTrue( np.allclose( - base_more_loss["l2_%s_loss" % key], my_more_loss["l2_%s_loss" % key] + base_more_loss[f"l2_{key}_loss"], my_more_loss[f"l2_{key}_loss"] ) ) - self.assertTrue(np.isnan(my_more_loss_absent["l2_%s_loss" % key])) + self.assertTrue(np.isnan(my_more_loss_absent[f"l2_{key}_loss"])) class TestEnerSpinLoss(unittest.TestCase): @@ -401,10 +401,10 @@ def fake_model(): for key in ["ener", "force_r", "force_m"]: self.assertTrue( np.allclose( - base_more_loss["l2_%s_loss" % key], my_more_loss["l2_%s_loss" % key] + base_more_loss[f"l2_{key}_loss"], my_more_loss[f"l2_{key}_loss"] ) ) - self.assertTrue(np.isnan(my_more_loss_absent["l2_%s_loss" % key])) + self.assertTrue(np.isnan(my_more_loss_absent[f"l2_{key}_loss"])) if __name__ == "__main__": diff --git a/source/tests/tf/common.py b/source/tests/tf/common.py index d4f3cc8392..705e9f7faa 100644 --- a/source/tests/tf/common.py +++ b/source/tests/tf/common.py @@ -667,8 +667,7 @@ def __init__(self, sys_path, set_prefix, seed=None, shuffle_test=True): ] if any(has_fparam) and (not all(has_fparam)): raise RuntimeError( - "system %s: if any set has frame parameter, then all sets should have frame parameter" - % sys_path + f"system {sys_path}: if any set has frame parameter, then all sets should have frame parameter" ) if all(has_fparam): self.has_fparam = 0 @@ -680,8 +679,7 @@ def __init__(self, sys_path, set_prefix, seed=None, shuffle_test=True): ] if any(has_aparam) and (not all(has_aparam)): raise RuntimeError( - "system %s: if any set has frame parameter, then all sets should have frame parameter" - % sys_path + f"system {sys_path}: if any set has frame parameter, then all sets should have frame parameter" ) if all(has_aparam): self.has_aparam = 0 @@ -771,7 +769,7 @@ def load_data(self, set_name, data_name, shape, is_necessary=True): return data return 1, data elif is_necessary: - raise OSError("%s not found!" % path) + raise OSError(f"{path} not found!") else: data = np.zeros(shape) return 0, data @@ -1025,7 +1023,7 @@ def print_summary(self): sys_width = 42 tmp_msg += "---Summary of DataSystem-----------------------------------------\n" tmp_msg += "find %d system(s):\n" % self.nsystems - tmp_msg += "%s " % self.format_name_length("system", sys_width) + tmp_msg += "{} ".format(self.format_name_length("system", sys_width)) tmp_msg += "{} {} {}\n".format("natoms", "bch_sz", "n_bch") for ii in range(self.nsystems): tmp_msg += "%s %6d %6d %5d\n" % (