aboutsummaryrefslogtreecommitdiff
path: root/setup.py
blob: 07baededbd8b7dad7036e2d33afbc0615ecb9988 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# SPDX-FileCopyrightText: Copyright 2022, Arm Limited and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
import argparse
import git
import os
import pathlib
import setuptools
import setuptools.command.build_ext
import shutil
import sys
import time


TOSA_CHECKER_VERSION = "0.1.0"
DEFAULT_TENSORFLOW_VERSION = "2.9.0"

# Get the TensorFlowâ„¢ source directory passed to the command line (if any).
# If none is given the sources are pulled from the official TF repository.
argparser = argparse.ArgumentParser()
argparser.add_argument(
    "--tensorflow_src_dir", help="TensorFlow source directory path", required=False
)
argparser.add_argument(
    "--sanitizer",
    help="Build using a sanitizer (choose from asan or ubsan)",
    choices=["asan", "ubsan"],
    required=False
)
argparser.add_argument(
    "--tosa_checker_copt",
    help="Build tosa_checker with additional copt (comma separated string)",
    default="",
    required=False
)
argparser.add_argument(
    "--nightly",
    help="Build tosa_checker as a nightly wheel",
    action="store_true"
)
args, unknown = argparser.parse_known_args()
sys.argv = [sys.argv[0]] + unknown

def increment_version(version_string):
    version_numbers = version_string.split(".")
    increment = int(version_numbers[1]) + 1

    version_numbers[1] = str(increment)

    return ".".join(version_numbers)

def get_package_version(nightly=False):
    if nightly:
        return "{}.dev{}".format(
            increment_version(TOSA_CHECKER_VERSION),
            time.strftime("%Y%m%d")
        )
    else:
        return TOSA_CHECKER_VERSION

def get_repo_version(repo_directory):
    r = git.repo.Repo(repo_directory)
    tag = r.git.tag('--points-at')

    if tag:
        return tag
    else:
        return r.head.commit.hexsha

class BazelExtensionModule(setuptools.Extension):
    def __init__(
        self,
        py_module_name,
        library_name,
        bazel_target,
        bazel_shared_lib_output,
        tensorflow_version,
    ):
        super().__init__(py_module_name, sources=[])
        self.library_name = library_name
        self.bazel_target = bazel_target
        self.bazel_shared_lib_output = bazel_shared_lib_output
        self.tensorflow_version = tensorflow_version


class BazelBuildExtension(setuptools.command.build_ext.build_ext):
    """Override build_extension to build the library with bazel and copying it
    beforehand."""

    def build_extension(self, ext):
        tensorflow_src_dir = args.tensorflow_src_dir

        if not tensorflow_src_dir:
            tensorflow_src_dir = os.path.join(self.build_temp, "tensorflow")
            self._clone_tf_repository(
                tensorflow_src_dir,
                ext.tensorflow_version,
            )

        commands = [
            "bazel",
            "build"
        ]

        if args.sanitizer:
            commands += [
                "--config={}".format(args.sanitizer)
            ]
        if args.tosa_checker_copt:
            commands += [
                "--per_file_copt=tosa_checker/tosa_checker.*@{}".format(args.tosa_checker_copt)
            ]
        commands += [
            # FIXME Some of the Bazel targets dependencies we use have
            # a 'friends' visibility, check if our Bazel target can be added
            # to the 'friends' list.
            "-c",
            "opt",
            "--check_visibility=false",
            "--override_repository=org_tensorflow={}".format(
                os.path.abspath(tensorflow_src_dir)
            ),
            ext.bazel_target
        ]

        self.spawn(commands)

        shared_lib_dest_path = self.get_ext_fullpath(ext.name)
        shared_lib_dest_dir = os.path.dirname(shared_lib_dest_path)
        package_dir = os.path.join(shared_lib_dest_dir, ext.library_name)

        os.makedirs(shared_lib_dest_dir, exist_ok=True)
        os.makedirs(package_dir, exist_ok=True)

        shutil.copyfile(ext.bazel_shared_lib_output, shared_lib_dest_path)

        # Get the TensorFlow version this is built with
        tf_version = get_repo_version(tensorflow_src_dir)

        with open(os.path.join(ext.library_name, "__init__.py"), "r") as f:
            module_init_file = f.read()

        module_init_file += "__tensorflow_version__ = \"{}\"\n".format(tf_version)

        with open(os.path.join(package_dir, "__init__.py"), "w") as f:
            f.write(module_init_file)

        super().build_extension(ext)

    def _clone_tf_repository(self, tensorflow_src_dir, tensorflow_version):
        if os.path.exists(tensorflow_src_dir):
            return

        tensorflow_repo = "https://github.com/tensorflow/tensorflow.git"
        self.spawn(
            [
                "git",
                "clone",
                "--depth=1",
                "--branch",
                "v" + tensorflow_version,
                tensorflow_repo,
                tensorflow_src_dir,
            ]
        )


setuptools.setup(
    name="tosa-checker",
    version=get_package_version(args.nightly),
    description="Tool to check if a ML model is compatible with the TOSA specification",
    long_description=(pathlib.Path(__file__).parent / "README.md").read_text(),
    long_description_content_type="text/markdown",
    author="Arm Limited",
    url="https://git.mlplatform.org/tosa/tosa_checker.git/",
    license="Apache-2.0",
    python_requires=">=3.7",
    cmdclass={"build_ext": BazelBuildExtension},
    ext_modules=[
        BazelExtensionModule(
            py_module_name="_tosa_checker_wrapper",
            library_name="tosa_checker",
            bazel_target="//tosa_checker:tosa_checker",
            bazel_shared_lib_output="bazel-bin/tosa_checker/_tosa_checker_wrapper.so",
            tensorflow_version=DEFAULT_TENSORFLOW_VERSION,
        ),
    ],
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python :: 3",
        "Topic :: Utilities",
    ],
)