File size: 5,141 Bytes
d2136d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c076111
d2136d7
 
c076111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2136d7
 
4c198ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2136d7
51f848e
 
 
 
 
 
d2136d7
51f848e
 
 
 
 
 
d2136d7
 
973da54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2136d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Force the lalamo attention implementation when the GPU cannot run Pallas.

lalamo's inference config defaults to the Pallas-Triton flash attention kernel
(``MixerForwardPassConfig.for_inference``). Pallas-Triton needs a Triton backend
that T4 (compute capability 7.5) does not provide, so the first forward fails
during XLA compilation even with ``--xla_gpu_enable_triton_gemm=false``.

``UZU_ATTENTION_IMPL=xla`` switches the mixer config to the plain XLA path.
``pallas`` forces the default back. Anything else (including unset) keeps the
config as-is.
"""

from __future__ import annotations

import os
import subprocess

ENV_VAR = "UZU_ATTENTION_IMPL"
# BF16 tensor cores start at Ampere. On Turing the XLA dot lowers to
# ALG_DOT_BF16_BF16_F32, which cuBLAS does not implement, so a bf16 forward
# dies inside the attention kernel instead of at startup.
BF16_MIN_CAPABILITY = 8.0


def gpu_capabilities() -> list[float]:
    """Return the compute capability of every visible GPU (empty off-GPU)."""
    try:
        result = subprocess.run(
            ["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"],
            text=True,
            capture_output=True,
            check=False,
            timeout=20,
        )
    except (OSError, subprocess.TimeoutExpired):
        return []
    caps = []
    if result.returncode != 0:
        return caps
    for line in (result.stdout or "").splitlines():
        try:
            caps.append(float(line.strip()))
        except ValueError:
            continue
    return caps


def bf16_block_reason(dtype: str, capabilities: list[float]) -> str | None:
    """Return why this dtype cannot run here, or None when it can."""
    if dtype != "bfloat16" or not capabilities:
        return None
    old = [capability for capability in capabilities if capability < BF16_MIN_CAPABILITY]
    if not old:
        return None
    return (
        f"GPU compute capability {old[0]:.1f} has no BF16 matmul "
        "(ALG_DOT_BF16_BF16_F32 is unimplemented); use float32. "
        "UZU_ATTENTION_IMPL=xla does not help: it only avoids Pallas-Triton."
    )



def enter_mesh(sharding):
    """Activate the sharding mesh for the rest of the process.

    With ``--parallel tensor`` the mesh has 2 devices, and any ``jax.jit``
    launched outside a mesh context fails with "Length of device assignment 1
    is not equal to the size of the mesh 2; enter your jit into a mesh context
    via jax.set_mesh". A single-device mesh never raises, which is why CPU
    lanes never showed this.
    """
    mesh = getattr(sharding, "mesh", None)
    if mesh is None or getattr(mesh, "empty", False):
        return None
    import jax

    manager = jax.set_mesh(mesh)
    manager.__enter__()
    return manager


def requested() -> str | None:
    """Explicit env wins; otherwise pick xla automatically on pre-Ampere.

    Pallas-Triton needs cc >= 8.0. Scripts that do not go through run_lane
    (Modal jobs, make_qad_dataset -> yaqa_calibration) used to fall back to
    Pallas and die at the first forward, so the device decides for them.
    """
    value = os.environ.get(ENV_VAR, "").strip().lower()
    if value in ("xla", "pallas"):
        return value
    capabilities = gpu_capabilities()
    if any(capability < BF16_MIN_CAPABILITY for capability in capabilities):
        return "xla"
    return None


def force_float32_activations(config):
    """Use f32 activations on GPUs without BF16 tensor cores.

    ``Model.load(..., dtype=float32)`` only fixes the weights: the embedding
    forward config still defaults to ``activation_dtype=bfloat16``, so the
    residual stream (and therefore attention's q/k/v) stays bf16 and the dot
    lowers to ALG_DOT_BF16_BF16_F32, which Turing does not implement.
    """
    capabilities = gpu_capabilities()
    if not capabilities or not any(capability < BF16_MIN_CAPABILITY for capability in capabilities):
        return config

    from dataclasses import replace

    import jax.numpy as jnp

    embedding = config.embedding_forward_pass_config
    if embedding.activation_dtype == jnp.float32:
        return config
    return replace(
        config,
        embedding_forward_pass_config=replace(embedding, activation_dtype=jnp.float32),
    )


def apply_attention_env(config):
    """Return config with the attention implementation overridden, if requested."""
    mode = requested()
    if mode is None:
        return config

    from dataclasses import replace

    from lalamo.modules import AttentionImplementation

    target = AttentionImplementation.XLA if mode == "xla" else AttentionImplementation.PALLAS
    transformer = config.transformer_forward_pass_config
    mixer = transformer.mixer_forward_pass_config
    if getattr(mixer, "attention_implementation", None) == target:
        return config
    return replace(
        config,
        transformer_forward_pass_config=replace(
            transformer,
            mixer_forward_pass_config=replace(mixer, attention_implementation=target),
        ),
    )


def describe() -> str:
    mode = requested()
    return f"attention={mode or 'default'}"