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

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

import setuptools

11
from .utils import get_cuda_include_dirs, all_files_in_dir, debug_build_enabled
12
13
from typing import List

14

15
16
17
18
19
20
21
22
23
24
def install_requirements() -> List[str]:
    """Install dependencies for TE/JAX extensions."""
    return ["jax[cuda12]", "flax>=0.7.1"]


def test_requirements() -> List[str]:
    """Test dependencies for TE/JAX extensions."""
    return ["numpy"]


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
42

43
44
45
46
47
48
49
50
51

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)
52
    extensions_dir = csrc_source_files / "extensions"
53
    sources = all_files_in_dir(extensions_dir, name_extension="cpp")
54
55

    # Header files
56
57
58
59
60
61
62
63
64
65
    include_dirs = get_cuda_include_dirs()
    include_dirs.extend(
        [
            common_header_files,
            common_header_files / "common",
            common_header_files / "common" / "include",
            csrc_header_files,
            xla_path(),
        ]
    )
66
67

    # Compile flags
68
    cxx_flags = ["-O3"]
69
70
71
72
73
    if debug_build_enabled():
        cxx_flags.append("-g")
        cxx_flags.append("-UNDEBUG")
    else:
        cxx_flags.append("-g0")
74
75
76
77

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

78
79
    class Pybind11CPPExtension(Pybind11Extension):
        """Modified Pybind11Extension to allow custom CXX flags."""
80
81
82

        def _add_cflags(self, flags: List[str]) -> None:
            if isinstance(self.extra_compile_args, dict):
83
                cxx_flags = self.extra_compile_args.pop("cxx", [])
84
                cxx_flags += flags
85
                self.extra_compile_args["cxx"] = cxx_flags
86
87
88
            else:
                self.extra_compile_args[:0] = flags

89
    return Pybind11CPPExtension(
90
91
92
        "transformer_engine_jax",
        sources=[str(path) for path in sources],
        include_dirs=[str(path) for path in include_dirs],
93
        extra_compile_args={"cxx": cxx_flags},
94
    )