__init__.py 11.8 KB
Newer Older
1
import ctypes
2
import logging
3
import os
EduardDurech's avatar
EduardDurech committed
4
5
import shutil
from pathlib import Path
6
from typing import List
7

8
9
import torch

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
logger = logging.getLogger(__name__)


def _get_compute_capability():
    """Get the compute capability of the current GPU."""
    if not torch.cuda.is_available():
        return None

    # Get the current device
    device = torch.cuda.current_device()
    properties = torch.cuda.get_device_properties(device)

    # Return as integer (major * 10 + minor)
    return properties.major * 10 + properties.minor


def _filter_compiled_extensions(file_list):
    """Filter and prioritize compiled extensions over Python source files."""
    compiled_extensions = [".so", ".pyd", ".dll"]  # Common compiled extension suffixes
    compiled_files = []
    other_files = []

    for file_path in file_list:
        path = Path(file_path)
        # Check if it's a compiled extension (including complex names like .abi3.so, .cpython-312.so)
        if any(
            str(path).endswith(ext) or ext in str(path) for ext in compiled_extensions
        ):
            compiled_files.append(file_path)
        else:
            other_files.append(file_path)

    # Return compiled files first, then others
    return compiled_files + other_files


def _load_architecture_specific_ops():
    """Load the appropriate common_ops library based on GPU architecture."""
    import importlib.util
    import sys
    from pathlib import Path

    compute_capability = _get_compute_capability()
    logger.debug(
        f"[sgl_kernel] GPU Detection: compute_capability = {compute_capability}"
    )

    # Get the directory where sgl_kernel is installed
    sgl_kernel_dir = Path(__file__).parent
    logger.debug(f"[sgl_kernel] sgl_kernel directory: {sgl_kernel_dir}")

    # Determine which version to load based on GPU architecture
    if compute_capability == 90:
        ops_subdir = "sm90"
        variant_name = "SM90 (Hopper/H100 with fast math optimization)"
    elif compute_capability is not None:
        ops_subdir = "sm100"
        variant_name = f"SM{compute_capability} (precise math for compatibility)"
    else:
        ops_subdir = "sm100"
        variant_name = "CPU/No GPU detected (using precise math)"

    # Look for the compiled module with any valid extension
    import glob

    ops_pattern = str(sgl_kernel_dir / ops_subdir / "common_ops.*")
    raw_matching_files = glob.glob(ops_pattern)
    matching_files = _filter_compiled_extensions(raw_matching_files)

    logger.debug(f"[sgl_kernel] Attempting to load {variant_name}")
    logger.debug(f"[sgl_kernel] Looking for library matching pattern: {ops_pattern}")
    logger.debug(f"[sgl_kernel] Found files: {raw_matching_files}")
    logger.debug(f"[sgl_kernel] Prioritized files: {matching_files}")

84
85
    previous_import_errors: List[Exception] = []

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    # Try to load from the architecture-specific directory
    if matching_files:
        ops_path = Path(matching_files[0])  # Use the first prioritized file
        logger.debug(f"[sgl_kernel] Found architecture-specific library: {ops_path}")
        try:
            # Load the module from specific path using importlib
            spec = importlib.util.spec_from_file_location("common_ops", str(ops_path))
            if spec is None:
                raise ImportError(f"Could not create module spec for {ops_path}")

            common_ops = importlib.util.module_from_spec(spec)
            if spec.loader is None:
                raise ImportError(f"Module spec has no loader for {ops_path}")

            logger.debug(f"[sgl_kernel] Loading module from {ops_path}...")
            spec.loader.exec_module(common_ops)
            logger.debug(f"[sgl_kernel] ✓ Successfully loaded {variant_name}")
            logger.debug(f"[sgl_kernel] ✓ Module file: {common_ops.__file__}")
            return common_ops

        except Exception as e:
107
            previous_import_errors.append(e)
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
            logger.debug(
                f"[sgl_kernel] ✗ Failed to load from {ops_path}: {type(e).__name__}: {e}"
            )
            # Continue to fallback
    else:
        logger.debug(
            f"[sgl_kernel] ✗ Architecture-specific library not found matching pattern: {ops_pattern}"
        )

    # Try alternative directory (in case installation structure differs)
    alt_pattern = str(sgl_kernel_dir / "common_ops.*")
    raw_alt_files = glob.glob(alt_pattern)
    alt_matching_files = _filter_compiled_extensions(raw_alt_files)
    logger.debug(f"[sgl_kernel] Attempting fallback: looking for pattern {alt_pattern}")
    logger.debug(f"[sgl_kernel] Found fallback files: {raw_alt_files}")
    logger.debug(f"[sgl_kernel] Prioritized fallback files: {alt_matching_files}")

    if alt_matching_files:
        alt_path = Path(alt_matching_files[0])  # Use the first prioritized file
        logger.debug(f"[sgl_kernel] Found fallback library: {alt_path}")
        try:
            spec = importlib.util.spec_from_file_location("common_ops", str(alt_path))
            if spec is None:
                raise ImportError(f"Could not create module spec for {alt_path}")

            common_ops = importlib.util.module_from_spec(spec)
            if spec.loader is None:
                raise ImportError(f"Module spec has no loader for {alt_path}")

            logger.debug(f"[sgl_kernel] Loading fallback module from {alt_path}...")
            spec.loader.exec_module(common_ops)
            logger.debug(f"[sgl_kernel] ✓ Successfully loaded fallback library")
            logger.debug(f"[sgl_kernel] ✓ Module file: {common_ops.__file__}")
            return common_ops

        except Exception as e:
144
            previous_import_errors.append(e)
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
            logger.debug(
                f"[sgl_kernel] ✗ Failed to load fallback from {alt_path}: {type(e).__name__}: {e}"
            )
    else:
        logger.debug(
            f"[sgl_kernel] ✗ Fallback library not found matching pattern: {alt_pattern}"
        )

    # Final attempt: try standard Python import (for backward compatibility)
    logger.debug(
        f"[sgl_kernel] Final attempt: trying standard Python import 'common_ops'"
    )
    try:
        import common_ops

        logger.debug(f"[sgl_kernel] ✓ Successfully imported via standard Python import")
        logger.debug(f"[sgl_kernel] ✓ Module file: {common_ops.__file__}")
        return common_ops
    except ImportError as e:
164
        previous_import_errors.append(e)
165
166
        logger.debug(f"[sgl_kernel] ✗ Standard Python import failed: {e}")

167
168
169
170
    attempt_error_msg = "\n".join(
        f"- {type(err).__name__}: {err}" for err in previous_import_errors
    )

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
    # All attempts failed
    error_msg = f"""
[sgl_kernel] CRITICAL: Could not load any common_ops library!

Attempted locations:
1. Architecture-specific pattern: {ops_pattern} - found files: {matching_files}
2. Fallback pattern: {alt_pattern} - found files: {alt_matching_files}
3. Standard Python import: common_ops - failed

GPU Info:
- Compute capability: {compute_capability}
- Expected variant: {variant_name}

Please ensure sgl_kernel is properly installed with:
pip install --upgrade sgl_kernel
186
187
188

Error details from previous import attempts:
{attempt_error_msg}
189
190
191
192
193
194
195
196
197
198
"""
    logger.debug(error_msg)
    raise ImportError(error_msg)


# Initialize the ops library based on current GPU
logger.debug("[sgl_kernel] Initializing architecture-specific operator library...")
common_ops = _load_architecture_specific_ops()
logger.debug("[sgl_kernel] ✓ Operator library initialization complete")

199

EduardDurech's avatar
EduardDurech committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# copy & modify from torch/utils/cpp_extension.py
def _find_cuda_home():
    """Find the CUDA install path."""
    # Guess #1
    cuda_home = os.environ.get("CUDA_HOME") or os.environ.get("CUDA_PATH")
    if cuda_home is None:
        # Guess #2
        nvcc_path = shutil.which("nvcc")
        if nvcc_path is not None:
            cuda_home = os.path.dirname(os.path.dirname(nvcc_path))
        else:
            # Guess #3
            cuda_home = "/usr/local/cuda"
    return cuda_home


216
if torch.version.cuda is not None:
EduardDurech's avatar
EduardDurech committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    cuda_home = Path(_find_cuda_home())

    if (cuda_home / "lib").is_dir():
        cuda_path = cuda_home / "lib"
    elif (cuda_home / "lib64").is_dir():
        cuda_path = cuda_home / "lib64"
    else:
        # Search for 'libcudart.so.12' in subdirectories
        for path in cuda_home.rglob("libcudart.so.12"):
            cuda_path = path.parent
            break
        else:
            raise RuntimeError("Could not find CUDA lib directory.")

    cuda_include = (cuda_path / "libcudart.so.12").resolve()
    if cuda_include.exists():
        ctypes.CDLL(str(cuda_include), mode=ctypes.RTLD_GLOBAL)
234

235
from sgl_kernel.allreduce import *
236
237
238
239
from sgl_kernel.attention import (
    cutlass_mla_decode,
    cutlass_mla_get_workspace_size,
    lightning_attention_decode,
Yineng Zhang's avatar
Yineng Zhang committed
240
    merge_state,
241
    merge_state_v2,
242
)
243
from sgl_kernel.cutlass_moe import cutlass_w4a8_moe_mm, get_cutlass_w4a8_moe_mm_data
244
from sgl_kernel.elementwise import (
245
    FusedSetKVBufferArg,
246
    apply_rope_with_cos_sin_cache_inplace,
247
    concat_mla_absorb_q,
248
    concat_mla_k,
249
    copy_to_gpu_no_ce,
250
    downcast_fp8,
251
252
253
254
255
256
257
258
    fused_add_rmsnorm,
    gelu_and_mul,
    gelu_tanh_and_mul,
    gemma_fused_add_rmsnorm,
    gemma_rmsnorm,
    rmsnorm,
    silu_and_mul,
)
259
from sgl_kernel.expert_specialization import es_fp8_blockwise_scaled_grouped_mm
260
from sgl_kernel.fused_moe import fused_marlin_moe
261
from sgl_kernel.gemm import (
262
    awq_dequantize,
263
    bmm_fp8,
Trevor Morris's avatar
Trevor Morris committed
264
    cutlass_scaled_fp4_mm,
265
    dsv3_fused_a_gemm,
266
    dsv3_router_gemm,
267
268
    fp8_blockwise_scaled_mm,
    fp8_scaled_mm,
269
270
271
    gptq_gemm,
    gptq_marlin_gemm,
    gptq_shuffle,
272
    int8_scaled_mm,
HandH1998's avatar
HandH1998 committed
273
274
    qserve_w4a8_per_chn_gemm,
    qserve_w4a8_per_group_gemm,
275
    scaled_fp4_experts_quant,
276
    scaled_fp4_grouped_quant,
Trevor Morris's avatar
Trevor Morris committed
277
    scaled_fp4_quant,
278
    sgl_per_tensor_quant_fp8,
279
    sgl_per_token_group_quant_8bit,
280
281
    sgl_per_token_group_quant_fp8,
    sgl_per_token_group_quant_int8,
282
    sgl_per_token_quant_fp8,
283
    shuffle_rows,
284
    silu_and_mul_scaled_fp4_grouped_quant,
285
)
286
from sgl_kernel.grammar import apply_token_bitmask_inplace_cuda
287
288
289
290
291
292
293
from sgl_kernel.hadamard import (
    hadamard_transform,
    hadamard_transform_12n,
    hadamard_transform_20n,
    hadamard_transform_28n,
    hadamard_transform_40n,
)
294
295
296
297
298
299
from sgl_kernel.kvcacheio import (
    transfer_kv_all_layer,
    transfer_kv_all_layer_mla,
    transfer_kv_per_layer,
    transfer_kv_per_layer_mla,
)
300
from sgl_kernel.mamba import causal_conv1d_fwd, causal_conv1d_update
301
302
303
304
305
from sgl_kernel.marlin import (
    awq_marlin_moe_repack,
    awq_marlin_repack,
    gptq_marlin_repack,
)
306
from sgl_kernel.memory import set_kv_buffer_kernel
307
from sgl_kernel.moe import (
308
    apply_shuffle_mul_sum,
309
    cutlass_fp4_group_mm,
310
311
312
    fp8_blockwise_scaled_grouped_mm,
    moe_align_block_size,
    moe_fused_gate,
313
    moe_sum,
314
    moe_sum_reduce,
315
    prepare_moe_input,
316
317
    topk_softmax,
)
318
319
320
321
322
323
324
325
from sgl_kernel.quantization import (
    ggml_dequantize,
    ggml_moe_a8,
    ggml_moe_a8_vec,
    ggml_moe_get_block_size,
    ggml_mul_mat_a8,
    ggml_mul_mat_vec_a8,
)
326
from sgl_kernel.sampling import (
327
    min_p_sampling_from_probs,
328
    top_k_mask_logits,
329
    top_k_renorm_prob,
330
    top_k_top_p_sampling_from_logits,
331
332
333
334
    top_k_top_p_sampling_from_probs,
    top_p_renorm_prob,
    top_p_sampling_from_probs,
)
335
336
from sgl_kernel.speculative import (
    build_tree_kernel_efficient,
337
    reconstruct_indices_from_tree_mask,
338
339
340
341
    segment_packbits,
    tree_speculative_sampling_target_only,
    verify_tree_greedy,
)
342
343
344
345
346
347
from sgl_kernel.top_k import (
    fast_topk,
    fast_topk_transform_fused,
    fast_topk_transform_ragged_fused,
    fast_topk_v2,
)
348
from sgl_kernel.version import __version__
349

350
351
352
if torch.version.hip is not None:
    from sgl_kernel.elementwise import gelu_quick

353
354
355
356
357
358
359
360
361
362
363

def create_greenctx_stream_by_value(*args, **kwargs):
    from sgl_kernel.spatial import create_greenctx_stream_by_value as _impl

    return _impl(*args, **kwargs)


def get_sm_available(*args, **kwargs):
    from sgl_kernel.spatial import get_sm_available as _impl

    return _impl(*args, **kwargs)