| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """Repack model script for training jobs to inject entry points""" |
| from __future__ import absolute_import |
|
|
| import argparse |
| import os |
| import shutil |
| import tarfile |
| import tempfile |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| from distutils.dir_util import copy_tree |
|
|
|
|
| def repack(inference_script, model_archive, dependencies=None, source_dir=None): |
| """Repack custom dependencies and code into an existing model TAR archive |
| |
| Args: |
| inference_script (str): The path to the custom entry point. |
| model_archive (str): The name or path (e.g. s3 uri) of the model TAR archive. |
| dependencies (str): A space-delimited string of paths to custom dependencies. |
| source_dir (str): The path to a custom source directory. |
| """ |
|
|
| |
| data_directory = "/opt/ml/input/data/training" |
| model_path = os.path.join(data_directory, model_archive.split("/")[-1]) |
|
|
| |
| with tempfile.TemporaryDirectory() as tmp: |
| local_path = os.path.join(tmp, "local.tar.gz") |
| |
| shutil.copy2(model_path, local_path) |
| src_dir = os.path.join(tmp, "src") |
| |
| code_dir = os.path.join(src_dir, "code") |
| os.makedirs(code_dir) |
| |
| |
| with tarfile.open(name=local_path, mode="r:gz") as tf: |
| tf.extractall(path=src_dir) |
|
|
| if source_dir: |
| |
| if os.path.exists(code_dir): |
| shutil.rmtree(code_dir) |
| shutil.copytree("/opt/ml/code", code_dir) |
| else: |
| |
| entry_point = os.path.join("/opt/ml/code", inference_script) |
| shutil.copy2(entry_point, os.path.join(code_dir, inference_script)) |
|
|
| |
| if dependencies: |
| for dependency in dependencies.split(" "): |
| actual_dependency_path = os.path.join("/opt/ml/code", dependency) |
| lib_dir = os.path.join(code_dir, "lib") |
| if not os.path.exists(lib_dir): |
| os.mkdir(lib_dir) |
| if os.path.isfile(actual_dependency_path): |
| shutil.copy2(actual_dependency_path, lib_dir) |
| else: |
| if os.path.exists(lib_dir): |
| shutil.rmtree(lib_dir) |
| |
| |
| |
| shutil.copytree("/opt/ml/code", lib_dir) |
| break |
|
|
| |
| |
| copy_tree(src_dir, "/opt/ml/model") |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--inference_script", type=str, default="inference.py") |
| parser.add_argument("--dependencies", type=str, default=None) |
| parser.add_argument("--source_dir", type=str, default=None) |
| parser.add_argument("--model_archive", type=str, default="model.tar.gz") |
| args, extra = parser.parse_known_args() |
| repack( |
| inference_script=args.inference_script, |
| dependencies=args.dependencies, |
| source_dir=args.source_dir, |
| model_archive=args.model_archive, |
| ) |
|
|