Save the model to an ``.mlmodel`` format. For an MIL program, the ``save_path`` is a package directory containing the ``mlmodel`` and weights. Parameters ---------- save_path: Target file path / bundle directory for the model. Examples -----
(self, save_path: str)
| 691 | return self.__repr__() |
| 692 | |
| 693 | def save(self, save_path: str): |
| 694 | """ |
| 695 | Save the model to an ``.mlmodel`` format. For an MIL program, the ``save_path`` is |
| 696 | a package directory containing the ``mlmodel`` and weights. |
| 697 | |
| 698 | Parameters |
| 699 | ---------- |
| 700 | save_path: Target file path / bundle directory for the model. |
| 701 | |
| 702 | Examples |
| 703 | -------- |
| 704 | .. sourcecode:: python |
| 705 | |
| 706 | model.save("my_model_file.mlmodel") |
| 707 | loaded_model = MLModel("my_model_file.mlmodel") |
| 708 | |
| 709 | """ |
| 710 | save_path = _os.path.expanduser(save_path) |
| 711 | |
| 712 | # Clean up existing file or directory. |
| 713 | if _os.path.exists(save_path): |
| 714 | if _os.path.isdir(save_path): |
| 715 | _shutil.rmtree(save_path) |
| 716 | else: |
| 717 | _os.remove(save_path) |
| 718 | |
| 719 | if self.is_package: |
| 720 | name, ext = _os.path.splitext(save_path) |
| 721 | if not ext: |
| 722 | save_path = "{}{}".format(save_path, _MLPACKAGE_EXTENSION) |
| 723 | elif ext != _MLPACKAGE_EXTENSION: |
| 724 | raise Exception( |
| 725 | "For an ML Program, extension must be {} (not {}). Please see https://coremltools.readme.io/docs/unified-conversion-api#target-conversion-formats to see the difference between neuralnetwork and mlprogram model types.".format( |
| 726 | _MLPACKAGE_EXTENSION, ext |
| 727 | ) |
| 728 | ) |
| 729 | _shutil.copytree(self.package_path, save_path) |
| 730 | |
| 731 | if self._mil_program is not None and all( |
| 732 | [ |
| 733 | _ScopeSource.EXIR_DEBUG_HANDLE in function._essential_scope_sources for function in self._mil_program.functions.values() |
| 734 | ] |
| 735 | ): |
| 736 | debug_handle_to_ops_mapping = ( |
| 737 | self._mil_program.construct_debug_handle_to_ops_mapping() |
| 738 | ) |
| 739 | if len(debug_handle_to_ops_mapping) > 0: |
| 740 | debug_handle_to_ops_mapping_as_json = json.dumps( |
| 741 | { |
| 742 | "version" : self.user_defined_metadata[_METADATA_VERSION], |
| 743 | "mapping" : debug_handle_to_ops_mapping, |
| 744 | } |
| 745 | ) |
| 746 | saved_debug_handle_to_ops_mapping_path = _os.path.join( |
| 747 | save_path, "executorch_debug_handle_mapping.json" |
| 748 | ) |
| 749 | with open(saved_debug_handle_to_ops_mapping_path, "w") as f: |
| 750 | f.write(debug_handle_to_ops_mapping_as_json) |