jax.py 2.34 KB
Newer Older
1
2
3
4
# Copyright (c) 2022-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# See LICENSE for license information.

5
6
"""JAX related extensions."""
import os
7
8
9
from pathlib import Path

import setuptools
10
from glob import glob
11

12
from .utils import cuda_path, all_files_in_dir
13
14
from typing import List

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

def xla_path() -> str:
    """XLA root path lookup.
    Throws FileNotFoundError if XLA source is not found."""

    try:
        from jax.extend import ffi
    except ImportError:
        if os.getenv("XLA_HOME"):
            xla_home = Path(os.getenv("XLA_HOME"))
        else:
            xla_home = "/opt/xla"
    else:
        xla_home = ffi.include_dir()

    if not os.path.isdir(xla_home):
        raise FileNotFoundError("Could not find xla source.")
    return xla_home
33

34
35
36
37
38
39
40
41
42

def setup_jax_extension(
    csrc_source_files,
    csrc_header_files,
    common_header_files,
) -> setuptools.Extension:
    """Setup PyBind11 extension for JAX support"""
    # Source files
    csrc_source_files = Path(csrc_source_files)
43
    extensions_dir = csrc_source_files / "extensions"
44
45
    sources = [
        csrc_source_files / "utils.cu",
Phuong Nguyen's avatar
Phuong Nguyen committed
46
    ] + all_files_in_dir(extensions_dir, ".cpp")
47
48
49

    # Header files
    cuda_home, _ = cuda_path()
50
    xla_home = xla_path()
51
52
53
54
55
56
    include_dirs = [
        cuda_home / "include",
        common_header_files,
        common_header_files / "common",
        common_header_files / "common" / "include",
        csrc_header_files,
57
        xla_home,
58
59
60
    ]

    # Compile flags
61
62
    cxx_flags = ["-O3"]
    nvcc_flags = ["-O3"]
63
64
65
66
67
68
69
70
71

    # Define TE/JAX as a Pybind11Extension
    from pybind11.setup_helpers import Pybind11Extension

    class Pybind11CUDAExtension(Pybind11Extension):
        """Modified Pybind11Extension to allow combined CXX + NVCC compile flags."""

        def _add_cflags(self, flags: List[str]) -> None:
            if isinstance(self.extra_compile_args, dict):
72
                cxx_flags = self.extra_compile_args.pop("cxx", [])
73
                cxx_flags += flags
74
                self.extra_compile_args["cxx"] = cxx_flags
75
76
77
78
79
80
81
            else:
                self.extra_compile_args[:0] = flags

    return Pybind11CUDAExtension(
        "transformer_engine_jax",
        sources=[str(path) for path in sources],
        include_dirs=[str(path) for path in include_dirs],
82
        extra_compile_args={"cxx": cxx_flags, "nvcc": nvcc_flags},
83
    )