setup.py 19.5 KB
Newer Older
1
# Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Przemek Tredak's avatar
Przemek Tredak committed
2
3
4
#
# See LICENSE for license information.

5
import ctypes
Tim Moon's avatar
Tim Moon committed
6
from functools import lru_cache
Przemek Tredak's avatar
Przemek Tredak committed
7
import os
Tim Moon's avatar
Tim Moon committed
8
from pathlib import Path
Przemek Tredak's avatar
Przemek Tredak committed
9
import re
Tim Moon's avatar
Tim Moon committed
10
11
12
13
import shutil
import subprocess
from subprocess import CalledProcessError
import sys
Przemek Tredak's avatar
Przemek Tredak committed
14
import tempfile
Tim Moon's avatar
Tim Moon committed
15
from typing import List, Optional, Tuple, Union
Przemek Tredak's avatar
Przemek Tredak committed
16

Tim Moon's avatar
Tim Moon committed
17
18
import setuptools
from setuptools.command.build_ext import build_ext
Przemek Tredak's avatar
Przemek Tredak committed
19

Tim Moon's avatar
Tim Moon committed
20
21
# Project directory root
root_path: Path = Path(__file__).resolve().parent
Przemek Tredak's avatar
Przemek Tredak committed
22

Tim Moon's avatar
Tim Moon committed
23
24
25
@lru_cache(maxsize=1)
def te_version() -> str:
    """Transformer Engine version string
Przemek Tredak's avatar
Przemek Tredak committed
26

Tim Moon's avatar
Tim Moon committed
27
28
    Includes Git commit as local version, unless suppressed with
    NVTE_NO_LOCAL_VERSION environment variable.
Przemek Tredak's avatar
Przemek Tredak committed
29

Tim Moon's avatar
Tim Moon committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    """
    with open(root_path / "VERSION", "r") as f:
        version = f.readline().strip()
    if not int(os.getenv("NVTE_NO_LOCAL_VERSION", "0")):
        try:
            output = subprocess.run(
                ["git", "rev-parse" , "--short", "HEAD"],
                capture_output=True,
                cwd=root_path,
                check=True,
                universal_newlines=True,
            )
        except (CalledProcessError, OSError):
            pass
        else:
            commit = output.stdout.strip()
            version += f"+{commit}"
    return version
Przemek Tredak's avatar
Przemek Tredak committed
48

Tim Moon's avatar
Tim Moon committed
49
50
51
52
53
54
55
56
57
58
@lru_cache(maxsize=1)
def with_debug_build() -> bool:
    """Whether to build with a debug configuration"""
    for arg in sys.argv:
        if arg == "--debug":
            sys.argv.remove(arg)
            return True
    if int(os.getenv("NVTE_BUILD_DEBUG", "0")):
        return True
    return False
Przemek Tredak's avatar
Przemek Tredak committed
59

Tim Moon's avatar
Tim Moon committed
60
61
62
# Call once in global scope since this function manipulates the
# command-line arguments. Future calls will use a cached value.
with_debug_build()
Przemek Tredak's avatar
Przemek Tredak committed
63

Tim Moon's avatar
Tim Moon committed
64
65
def found_cmake() -> bool:
    """"Check if valid CMake is available
Przemek Tredak's avatar
Przemek Tredak committed
66

Tim Moon's avatar
Tim Moon committed
67
    CMake 3.18 or newer is required.
68

Tim Moon's avatar
Tim Moon committed
69
    """
Przemek Tredak's avatar
Przemek Tredak committed
70

Tim Moon's avatar
Tim Moon committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    # Check if CMake is available
    try:
        _cmake_bin = cmake_bin()
    except FileNotFoundError:
        return False

    # Query CMake for version info
    output = subprocess.run(
        [_cmake_bin, "--version"],
        capture_output=True,
        check=True,
        universal_newlines=True,
    )
    match = re.search(r"version\s*([\d.]+)", output.stdout)
    version = match.group(1).split('.')
    version = tuple(int(v) for v in version)
    return version >= (3, 18)
Przemek Tredak's avatar
Przemek Tredak committed
88

Tim Moon's avatar
Tim Moon committed
89
90
def cmake_bin() -> Path:
    """Get CMake executable
Przemek Tredak's avatar
Przemek Tredak committed
91

Tim Moon's avatar
Tim Moon committed
92
    Throws FileNotFoundError if not found.
93

Tim Moon's avatar
Tim Moon committed
94
    """
95

Tim Moon's avatar
Tim Moon committed
96
97
98
99
100
    # Search in CMake Python package
    _cmake_bin: Optional[Path] = None
    try:
        import cmake
    except ImportError:
101
        pass
Tim Moon's avatar
Tim Moon committed
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
    else:
        cmake_dir = Path(cmake.__file__).resolve().parent
        _cmake_bin = cmake_dir / "data" / "bin" / "cmake"
        if not _cmake_bin.is_file():
            _cmake_bin = None

    # Search in path
    if _cmake_bin is None:
        _cmake_bin = shutil.which("cmake")
        if _cmake_bin is not None:
            _cmake_bin = Path(_cmake_bin).resolve()

    # Return executable if found
    if _cmake_bin is None:
        raise FileNotFoundError("Could not find CMake executable")
    return _cmake_bin

def found_ninja() -> bool:
    """"Check if Ninja is available"""
    return shutil.which("ninja") is not None

def found_pybind11() -> bool:
    """"Check if pybind11 is available"""

    # Check if Python package is installed
    try:
        import pybind11
    except ImportError:
130
        pass
Tim Moon's avatar
Tim Moon committed
131
132
    else:
        return True
133

Tim Moon's avatar
Tim Moon committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    # Check if CMake can find pybind11
    if not found_cmake():
        return False
    try:
        subprocess.run(
            [
                "cmake",
                "--find-package",
                "-DMODE=EXIST",
                "-DNAME=pybind11",
                "-DCOMPILER_ID=CXX",
                "-DLANGUAGE=CXX",
            ],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=True,
        )
    except (CalledProcessError, OSError):
152
        pass
Tim Moon's avatar
Tim Moon committed
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
195
196
197
198
199
200
201
202
203
204
205
    else:
        return True
    return False

def cuda_version() -> Tuple[int, ...]:
    """CUDA Toolkit version as a (major, minor) tuple

    Throws FileNotFoundError if NVCC is not found.

    """

    # Try finding NVCC
    nvcc_bin: Optional[Path] = None
    if nvcc_bin is None and os.getenv("CUDA_HOME"):
        # Check in CUDA_HOME
        cuda_home = Path(os.getenv("CUDA_HOME"))
        nvcc_bin = cuda_home / "bin" / "nvcc"
    if nvcc_bin is None:
        # Check if nvcc is in path
        nvcc_bin = shutil.which("nvcc")
        if nvcc_bin is not None:
            nvcc_bin = Path(nvcc_bin)
    if nvcc_bin is None:
        # Last-ditch guess in /usr/local/cuda
        cuda_home = Path("/usr/local/cuda")
        nvcc_bin = cuda_home / "bin" / "nvcc"
    if not nvcc_bin.is_file():
        raise FileNotFoundError(f"Could not find NVCC at {nvcc_bin}")

    # Query NVCC for version info
    output = subprocess.run(
        [nvcc_bin, "-V"],
        capture_output=True,
        check=True,
        universal_newlines=True,
    )
    match = re.search(r"release\s*([\d.]+)", output.stdout)
    version = match.group(1).split('.')
    return tuple(int(v) for v in version)

@lru_cache(maxsize=1)
def with_userbuffers() -> bool:
    """Check if userbuffers support is enabled"""
    if int(os.getenv("NVTE_WITH_USERBUFFERS", "0")):
        assert os.getenv("MPI_HOME"), \
            "MPI_HOME must be set if NVTE_WITH_USERBUFFERS=1"
        return True
    return False

@lru_cache(maxsize=1)
def frameworks() -> List[str]:
    """DL frameworks to build support for"""
    _frameworks: List[str] = []
206
    supported_frameworks = ["pytorch", "jax", "tensorflow", "paddle"]
Tim Moon's avatar
Tim Moon committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

    # Check environment variable
    if os.getenv("NVTE_FRAMEWORK"):
        _frameworks.extend(os.getenv("NVTE_FRAMEWORK").split(","))

    # Check command-line arguments
    for arg in sys.argv.copy():
        if arg.startswith("--framework="):
            _frameworks.extend(arg.replace("--framework=", "").split(","))
            sys.argv.remove(arg)

    # Detect installed frameworks if not explicitly specified
    if not _frameworks:
        try:
            import torch
        except ImportError:
            pass
        else:
            _frameworks.append("pytorch")
        try:
            import jax
        except ImportError:
            pass
        else:
            _frameworks.append("jax")
        try:
            import tensorflow
        except ImportError:
            pass
        else:
            _frameworks.append("tensorflow")
238
239
240
241
242
243
        try:
            import paddle
        except ImportError:
            pass
        else:
            _frameworks.append("paddle")
Tim Moon's avatar
Tim Moon committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257

    # Special framework names
    if "all" in _frameworks:
        _frameworks = supported_frameworks.copy()
    if "none" in _frameworks:
        _frameworks = []

    # Check that frameworks are valid
    _frameworks = [framework.lower() for framework in _frameworks]
    for framework in _frameworks:
        if framework not in supported_frameworks:
            raise ValueError(
                f"Transformer Engine does not support framework={framework}"
            )
258

Tim Moon's avatar
Tim Moon committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
    return _frameworks

# Call once in global scope since this function manipulates the
# command-line arguments. Future calls will use a cached value.
frameworks()

def setup_requirements() -> Tuple[List[str], List[str], List[str]]:
    """Setup Python dependencies

    Returns dependencies for build, runtime, and testing.

    """

    # Common requirements
    setup_reqs: List[str] = []
    install_reqs: List[str] = ["pydantic"]
    test_reqs: List[str] = ["pytest"]

    def add_unique(l: List[str], vals: Union[str, List[str]]) -> None:
        """Add entry to list if not already included"""
        if isinstance(vals, str):
            vals = [vals]
        for val in vals:
            if val not in l:
                l.append(val)

    # Requirements that may be installed outside of Python
    if not found_cmake():
        add_unique(setup_reqs, "cmake>=3.18")
    if not found_ninja():
        add_unique(setup_reqs, "ninja")

    # Framework-specific requirements
    if "pytorch" in frameworks():
293
        add_unique(install_reqs, ["torch", "flash-attn>=1.0.6, <=2.2.1"])
Tim Moon's avatar
Tim Moon committed
294
295
296
297
        add_unique(test_reqs, ["numpy", "onnxruntime", "torchvision"])
    if "jax" in frameworks():
        if not found_pybind11():
            add_unique(setup_reqs, "pybind11")
298
        add_unique(install_reqs, ["jax", "flax>=0.7.1"])
Tim Moon's avatar
Tim Moon committed
299
300
301
302
303
304
        add_unique(test_reqs, ["numpy", "praxis"])
    if "tensorflow" in frameworks():
        if not found_pybind11():
            add_unique(setup_reqs, "pybind11")
        add_unique(install_reqs, "tensorflow")
        add_unique(test_reqs, ["keras", "tensorflow_datasets"])
305
306
307
    if "paddle" in frameworks():
        add_unique(install_reqs, "paddlepaddle-gpu")
        add_unique(test_reqs, "numpy")
Tim Moon's avatar
Tim Moon committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

    return setup_reqs, install_reqs, test_reqs


class CMakeExtension(setuptools.Extension):
    """CMake extension module"""

    def __init__(
            self,
            name: str,
            cmake_path: Path,
            cmake_flags: Optional[List[str]] = None,
    ) -> None:
        super().__init__(name, sources=[])  # No work for base class
        self.cmake_path: Path = cmake_path
        self.cmake_flags: List[str] = [] if cmake_flags is None else cmake_flags

    def _build_cmake(self, build_dir: Path, install_dir: Path) -> None:

        # Make sure paths are str
        _cmake_bin = str(cmake_bin())
        cmake_path = str(self.cmake_path)
        build_dir = str(build_dir)
        install_dir = str(install_dir)

        # CMake configure command
        build_type = "Debug" if with_debug_build() else "Release"
        configure_command = [
            _cmake_bin,
            "-S",
            cmake_path,
            "-B",
            build_dir,
            f"-DCMAKE_BUILD_TYPE={build_type}",
            f"-DCMAKE_INSTALL_PREFIX={install_dir}",
343
        ]
Tim Moon's avatar
Tim Moon committed
344
345
346
347
348
349
350
351
352
353
354
        configure_command += self.cmake_flags
        if found_ninja():
            configure_command.append("-GNinja")
        try:
            import pybind11
        except ImportError:
            pass
        else:
            pybind11_dir = Path(pybind11.__file__).resolve().parent
            pybind11_dir = pybind11_dir / "share" / "cmake" / "pybind11"
            configure_command.append(f"-Dpybind11_DIR={pybind11_dir}")
355

Tim Moon's avatar
Tim Moon committed
356
357
358
        # CMake build and install commands
        build_command = [_cmake_bin, "--build", build_dir]
        install_command = [_cmake_bin, "--install", build_dir]
359

Tim Moon's avatar
Tim Moon committed
360
361
362
363
364
365
366
        # Run CMake commands
        for command in [configure_command, build_command, install_command]:
            print(f"Running command {' '.join(command)}")
            try:
                subprocess.run(command, cwd=build_dir, check=True)
            except (CalledProcessError, OSError) as e:
                raise RuntimeError(f"Error when running CMake: {e}")
367

Przemek Tredak's avatar
Przemek Tredak committed
368

Tim Moon's avatar
Tim Moon committed
369
370
371
# PyTorch extension modules require special handling
if "pytorch" in frameworks():
    from torch.utils.cpp_extension import BuildExtension
372
373
elif "paddle" in frameworks():
    from paddle.utils.cpp_extension import BuildExtension
Tim Moon's avatar
Tim Moon committed
374
375
else:
    from setuptools.command.build_ext import build_ext as BuildExtension
376

377

Tim Moon's avatar
Tim Moon committed
378
379
class CMakeBuildExtension(BuildExtension):
    """Setuptools command with support for CMake extension modules"""
380

Tim Moon's avatar
Tim Moon committed
381
382
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
383

Tim Moon's avatar
Tim Moon committed
384
    def run(self) -> None:
Przemek Tredak's avatar
Przemek Tredak committed
385

Tim Moon's avatar
Tim Moon committed
386
387
388
389
390
391
392
393
394
395
396
397
398
        # Build CMake extensions
        for ext in self.extensions:
            if isinstance(ext, CMakeExtension):
                print(f"Building CMake extension {ext.name}")
                with tempfile.TemporaryDirectory() as build_dir:
                    build_dir = Path(build_dir)
                    package_path = Path(self.get_ext_fullpath(ext.name))
                    install_dir = package_path.resolve().parent
                    ext._build_cmake(
                        build_dir=build_dir,
                        install_dir=install_dir,
                    )

399
400
401
402
403
404
405
406
407
        # Paddle requires linker search path for libtransformer_engine.so
        paddle_ext = None
        if "paddle" in frameworks():
            for ext in self.extensions:
                if "paddle" in ext.name:
                    ext.library_dirs.append(self.build_lib)
                    paddle_ext = ext
                    break

Tim Moon's avatar
Tim Moon committed
408
409
410
411
412
413
414
415
416
        # Build non-CMake extensions as usual
        all_extensions = self.extensions
        self.extensions = [
            ext for ext in self.extensions
            if not isinstance(ext, CMakeExtension)
        ]
        super().run()
        self.extensions = all_extensions

417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
        # Manually write stub file for Paddle extension
        if paddle_ext is not None:

            # Load libtransformer_engine.so to avoid linker errors
            for path in Path(self.build_lib).iterdir():
                if path.name.startswith("libtransformer_engine."):
                    ctypes.CDLL(str(path), mode=ctypes.RTLD_GLOBAL)

            # Figure out stub file path
            module_name = paddle_ext.name
            assert module_name.endswith("_pd_"), \
                "Expected Paddle extension module to end with '_pd_'"
            stub_name = module_name[:-4]  # remove '_pd_'
            stub_path = os.path.join(self.build_lib, stub_name + ".py")

            # Figure out library name
            # Note: This library doesn't actually exist. Paddle
            # internally reinserts the '_pd_' suffix.
            so_path = self.get_ext_fullpath(module_name)
            _, so_ext = os.path.splitext(so_path)
            lib_name = stub_name + so_ext

            # Write stub file
            print(f"Writing Paddle stub for {lib_name} into file {stub_path}")
            from paddle.utils.cpp_extension.extension_utils import custom_write_stub
            custom_write_stub(lib_name, stub_path)


Tim Moon's avatar
Tim Moon committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def setup_common_extension() -> CMakeExtension:
    """Setup CMake extension for common library

    Also builds JAX, TensorFlow, and userbuffers support if needed.

    """
    cmake_flags = []
    if "jax" in frameworks():
        cmake_flags.append("-DENABLE_JAX=ON")
    if "tensorflow" in frameworks():
        cmake_flags.append("-DENABLE_TENSORFLOW=ON")
    if with_userbuffers():
        cmake_flags.append("-DNVTE_WITH_USERBUFFERS=ON")
    return CMakeExtension(
Przemek Tredak's avatar
Przemek Tredak committed
459
        name="transformer_engine",
Tim Moon's avatar
Tim Moon committed
460
461
        cmake_path=root_path / "transformer_engine",
        cmake_flags=cmake_flags,
Przemek Tredak's avatar
Przemek Tredak committed
462
463
    )

464
465
466
def _all_files_in_dir(path):
    return list(path.iterdir())

Tim Moon's avatar
Tim Moon committed
467
468
def setup_pytorch_extension() -> setuptools.Extension:
    """Setup CUDA extension for PyTorch support"""
469

Tim Moon's avatar
Tim Moon committed
470
471
    # Source files
    src_dir = root_path / "transformer_engine" / "pytorch" / "csrc"
472
    extensions_dir = src_dir / "extensions"
Tim Moon's avatar
Tim Moon committed
473
474
475
    sources = [
        src_dir / "common.cu",
        src_dir / "ts_fp8_op.cpp",
476
477
    ] + \
    _all_files_in_dir(extensions_dir)
478

Tim Moon's avatar
Tim Moon committed
479
480
481
482
483
484
    # Header files
    include_dirs = [
        root_path / "transformer_engine" / "common" / "include",
        root_path / "transformer_engine" / "pytorch" / "csrc",
        root_path / "3rdparty" / "cudnn-frontend" / "include",
    ]
Przemek Tredak's avatar
Przemek Tredak committed
485

Tim Moon's avatar
Tim Moon committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
    # Compiler flags
    cxx_flags = ["-O3"]
    nvcc_flags = [
        "-O3",
        "-gencode",
        "arch=compute_70,code=sm_70",
        "-U__CUDA_NO_HALF_OPERATORS__",
        "-U__CUDA_NO_HALF_CONVERSIONS__",
        "-U__CUDA_NO_BFLOAT16_OPERATORS__",
        "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
        "-U__CUDA_NO_BFLOAT162_OPERATORS__",
        "-U__CUDA_NO_BFLOAT162_CONVERSIONS__",
        "--expt-relaxed-constexpr",
        "--expt-extended-lambda",
        "--use_fast_math",
    ]
Przemek Tredak's avatar
Przemek Tredak committed
502

Tim Moon's avatar
Tim Moon committed
503
    # Version-dependent CUDA options
Przemek Tredak's avatar
Przemek Tredak committed
504
    try:
Tim Moon's avatar
Tim Moon committed
505
506
507
        version = cuda_version()
    except FileNotFoundError:
        print("Could not determine CUDA Toolkit version")
Przemek Tredak's avatar
Przemek Tredak committed
508
    else:
Tim Moon's avatar
Tim Moon committed
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
        if version >= (11, 2):
            nvcc_flags.extend(["--threads", "4"])
        if version >= (11, 0):
            nvcc_flags.extend(["-gencode", "arch=compute_80,code=sm_80"])
        if version >= (11, 8):
            nvcc_flags.extend(["-gencode", "arch=compute_90,code=sm_90"])

    # userbuffers support
    if with_userbuffers():
        if os.getenv("MPI_HOME"):
            mpi_home = Path(os.getenv("MPI_HOME"))
            include_dirs.append(mpi_home / "include")
        cxx_flags.append("-DNVTE_WITH_USERBUFFERS")
        nvcc_flags.append("-DNVTE_WITH_USERBUFFERS")

    # Construct PyTorch CUDA extension
    sources = [str(path) for path in sources]
    include_dirs = [str(path) for path in include_dirs]
    from torch.utils.cpp_extension import CUDAExtension
    return CUDAExtension(
        name="transformer_engine_extensions",
        sources=sources,
        include_dirs=include_dirs,
        # libraries=["transformer_engine"], ### TODO (tmoon) Debug linker errors
        extra_compile_args={
            "cxx": cxx_flags,
            "nvcc": nvcc_flags,
        },
    )
Przemek Tredak's avatar
Przemek Tredak committed
538

539

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
def setup_paddle_extension() -> setuptools.Extension:
    """Setup CUDA extension for Paddle support"""

    # Source files
    src_dir = root_path / "transformer_engine" / "paddle" / "csrc"
    sources = [
        src_dir / "extensions.cu",
        src_dir / "common.cpp",
        src_dir / "custom_ops.cu",
    ]

    # Header files
    include_dirs = [
        root_path / "transformer_engine" / "common" / "include",
        root_path / "transformer_engine" / "paddle" / "csrc",
    ]

    # Compiler flags
    cxx_flags = ["-O3"]
    nvcc_flags = [
        "-O3",
        "-gencode",
        "arch=compute_70,code=sm_70",
        "-U__CUDA_NO_HALF_OPERATORS__",
        "-U__CUDA_NO_HALF_CONVERSIONS__",
        "-U__CUDA_NO_BFLOAT16_OPERATORS__",
        "-U__CUDA_NO_BFLOAT16_CONVERSIONS__",
        "-U__CUDA_NO_BFLOAT162_OPERATORS__",
        "-U__CUDA_NO_BFLOAT162_CONVERSIONS__",
        "--expt-relaxed-constexpr",
        "--expt-extended-lambda",
        "--use_fast_math",
    ]

    # Version-dependent CUDA options
    try:
        version = cuda_version()
    except FileNotFoundError:
        print("Could not determine CUDA Toolkit version")
    else:
        if version >= (11, 2):
            nvcc_flags.extend(["--threads", "4"])
        if version >= (11, 0):
            nvcc_flags.extend(["-gencode", "arch=compute_80,code=sm_80"])
        if version >= (11, 8):
            nvcc_flags.extend(["-gencode", "arch=compute_90,code=sm_90"])

    # Construct Paddle CUDA extension
    sources = [str(path) for path in sources]
    include_dirs = [str(path) for path in include_dirs]
    from paddle.utils.cpp_extension import CUDAExtension
    ext = CUDAExtension(
        sources=sources,
        include_dirs=include_dirs,
        libraries=["transformer_engine"],
        extra_compile_args={
            "cxx": cxx_flags,
            "nvcc": nvcc_flags,
        },
    )
    ext.name = "transformer_engine_paddle_pd_"
    return ext

Tim Moon's avatar
Tim Moon committed
603
def main():
604

Tim Moon's avatar
Tim Moon committed
605
606
607
608
    # Submodules to install
    packages = setuptools.find_packages(
        include=["transformer_engine", "transformer_engine.*"],
    )
609

Tim Moon's avatar
Tim Moon committed
610
611
    # Dependencies
    setup_requires, install_requires, test_requires = setup_requirements()
612

Tim Moon's avatar
Tim Moon committed
613
614
615
616
    # Extensions
    ext_modules = [setup_common_extension()]
    if "pytorch" in frameworks():
        ext_modules.append(setup_pytorch_extension())
Przemek Tredak's avatar
Przemek Tredak committed
617

618
619
620
    if "paddle" in frameworks():
        ext_modules.append(setup_paddle_extension())

Tim Moon's avatar
Tim Moon committed
621
622
623
624
625
626
627
628
629
630
631
632
633
    # Configure package
    setuptools.setup(
        name="transformer_engine",
        version=te_version(),
        packages=packages,
        description="Transformer acceleration library",
        ext_modules=ext_modules,
        cmdclass={"build_ext": CMakeBuildExtension},
        setup_requires=setup_requires,
        install_requires=install_requires,
        extras_require={"test": test_requires},
        license_files=("LICENSE",),
    )
Przemek Tredak's avatar
Przemek Tredak committed
634
635


Tim Moon's avatar
Tim Moon committed
636
637
if __name__ == "__main__":
    main()